lang
stringclasses 2
values | license
stringclasses 13
values | stderr
stringlengths 0
343
| commit
stringlengths 40
40
| returncode
int64 0
128
| repos
stringlengths 6
87.7k
| new_contents
stringlengths 0
6.23M
| new_file
stringlengths 3
311
| old_contents
stringlengths 0
6.23M
| message
stringlengths 6
9.1k
| old_file
stringlengths 3
311
| subject
stringlengths 0
4k
| git_diff
stringlengths 0
6.31M
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
Java | apache-2.0 | error: pathspec 'yuannews/src/main/java/cn/edu/hpu/yuan/yuannews/main/util/NotificationUtil.java' did not match any file(s) known to git
| b9f93628b969f02bd54c1ca877346d416e3a6b49 | 1 | LABELNET/YuanNewsForAndroid | package cn.edu.hpu.yuan.yuannews.main.util;
import android.app.Notification;
import android.content.Context;
/**
* Created by yuan on 16-5-18.
* 通知util - 实现通知的初始化,更新,删除操作;
* (1)显示通知
* (2)隐藏通知
* (3)更新通知实现
*/
public class NotificationUtil {
private Notification.Builder builder;
private static NotificationUtil notificationUtil;
public NotificationUtil(Context context) {
builder=new Notification.Builder(context);
}
public static NotificationUtil newInstance(Context context) {
NotificationUtil util = new NotificationUtil(context);
return util;
}
}
| yuannews/src/main/java/cn/edu/hpu/yuan/yuannews/main/util/NotificationUtil.java | 【EDIT】添加通知的util类
| yuannews/src/main/java/cn/edu/hpu/yuan/yuannews/main/util/NotificationUtil.java | 【EDIT】添加通知的util类 | <ide><path>uannews/src/main/java/cn/edu/hpu/yuan/yuannews/main/util/NotificationUtil.java
<add>package cn.edu.hpu.yuan.yuannews.main.util;
<add>
<add>import android.app.Notification;
<add>import android.content.Context;
<add>
<add>/**
<add> * Created by yuan on 16-5-18.
<add> * 通知util - 实现通知的初始化,更新,删除操作;
<add> * (1)显示通知
<add> * (2)隐藏通知
<add> * (3)更新通知实现
<add> */
<add>public class NotificationUtil {
<add>
<add>
<add> private Notification.Builder builder;
<add> private static NotificationUtil notificationUtil;
<add>
<add> public NotificationUtil(Context context) {
<add> builder=new Notification.Builder(context);
<add> }
<add>
<add> public static NotificationUtil newInstance(Context context) {
<add> NotificationUtil util = new NotificationUtil(context);
<add> return util;
<add> }
<add>
<add>
<add>} |
|
JavaScript | mit | d22be563ea455c8899c430c5634c444471dfefac | 0 | boof/vizard,boof/vizard,boof/vizard | // Note: This filter only works for SCRIPT tags with known TYPE values!
(function(filter) {
// script types could be evaluated
var SCRIPT_TYPEs = /type=["'](?:text|application)\/(?:x-)?(?:j(?:ava)?|ecma)script["']/g
, noSCRIPT_TYPE = 'type="text/noscript+javascript"'
, noSCRIPT_TYPEs = /type="text\/noscript\+javascript"/g
, SCRIPT_TYPE = 'type="text/javascript"';
function disableSCRIPT( source ) {
return source.replace( SCRIPT_TYPEs, noSCRIPT_TYPE );
}
function enableSCRIPT( source ) {
return source.replace( noSCRIPT_TYPEs, SCRIPT_TYPE);
}
filter.disableSCRIPT = disableSCRIPT;
filter.enableSCRIPT = enableSCRIPT;
})(Vizard.Filter);
| source/filter/noscript.js | // Note: This filter only works for SCRIPT tags with known TYPE values!
(function(filter) {
// script types could be evaluated
var SCRIPT_TYPEs = /type=["'](?:text|application)\/(?:x-)?(?:j(?:ava)?|ecma)script["']/g
, noSCRIPT_TYPE = 'type="text/noscript+javascript"';
// disable SCRIPTs...
function noSCRIPT( source ) {
return source.replace( SCRIPT_TYPEs, noSCRIPT_TYPE );
}
filter.noSCRIPT = noSCRIPT;
})(Vizard.Filter);
| Completed input and output functions for noscript filter.
| source/filter/noscript.js | Completed input and output functions for noscript filter. | <ide><path>ource/filter/noscript.js
<ide> (function(filter) {
<ide>
<ide> // script types could be evaluated
<del> var SCRIPT_TYPEs = /type=["'](?:text|application)\/(?:x-)?(?:j(?:ava)?|ecma)script["']/g
<del> , noSCRIPT_TYPE = 'type="text/noscript+javascript"';
<add> var SCRIPT_TYPEs = /type=["'](?:text|application)\/(?:x-)?(?:j(?:ava)?|ecma)script["']/g
<add> , noSCRIPT_TYPE = 'type="text/noscript+javascript"'
<add> , noSCRIPT_TYPEs = /type="text\/noscript\+javascript"/g
<add> , SCRIPT_TYPE = 'type="text/javascript"';
<ide>
<del> // disable SCRIPTs...
<del> function noSCRIPT( source ) {
<add> function disableSCRIPT( source ) {
<ide> return source.replace( SCRIPT_TYPEs, noSCRIPT_TYPE );
<ide> }
<add> function enableSCRIPT( source ) {
<add> return source.replace( noSCRIPT_TYPEs, SCRIPT_TYPE);
<add> }
<ide>
<del> filter.noSCRIPT = noSCRIPT;
<add> filter.disableSCRIPT = disableSCRIPT;
<add> filter.enableSCRIPT = enableSCRIPT;
<ide>
<ide> })(Vizard.Filter); |
|
Java | bsd-3-clause | 0081733f2113a6f58a3126b6a74ea16103274bea | 0 | flexgen/flexgen | /*
FlexGen : Flexible Map Generator Library
Copyright (C) 2009 - Jeffrey J. Weston <[email protected]>
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 FlexGen project 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.
*/
package org.flexgen.map;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/**
* Class containing logic for randomly generating a map using a specified set of map tile types.
*/
public class MapGenerator
{
/**
* Data structure containing the map. Maps map tile locations to map tiles.
*/
private final Map< MapTileLocation, MapTile > map;
/**
* List of listeners for the event of adding a map tile.
*/
private final List< MapTileAddedListener > mapTileAddedListeners;
/**
* The size of the map unit array that defines the map tile types used by this map generator.
*/
private final int tileSize;
/**
* Smallest possible X coordinate for map tiles in the map.
*/
private final int minX;
/**
* Smallest possible Y coordinate for map tiles in the map.
*/
private final int minY;
/**
* Largest possible X coordinate for map tiles in the map.
*/
private final int maxX;
/**
* Largest possible Y coordinate for map tiles in the map.
*/
private final int maxY;
/**
* Construct a map generator.
*
* @param mapTileTypes
* Array of map tile types that define the available map tile types for randomly
* generating the map. Cannot be null. Must contain at least one element. No element
* can be null. Cannot contain two or more elements that are identical. All map tile
* types in the array must be the same size.
* @param minX
* Smallest possible X coordinate for map tiles in the map.
* @param minY
* Smallest possible Y coordinate for map tiles in the map.
* @param maxX
* Largest possible X coordinate for map tiles in the map. Must be greater than or
* equal to minX.
* @param maxY
* Largest possible Y coordinate for map tiles in the map. Must be greater than or
* equal to minY.
*/
public MapGenerator( MapTileType[] mapTileTypes, int minX, int minY, int maxX, int maxY )
{
if ( mapTileTypes == null )
{
throw new IllegalArgumentException( "Parameter 'mapTileTypes' cannot be null." );
}
if ( mapTileTypes.length == 0 )
{
throw new IllegalArgumentException(
"Parameter 'mapTileTypes' must contain at least one element." );
}
int tileSize = 0;
for ( int i = 0; i < mapTileTypes.length; i++ )
{
// check for a null element
if ( mapTileTypes[ i ] == null )
{
throw new IllegalArgumentException(
"Parameter 'mapTileTypes' must not contain any null elements." );
}
// check for a duplicate element
for ( int j = i + 1; j < mapTileTypes.length; j++ )
{
if ( mapTileTypes[ i ].equals( mapTileTypes[ j ] ))
{
throw new IllegalArgumentException(
"Parameter 'mapTileTypes' must not contain any duplicate elements." );
}
}
// check to see that all elements are the same size
if ( tileSize == 0 )
{
tileSize = mapTileTypes[ i ].getSize();
}
else
{
if ( tileSize != mapTileTypes[ i ].getSize() )
{
throw new IllegalArgumentException( "All map tile types in parameter " +
"'mapTileTypes' must be the same size." );
}
}
}
if ( maxX < minX )
{
throw new IllegalArgumentException(
"Parameter 'maxX' must be greater than or equal to parameter 'minX'." );
}
if ( maxY < minY )
{
throw new IllegalArgumentException(
"Parameter 'maxY' must be greater than or equal to parameter 'minY'." );
}
this.map = new HashMap< MapTileLocation, MapTile >();
this.mapTileAddedListeners = new LinkedList< MapTileAddedListener >();
this.tileSize = tileSize;
this.minX = minX;
this.minY = minY;
this.maxX = maxX;
this.maxY = maxY;
}
/**
* Get the size of the map unit array that defines the map tile types used by this map
* generator.
*
* @return The size of the map unit array that defines the map tile types used by this map
* generator.
*/
public int getTileSize()
{
return tileSize;
}
/**
* Get the smallest possible X coordinate for map tiles in the map.
*
* @return The smallest possible X coordinate for map tiles in the map.
*/
public int getMinX()
{
return minX;
}
/**
* Get the smallest possible Y coordinate for map tiles in the map.
*
* @return The smallest possible Y coordinate for map tiles in the map.
*/
public int getMinY()
{
return minY;
}
/**
* Get the largest possible X coordinate for map tiles in the map.
*
* @return The largest possible X coordinate for map tiles in the map.
*/
public int getMaxX()
{
return maxX;
}
/**
* Get the largest possible Y coordinate for map tiles in the map.
*
* @return The largest possible Y coordinate for map tiles in the map.
*/
public int getMaxY()
{
return maxY;
}
/**
* Add a new listener for the event of adding a map tile to the map.
*
* @param mapTileAddedListener
* The listener to add.
*/
public void addMapTileAddedListener( MapTileAddedListener mapTileAddedListener )
{
mapTileAddedListeners.add( mapTileAddedListener );
}
/**
* Get the map tile at a specified location.
*
* @param mapTileLocation
* Location for which to get the map tile.
*
* @return The map tile at a specified location.
*/
public MapTile getMapTile( MapTileLocation mapTileLocation )
{
if ( mapTileLocation == null )
{
throw new IllegalArgumentException( "Parameter 'mapTileLocation' cannot be null." );
}
return map.get( mapTileLocation );
}
/**
* Add a map tile to the map at the specified location.
*
* @param mapTileLocation
* Location at which to add the map tile.
* @param mapTile
* Map tile to add.
*/
public void addMapTile( MapTileLocation mapTileLocation, MapTile mapTile )
{
if ( mapTileLocation == null )
{
throw new IllegalArgumentException( "Parameter 'mapTileLocation' cannot be null." );
}
map.put( mapTileLocation, mapTile );
for ( MapTileAddedListener mapTileAddedListener : mapTileAddedListeners )
{
mapTileAddedListener.mapTileAdded( this, mapTileLocation );
}
}
/**
* Generate the map.
*/
public void generate()
{
// while there are open locations:
// randomly pick tile type
// randomly pick tile position (location and orientation)
// add tile of the appropriate type at the selected position
}
}
| src/org/flexgen/map/MapGenerator.java | /*
FlexGen : Flexible Map Generator Library
Copyright (C) 2009 - Jeffrey J. Weston <[email protected]>
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 FlexGen project 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.
*/
package org.flexgen.map;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/**
* Class containing logic for randomly generating a map using a specified set of map tile types.
*/
public class MapGenerator
{
/**
* Data structure containing the map. Maps map tile locations to map tiles.
*/
private final Map< MapTileLocation, MapTile > map;
/**
* List of listeners for the event of adding a map tile.
*/
private final List< MapTileAddedListener > mapTileAddedListeners;
/**
* The size of the map unit array that defines the map tile types used by this map generator.
*/
private final int tileSize;
/**
* Smallest possible X coordinate for map tiles in the map.
*/
private final int minX;
/**
* Smallest possible Y coordinate for map tiles in the map.
*/
private final int minY;
/**
* Largest possible X coordinate for map tiles in the map.
*/
private final int maxX;
/**
* Largest possible Y coordinate for map tiles in the map.
*/
private final int maxY;
/**
* Construct a map generator.
*
* @param mapTileTypes
* Array of map tile types that define the available map tile types for randomly
* generating the map. Cannot be null. Must contain at least one element. No element
* can be null. Cannot contain two or more elements that are identical. All map tile
* types in the array must be the same size.
* @param minX
* Smallest possible X coordinate for map tiles in the map.
* @param minY
* Smallest possible Y coordinate for map tiles in the map.
* @param maxX
* Largest possible X coordinate for map tiles in the map. Must be greater than or
* equal to minX.
* @param maxY
* Largest possible Y coordinate for map tiles in the map. Must be greater than or
* equal to minY.
*/
public MapGenerator( MapTileType[] mapTileTypes, int minX, int minY, int maxX, int maxY )
{
if ( mapTileTypes == null )
{
throw new IllegalArgumentException( "Parameter 'mapTileTypes' cannot be null." );
}
if ( mapTileTypes.length == 0 )
{
throw new IllegalArgumentException(
"Parameter 'mapTileTypes' must contain at least one element." );
}
int tileSize = 0;
for ( int i = 0; i < mapTileTypes.length; i++ )
{
// check for a null element
if ( mapTileTypes[ i ] == null )
{
throw new IllegalArgumentException(
"Parameter 'mapTileTypes' must not contain any null elements." );
}
// check for a duplicate element
for ( int j = i + 1; j < mapTileTypes.length; j++ )
{
if ( mapTileTypes[ i ].equals( mapTileTypes[ j ] ))
{
throw new IllegalArgumentException(
"Parameter 'mapTileTypes' must not contain any duplicate elements." );
}
}
// check to see that all elements are the same size
if ( tileSize == 0 )
{
tileSize = mapTileTypes[ i ].getSize();
}
else
{
if ( tileSize != mapTileTypes[ i ].getSize() )
{
throw new IllegalArgumentException( "All map tile types in parameter " +
"'mapTileTypes' must be the same size." );
}
}
}
if ( maxX < minX )
{
throw new IllegalArgumentException(
"Parameter 'maxX' must be greater than or equal to parameter 'minX'." );
}
if ( maxY < minY )
{
throw new IllegalArgumentException(
"Parameter 'maxY' must be greater than or equal to parameter 'minY'." );
}
this.map = new HashMap< MapTileLocation, MapTile >();
this.mapTileAddedListeners = new LinkedList< MapTileAddedListener >();
this.tileSize = tileSize;
this.minX = minX;
this.minY = minY;
this.maxX = maxX;
this.maxY = maxY;
}
/**
* Get the size of the map unit array that defines the map tile types used by this map
* generator.
*
* @return The size of the map unit array that defines the map tile types used by this map
* generator.
*/
public int getTileSize()
{
return tileSize;
}
/**
* Get the smallest possible X coordinate for map tiles in the map.
*
* @return The smallest possible X coordinate for map tiles in the map.
*/
public int getMinX()
{
return minX;
}
/**
* Get the smallest possible Y coordinate for map tiles in the map.
*
* @return The smallest possible Y coordinate for map tiles in the map.
*/
public int getMinY()
{
return minY;
}
/**
* Get the largest possible X coordinate for map tiles in the map.
*
* @return The largest possible X coordinate for map tiles in the map.
*/
public int getMaxX()
{
return maxX;
}
/**
* Get the largest possible Y coordinate for map tiles in the map.
*
* @return The largest possible Y coordinate for map tiles in the map.
*/
public int getMaxY()
{
return maxY;
}
/**
* Add a new listener for the event of adding a map tile to the map.
*
* @param mapTileAddedListener
* The listener to add.
*/
public void addMapTileAddedListener( MapTileAddedListener mapTileAddedListener )
{
mapTileAddedListeners.add( mapTileAddedListener );
}
/**
* Get the map tile at a specified location.
*
* @param mapTileLocation
* Location for which to get the map tile.
*
* @return The map tile at a specified location.
*/
public MapTile getMapTile( MapTileLocation mapTileLocation )
{
if ( mapTileLocation == null )
{
throw new IllegalArgumentException( "Parameter 'mapTileLocation' cannot be null." );
}
return map.get( mapTileLocation );
}
/**
* Add a map tile to the map at the specified location.
*
* @param mapTileLocation
* Location at which to add the map tile.
* @param mapTile
* Map tile to add.
*/
public void addMapTile( MapTileLocation mapTileLocation, MapTile mapTile )
{
if ( mapTileLocation == null )
{
throw new IllegalArgumentException( "Parameter 'mapTileLocation' cannot be null." );
}
map.put( mapTileLocation, mapTile );
for ( MapTileAddedListener mapTileAddedListener : mapTileAddedListeners )
{
mapTileAddedListener.mapTileAdded( this, mapTileLocation );
}
}
/**
* Generate the map.
*/
public void generate()
{
// while there are open locations:
// randomly pick tile type
// randomly pick tile position (location and orientation)
// add tile of the appropriate type at the selected position
}
}
| Minor formatting fix.
| src/org/flexgen/map/MapGenerator.java | Minor formatting fix. | <ide><path>rc/org/flexgen/map/MapGenerator.java
<ide> import java.util.LinkedList;
<ide> import java.util.List;
<ide> import java.util.Map;
<del>
<ide>
<ide> /**
<ide> * Class containing logic for randomly generating a map using a specified set of map tile types. |
|
JavaScript | apache-2.0 | a364dc639cbd0a6e8f7e39c698586e4ae53066b9 | 0 | joewalker/gcli,mozilla/gcli,mozilla/gcli,mozilla/gcli,joewalker/gcli | /*
* Copyright 2009-2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE.txt or:
* http://opensource.org/licenses/BSD-3-Clause
*/
var copy = require('dryice').copy;
var path = require('path');
var fs = require('fs');
var gcliHome = __dirname;
/**
* The main() function is called at the bottom of this file to ensure all the
* globals are setup properly.
*/
function main() {
var args = process.argv;
if (args.length < 3 || args[2] === 'standard') {
buildStandard();
}
else if (args[2] === 'firefox') {
buildFirefox(args[3]);
}
else {
console.error('Error: Unknown target: \'' + args[2] + '\'');
process.exit(1);
}
}
/**
* There are 2 important ways to build GCLI.
* The first is for use within a normal web page.
* It has compressed and uncompressed versions of the output script file.
*/
function buildStandard() {
console.log('Building built/gcli[-uncompressed].js:');
if (!path.existsSync(gcliHome + '/built')) {
fs.mkdirSync(gcliHome + '/built', 0755);
}
var project = copy.createCommonJsProject({
roots: [ gcliHome + '/lib' ]
});
var sources = copy.createDataObject();
copy({
source: copy.source.commonjs({
project: project,
// This list of dependencies should be the same as in index.html
require: [ 'gcli/index', 'demo/index', 'gclitest/index' ]
}),
filter: copy.filter.moduleDefines,
dest: sources
});
copy({
source: { root: project, include: /.*\.png$|.*\.gif$/ },
filter: copy.filter.base64,
dest: sources
});
console.log(project.report());
// Create a GraphML dependency report. Directions:
// - Install yEd (http://www.yworks.com/en/products_yed_about.htm)
// - Load gcli/built/gcli.graphml
// - Resize the nodes (Tools->Fit Node to Label)
// - Apply a layout (Layout->Hierarchical)
console.log('Outputting dependency graph to built/gcli.graphml\n');
if (project.getDependencyGraphML) {
copy({
source: { value:project.getDependencyGraphML() },
dest: 'built/gcli.graphml',
});
}
// Create the output scripts, compressed and uncompressed
copy({ source: 'index.html', filter: tweakIndex, dest: 'built/index.html' });
copy({ source: 'scripts/es5-shim.js', dest: 'built/es5-shim.js' });
copy({
source: [ copy.getMiniRequire(), sources ],
dest: 'built/gcli-uncompressed.js'
});
try {
copy({
source: [ copy.getMiniRequire(), sources ],
filter: copy.filter.uglifyjs,
dest: 'built/gcli.js'
});
}
catch (ex) {
console.log('ERROR: Uglify compression fails on windows/linux. ' +
'Skipping creation of built/gcli.js\n');
}
}
/**
* Build the Javascript JSM files for Firefox
* It consists of 1 output file: gcli.jsm
*/
function buildFirefox(destDir) {
console.log('Building to ' + (destDir || 'built/ff') + '.\n');
if (!destDir) {
if (!path.existsSync(gcliHome + '/built')) {
fs.mkdirSync(gcliHome + '/built', 0755);
}
if (!path.existsSync(gcliHome + '/built/ff')) {
fs.mkdirSync(gcliHome + '/built/ff', 0755);
}
}
var jsmDir = '/browser/devtools/webconsole';
var winCssDir = '/browser/themes/winstripe/browser/devtools';
var pinCssDir = '/browser/themes/pinstripe/browser/devtools';
var gnomeCssDir = '/browser/themes/gnomestripe/browser/devtools';
var propsDir = '/browser/locales/en-US/chrome/browser';
if (destDir) {
var fail = false;
if (!path.existsSync(destDir + jsmDir)) {
console.error('Missing path for JSM: ' + destDir + jsmDir);
fail = true;
}
if (!path.existsSync(destDir + winCssDir)) {
console.error('Missing path for Windows CSS: ' + destDir + winCssDir);
fail = true;
}
if (!path.existsSync(destDir + pinCssDir)) {
console.error('Missing path for Mac CSS: ' + destDir + pinCssDir);
fail = true;
}
if (!path.existsSync(destDir + gnomeCssDir)) {
console.error('Missing path for Gnome CSS: ' + destDir + gnomeCssDir);
fail = true;
}
if (!path.existsSync(destDir + propsDir)) {
console.error('Missing path for l10n string: ' + destDir + propsDir);
fail = true;
}
if (fail) {
process.exit(1);
}
}
var project = copy.createCommonJsProject({
roots: [ gcliHome + '/mozilla', gcliHome + '/lib' ],
ignores: [ 'text!gcli/ui/inputter.css' ]
});
// Package the JavaScript
copy({
source: [
'mozilla/build/prefix-gcli.jsm',
'mozilla/build/console.js',
copy.getMiniRequire(),
copy.source.commonjs({
project: project,
// This list of dependencies should be the same as in suffix-gcli.jsm
require: [ 'gcli/index' ]
}),
'mozilla/build/suffix-gcli.jsm'
],
filter: copy.filter.moduleDefines,
dest: (destDir ? destDir + jsmDir : 'built/ff') + '/gcli.jsm'
});
// Package the CSS
var css = copy.createDataObject();
copy({
source: [
'mozilla/build/license-block.txt',
{ value: '\n/* From: $GCLI/mozilla/gcli/ui/gcliterm.css */' },
'mozilla/gcli/ui/gcliterm.css',
{ value: '\n/* From: $GCLI/lib/gcli/ui/arg_fetch.css */' },
'lib/gcli/ui/arg_fetch.css',
{ value: '\n/* From: $GCLI/lib/gcli/ui/hinter.css */' },
'lib/gcli/ui/hinter.css',
{ value: '\n/* From: $GCLI/lib/gcli/ui/menu.css */' },
'lib/gcli/ui/menu.css',
{ value: '\n/* From: $GCLI/lib/gcli/ui/inputter.css */' },
'lib/gcli/ui/inputter.css',
{ value: '\n/* From: $GCLI/lib/gcli/ui/command_output_view.css */' },
'lib/gcli/ui/command_output_view.css'
],
dest: css
});
copy({
source: css,
dest: (destDir ? destDir + winCssDir : 'built/ff') + '/gcli.css'
});
copy({
source: css,
dest: (destDir ? destDir + pinCssDir : 'built/ff') + '/gcli.css'
});
copy({
source: css,
dest: (destDir ? destDir + gnomeCssDir : 'built/ff') + '/gcli.css'
});
// Package the i18n strings
copy({
source: 'lib/gcli/nls/strings.js',
filter: tweakI18nStrings,
dest: (destDir ? destDir + propsDir : 'built/ff') + '/gcli.properties'
});
console.log(project.report());
}
/**
* Filter index.html to:
* - Make links relative, we flatten out the scripts directory
* - Replace require.js with the built GCLI script file
* - Remove the RequireJS configuration
*/
function tweakIndex(data) {
return data
.replace(/scripts\/es5-shim.js/, 'es5-shim.js')
.replace(/scripts\/require.js/, 'gcli-uncompressed.js')
.replace(/\s*require\([^;]*;\n/, '');
}
/**
* Regular expression that removes the header/footer from a nls strings file.
* If/when we revert to RequireJS formatted strings files, we'll need to update
* this.
* See lib/gcli/nls/strings.js for an example
*/
var outline = /root: {([^}]*)}/;
/**
* Regex to match a set of single line comments followed by a name:value
* We run this to fund the list of strings once we've used 'outline' to get the
* main body.
* See lib/gcli/nls/strings.js for an example
*/
var singleString = /((\s*\/\/.*\n)+)\s*([A-z.]+):\s*'(.*)',?\n/g;
/**
* Filter to turn GCLIs l18n script file into a Firefox l10n strings file
*/
function tweakI18nStrings(data) {
// Rip off the CommonJS header/footer
var results = outline.exec(data);
if (!results) {
console.error('Mismatch in lib/gcli/nls/strings.js');
process.exit(1);
}
// Remove the trailing spaces
var data = results[1].replace(/ *$/, '');
// Convert each of the string definitions
data = data.replace(singleString, function(m, note, x, name, value) {
note = note.replace(/\n? *\/\/ */g, ' ')
.replace(/^ /, '')
.replace(/\n$/, '');
note = 'LOCALIZATION NOTE (' + name + '): ' + note;
var lines = '# ' + wordWrap(note, 77).join('\n# ') + '\n';
// Unescape JavaScript strings so they're property values
value = value.replace(/\\\\/g, '\\')
.replace(/\\'/g, '\'');
return lines + name + '=' + value + '\n\n';
});
return '# LOCALIZATION NOTE These strings are used inside the GCLI.\n\n' + data;
}
/**
* Return an input string split into lines of a given length
*/
function wordWrap(input, length) {
// LOOK! Over there! Is it an airplane?
var wrapper = new RegExp('.{0,' + (length - 1) + '}([ $|\\s$]|$)', 'g');
return input.match(wrapper).slice(0, -1).map(function(s) {
return s.replace(/ $/, '');
});
}
// Now everything is defined properly, start working
main();
| Makefile.dryice.js | /*
* Copyright 2009-2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE.txt or:
* http://opensource.org/licenses/BSD-3-Clause
*/
var copy = require('dryice').copy;
var path = require('path');
var fs = require('fs');
var gcliHome = __dirname;
/**
* The main() function is called at the bottom of this file to ensure all the
* globals are setup properly.
*/
function main() {
var args = process.argv;
if (args.length < 3 || args[2] === 'standard') {
buildStandard();
}
else if (args[2] === 'firefox') {
buildFirefox(args[3]);
}
else {
console.error('Error: Unknown target: \'' + args[2] + '\'');
process.exit(1);
}
}
/**
* There are 2 important ways to build GCLI.
* The first is for use within a normal web page.
* It has compressed and uncompressed versions of the output script file.
*/
function buildStandard() {
console.log('Building built/gcli[-uncompressed].js:');
if (!path.existsSync(gcliHome + '/built')) {
fs.mkdirSync(gcliHome + '/built', 0755);
}
var project = copy.createCommonJsProject({
roots: [ gcliHome + '/lib' ]
});
var sources = copy.createDataObject();
copy({
source: copy.source.commonjs({
project: project,
// This list of dependencies should be the same as in index.html
require: [ 'gcli/index', 'demo/index', 'gclitest/index' ]
}),
filter: copy.filter.moduleDefines,
dest: sources
});
copy({
source: { root: project, include: /.*\.png$|.*\.gif$/ },
filter: copy.filter.base64,
dest: sources
});
console.log(project.report());
// Create a GraphML dependency report. Directions:
// - Install yEd (http://www.yworks.com/en/products_yed_about.htm)
// - Load gcli/built/gcli.graphml
// - Resize the nodes (Tools->Fit Node to Label)
// - Apply a layout (Layout->Hierarchical)
console.log('Outputting dependency graph to built/gcli.graphml\n');
if (project.getDependencyGraphML) {
copy({
source: { value:project.getDependencyGraphML() },
dest: 'built/gcli.graphml',
});
}
// Create the output scripts, compressed and uncompressed
copy({ source: 'index.html', filter: tweakIndex, dest: 'built/index.html' });
copy({ source: 'scripts/es5-shim.js', dest: 'built/es5-shim.js' });
copy({
source: [ copy.getMiniRequire(), sources ],
dest: 'built/gcli-uncompressed.js'
});
try {
copy({
source: [ copy.getMiniRequire(), sources ],
filter: copy.filter.uglifyjs,
dest: 'built/gcli.js'
});
}
catch (ex) {
console.log('ERROR: Uglify compression fails on windows/linux. ' +
'Skipping creation of built/gcli.js\n');
}
}
/**
* Build the Javascript JSM files for Firefox
* It consists of 1 output file: gcli.jsm
*/
function buildFirefox(destDir) {
console.log('Building to ' + (destDir || 'built/ff') + '.\n');
if (!destDir) {
if (!path.existsSync(gcliHome + '/built')) {
fs.mkdirSync(gcliHome + '/built', 0755);
}
if (!path.existsSync(gcliHome + '/built/ff')) {
fs.mkdirSync(gcliHome + '/built/ff', 0755);
}
}
var jsmDir = '/browser/devtools/webconsole';
var winCssDir = '/browser/themes/winstripe/browser/devtools';
var pinCssDir = '/browser/themes/pinstripe/browser/devtools';
var gnomeCssDir = '/browser/themes/gnomestripe/browser/devtools';
var propsDir = '/browser/locales/en-US/chrome/browser';
if (destDir) {
var fail = false;
if (!path.existsSync(destDir + jsmDir)) {
console.error('Missing path for JSM: ' + destDir + jsmDir);
fail = true;
}
if (!path.existsSync(destDir + winCssDir)) {
console.error('Missing path for Windows CSS: ' + destDir + winCssDir);
fail = true;
}
if (!path.existsSync(destDir + pinCssDir)) {
console.error('Missing path for Mac CSS: ' + destDir + pinCssDir);
fail = true;
}
if (!path.existsSync(destDir + gnomeCssDir)) {
console.error('Missing path for Gnome CSS: ' + destDir + gnomeCssDir);
fail = true;
}
if (!path.existsSync(destDir + propsDir)) {
console.error('Missing path for l10n string: ' + destDir + propsDir);
fail = true;
}
if (fail) {
process.exit(1);
}
}
var project = copy.createCommonJsProject({
roots: [ gcliHome + '/mozilla', gcliHome + '/lib' ],
ignores: [ 'text!gcli/ui/inputter.css' ]
});
// Package the JavaScript
copy({
source: [
'mozilla/build/prefix-gcli.jsm',
'mozilla/build/console.js',
copy.getMiniRequire(),
copy.source.commonjs({
project: project,
// This list of dependencies should be the same as in suffix-gcli.jsm
require: [ 'gcli/index' ]
}),
'mozilla/build/suffix-gcli.jsm'
],
filter: copy.filter.moduleDefines,
dest: (destDir ? destDir + jsmDir : 'built/ff') + '/gcli.jsm'
});
// Package the CSS
var css = copy.createDataObject();
copy({
source: [
'mozilla/build/license-block.txt',
{ value: '\n/* From: $GCLI/mozilla/gcli/ui/gcliterm.css */' },
'mozilla/gcli/ui/gcliterm.css',
{ value: '\n/* From: $GCLI/lib/gcli/ui/arg_fetch.css */' },
'lib/gcli/ui/arg_fetch.css',
{ value: '\n/* From: $GCLI/lib/gcli/ui/hinter.css */' },
'lib/gcli/ui/hinter.css',
{ value: '\n/* From: $GCLI/lib/gcli/ui/menu.css */' },
'lib/gcli/ui/menu.css',
{ value: '\n/* From: $GCLI/lib/gcli/ui/inputter.css */' },
'lib/gcli/ui/inputter.css',
{ value: '\n/* From: $GCLI/lib/gcli/ui/command_output_view.css */' },
'lib/gcli/ui/command_output_view.css'
],
dest: css
});
copy({
source: css,
dest: (destDir ? destDir + winCssDir : 'built/ff') + '/gcli.css'
});
copy({
source: css,
dest: (destDir ? destDir + pinCssDir : 'built/ff') + '/gcli.css'
});
copy({
source: css,
dest: (destDir ? destDir + gnomeCssDir : 'built/ff') + '/gcli.css'
});
// Package the i18n strings
copy({
source: 'lib/gcli/nls/strings.js',
dest: (destDir ? destDir + propsDir : 'built/ff') + '/gcli.properties'
});
console.log(project.report());
}
/**
* Filter index.html to:
* - Make links relative, we flatten out the scripts directory
* - Replace require.js with the built GCLI script file
* - Remove the RequireJS configuration
*/
function tweakIndex(data) {
return data
.replace(/scripts\/es5-shim.js/, 'es5-shim.js')
.replace(/scripts\/require.js/, 'gcli-uncompressed.js')
.replace(/\s*require\([^;]*;\n/, '');
}
// Now everything is defined properly, start working
main();
| Bug 653139 (l10n): Makefile update - Add a filter to convert the JavaScript
strings format used by GCLI on the web to the Java properties format used by
Firefoxes l10n code.
| Makefile.dryice.js | Bug 653139 (l10n): Makefile update - Add a filter to convert the JavaScript strings format used by GCLI on the web to the Java properties format used by Firefoxes l10n code. | <ide><path>akefile.dryice.js
<ide> // Package the i18n strings
<ide> copy({
<ide> source: 'lib/gcli/nls/strings.js',
<add> filter: tweakI18nStrings,
<ide> dest: (destDir ? destDir + propsDir : 'built/ff') + '/gcli.properties'
<ide> });
<ide>
<ide> .replace(/scripts\/require.js/, 'gcli-uncompressed.js')
<ide> .replace(/\s*require\([^;]*;\n/, '');
<ide> }
<add>
<add>/**
<add> * Regular expression that removes the header/footer from a nls strings file.
<add> * If/when we revert to RequireJS formatted strings files, we'll need to update
<add> * this.
<add> * See lib/gcli/nls/strings.js for an example
<add> */
<add>var outline = /root: {([^}]*)}/;
<add>
<add>/**
<add> * Regex to match a set of single line comments followed by a name:value
<add> * We run this to fund the list of strings once we've used 'outline' to get the
<add> * main body.
<add> * See lib/gcli/nls/strings.js for an example
<add> */
<add>var singleString = /((\s*\/\/.*\n)+)\s*([A-z.]+):\s*'(.*)',?\n/g;
<add>
<add>/**
<add> * Filter to turn GCLIs l18n script file into a Firefox l10n strings file
<add> */
<add>function tweakI18nStrings(data) {
<add> // Rip off the CommonJS header/footer
<add> var results = outline.exec(data);
<add> if (!results) {
<add> console.error('Mismatch in lib/gcli/nls/strings.js');
<add> process.exit(1);
<add> }
<add> // Remove the trailing spaces
<add> var data = results[1].replace(/ *$/, '');
<add> // Convert each of the string definitions
<add> data = data.replace(singleString, function(m, note, x, name, value) {
<add> note = note.replace(/\n? *\/\/ */g, ' ')
<add> .replace(/^ /, '')
<add> .replace(/\n$/, '');
<add> note = 'LOCALIZATION NOTE (' + name + '): ' + note;
<add> var lines = '# ' + wordWrap(note, 77).join('\n# ') + '\n';
<add> // Unescape JavaScript strings so they're property values
<add> value = value.replace(/\\\\/g, '\\')
<add> .replace(/\\'/g, '\'');
<add> return lines + name + '=' + value + '\n\n';
<add> });
<add>
<add> return '# LOCALIZATION NOTE These strings are used inside the GCLI.\n\n' + data;
<add>}
<add>
<add>/**
<add> * Return an input string split into lines of a given length
<add> */
<add>function wordWrap(input, length) {
<add> // LOOK! Over there! Is it an airplane?
<add> var wrapper = new RegExp('.{0,' + (length - 1) + '}([ $|\\s$]|$)', 'g');
<add> return input.match(wrapper).slice(0, -1).map(function(s) {
<add> return s.replace(/ $/, '');
<add> });
<add>}
<add>
<ide> // Now everything is defined properly, start working
<ide> main(); |
|
Java | epl-1.0 | 9b8d75a82f8dd106893b59922ef28f3f2d7552d1 | 0 | floralvikings/jenjin | package com.jenjinstudios.core.xml;
import javax.xml.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
/**
* Contains properties representing the metadata of a {@code Message} object, used to constuct a {@code Message} from a
* stream.
*
* @author Caleb Brinkman
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "message", namespace = "https://www.jenjinstudios.com", propOrder = {
"arguments",
"executable"
})
public class MessageType
{
@XmlElement(name = "argument", namespace = "https://www.jenjinstudios.com")
private List<ArgumentType> arguments;
@XmlElement(name = "executable", namespace = "https://www.jenjinstudios.com")
private String executable;
@XmlAttribute(name = "name", required = true)
private String name;
@XmlAttribute(name = "id", required = true)
private short id;
/**
* Get the {@code ArgumentType} objects containing the metadata of the arguments that the {@code Message} should
* contain, in the order in which they should be read and written to a stream.
*
* @return The {@code ArgumentType} objects containing the metadata of the arguments that the {@code Message}
* should
* contain, in the order in which they should be read and written to a stream.
*/
public List<ArgumentType> getArguments() {
if (arguments == null)
{
arguments = new ArrayList<>();
}
return this.arguments;
}
public String getExecutable() { return executable; }
public String getName() { return name; }
public void setName(String value) { this.name = value; }
public short getId() { return id; }
public void setId(short value) { this.id = value; }
}
| jenjin-core/src/main/java/com/jenjinstudios/core/xml/MessageType.java | package com.jenjinstudios.core.xml;
import javax.xml.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
/**
* Contains properties representing the metadata of a {@code Message} object, used to constuct a {@code Message} from a
* stream.
*
* @author Caleb Brinkman
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "message", namespace = "https://www.jenjinstudios.com", propOrder = {
"arguments",
"executable"
})
public class MessageType
{
@XmlElement(name = "argument", namespace = "https://www.jenjinstudios.com")
private List<ArgumentType> arguments;
@XmlElement(name = "executable", namespace = "https://www.jenjinstudios.com")
private String executable;
@XmlAttribute(name = "name", required = true)
private String name;
@XmlAttribute(name = "id", required = true)
private short id;
public List<ArgumentType> getArguments() {
if (arguments == null)
{
arguments = new ArrayList<>();
}
return this.arguments;
}
public String getExecutable() { return executable; }
public String getName() { return name; }
public void setName(String value) { this.name = value; }
public short getId() { return id; }
public void setId(short value) { this.id = value; }
}
| Added getArguments JavaDoc
| jenjin-core/src/main/java/com/jenjinstudios/core/xml/MessageType.java | Added getArguments JavaDoc | <ide><path>enjin-core/src/main/java/com/jenjinstudios/core/xml/MessageType.java
<ide> @XmlAttribute(name = "id", required = true)
<ide> private short id;
<ide>
<add> /**
<add> * Get the {@code ArgumentType} objects containing the metadata of the arguments that the {@code Message} should
<add> * contain, in the order in which they should be read and written to a stream.
<add> *
<add> * @return The {@code ArgumentType} objects containing the metadata of the arguments that the {@code Message}
<add> * should
<add> * contain, in the order in which they should be read and written to a stream.
<add> */
<ide> public List<ArgumentType> getArguments() {
<ide> if (arguments == null)
<ide> { |
|
Java | bsd-2-clause | 98e5d8c080130f8c2cd06f09899986e1efff2648 | 0 | tim-group/Tucker,tim-group/Tucker | package com.timgroup.status;
import java.io.IOException;
import java.io.Writer;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TimeZone;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
public class ApplicationReport {
private static final TimeZone UTC = TimeZone.getTimeZone("UTC");
private static final XMLOutputFactory XML_OUTPUT_FACTORY = XMLOutputFactory.newInstance();
private static final String TAG_APPLICATION = "application";
private static final String TAG_COMPONENT = "component";
private static final String TAG_VALUE = "value";
private static final String TAG_EXCEPTION = "exception";
private static final String TAG_TIMESTAMP = "timestamp";
private static final String ATTR_CLASS = "class";
private static final String ATTR_ID = "id";
private final String applicationId;
private final Map<Component, Report> componentReports;
private final long timestamp;
private final Status applicationStatus;
public ApplicationReport(String applicationId, Map<Component, Report> componentReports) {
timestamp = System.currentTimeMillis();
this.applicationId = applicationId;
this.componentReports = componentReports;
applicationStatus = Report.worstStatus(componentReports.values());
}
public void render(Writer writer) throws IOException {
try {
XMLStreamWriter out = XML_OUTPUT_FACTORY.createXMLStreamWriter(writer);
out.writeStartDocument();
out.writeDTD(constructDTD(TAG_APPLICATION, StatusPage.DTD_FILENAME));
out.writeProcessingInstruction("xml-stylesheet", "type=\"text/css\" href=\"" + StatusPage.CSS_FILENAME + "\"");
out.writeStartElement(TAG_APPLICATION);
out.writeAttribute(ATTR_ID, applicationId);
out.writeAttribute(ATTR_CLASS, applicationStatus.name().toLowerCase());
for (Entry<Component, Report> componentReport : componentReports.entrySet()) {
Component component = componentReport.getKey();
Report report = componentReport.getValue();
out.writeStartElement(TAG_COMPONENT);
out.writeAttribute(ATTR_ID, component.getId());
out.writeAttribute(ATTR_CLASS, report.getStatus().name().toLowerCase());
out.writeCharacters(component.getLabel());
if (report.hasValue()) {
out.writeCharacters(": ");
if (report.isSuccessful()) {
out.writeStartElement(TAG_VALUE);
out.writeCharacters(String.valueOf(report.getValue()));
out.writeEndElement();
} else {
out.writeStartElement(TAG_EXCEPTION);
out.writeCharacters(report.getException().getMessage());
out.writeEndElement();
}
}
out.writeEndElement();
}
out.writeStartElement(TAG_TIMESTAMP);
out.writeCharacters(formatTime(timestamp));
out.writeEndElement();
out.writeEndElement();
out.writeEndDocument();
out.close();
} catch (XMLStreamException e) {
throw new IOException(e);
}
}
private String constructDTD(String rootElement, String systemID) {
return "<!DOCTYPE " + rootElement + " SYSTEM \"" + systemID + "\">";
}
private String formatTime(long time) {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
df.setTimeZone(UTC);
return df.format(time);
}
}
| src/main/java/com/timgroup/status/ApplicationReport.java | package com.timgroup.status;
import java.io.IOException;
import java.io.Writer;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TimeZone;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
public class ApplicationReport {
private static final TimeZone UTC = TimeZone.getTimeZone("UTC");
private static final XMLOutputFactory XML_OUTPUT_FACTORY = XMLOutputFactory.newInstance();
private static final String TAG_APPLICATION = "application";
private static final String TAG_COMPONENT = "component";
private static final String TAG_VALUE = "value";
private static final String TAG_EXCEPTION = "exception";
private static final String TAG_TIMESTAMP = "timestamp";
private static final String ATTR_CLASS = "class";
private static final String ATTR_ID = "id";
private final String applicationId;
private final Map<Component, Report> componentReports;
private final long timestamp;
public ApplicationReport(String applicationId, Map<Component, Report> componentReports) {
this.applicationId = applicationId;
this.componentReports = componentReports;
timestamp = System.currentTimeMillis();
}
public void render(Writer writer) throws IOException {
try {
XMLStreamWriter out = XML_OUTPUT_FACTORY.createXMLStreamWriter(writer);
out.writeStartDocument();
out.writeDTD(constructDTD(TAG_APPLICATION, StatusPage.DTD_FILENAME));
out.writeProcessingInstruction("xml-stylesheet", "type=\"text/css\" href=\"" + StatusPage.CSS_FILENAME + "\"");
out.writeStartElement(TAG_APPLICATION);
out.writeAttribute(ATTR_ID, applicationId);
Status applicationStatus = findApplicationStatus(componentReports);
out.writeAttribute(ATTR_CLASS, applicationStatus.name().toLowerCase());
for (Entry<Component, Report> componentReport : componentReports.entrySet()) {
Component component = componentReport.getKey();
Report report = componentReport.getValue();
out.writeStartElement(TAG_COMPONENT);
out.writeAttribute(ATTR_ID, component.getId());
out.writeAttribute(ATTR_CLASS, report.getStatus().name().toLowerCase());
out.writeCharacters(component.getLabel());
if (report.hasValue()) {
out.writeCharacters(": ");
if (report.isSuccessful()) {
out.writeStartElement(TAG_VALUE);
out.writeCharacters(String.valueOf(report.getValue()));
out.writeEndElement();
} else {
out.writeStartElement(TAG_EXCEPTION);
out.writeCharacters(report.getException().getMessage());
out.writeEndElement();
}
}
out.writeEndElement();
}
out.writeStartElement(TAG_TIMESTAMP);
out.writeCharacters(formatTime(timestamp));
out.writeEndElement();
out.writeEndElement();
out.writeEndDocument();
out.close();
} catch (XMLStreamException e) {
throw new IOException(e);
}
}
private Status findApplicationStatus(Map<Component, Report> componentReports) {
return Report.worstStatus(componentReports.values());
}
private String constructDTD(String rootElement, String systemID) {
return "<!DOCTYPE " + rootElement + " SYSTEM \"" + systemID + "\">";
}
private String formatTime(long time) {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
df.setTimeZone(UTC);
return df.format(time);
}
}
| TomA: compute overall application status when we create the application report, not when we render
| src/main/java/com/timgroup/status/ApplicationReport.java | TomA: compute overall application status when we create the application report, not when we render | <ide><path>rc/main/java/com/timgroup/status/ApplicationReport.java
<ide> private final String applicationId;
<ide> private final Map<Component, Report> componentReports;
<ide> private final long timestamp;
<add> private final Status applicationStatus;
<ide>
<ide> public ApplicationReport(String applicationId, Map<Component, Report> componentReports) {
<add> timestamp = System.currentTimeMillis();
<ide> this.applicationId = applicationId;
<ide> this.componentReports = componentReports;
<del> timestamp = System.currentTimeMillis();
<add> applicationStatus = Report.worstStatus(componentReports.values());
<ide> }
<ide>
<ide> public void render(Writer writer) throws IOException {
<ide>
<ide> out.writeStartElement(TAG_APPLICATION);
<ide> out.writeAttribute(ATTR_ID, applicationId);
<del> Status applicationStatus = findApplicationStatus(componentReports);
<ide> out.writeAttribute(ATTR_CLASS, applicationStatus.name().toLowerCase());
<ide>
<ide> for (Entry<Component, Report> componentReport : componentReports.entrySet()) {
<ide> }
<ide> }
<ide>
<del> private Status findApplicationStatus(Map<Component, Report> componentReports) {
<del> return Report.worstStatus(componentReports.values());
<del> }
<del>
<ide> private String constructDTD(String rootElement, String systemID) {
<ide> return "<!DOCTYPE " + rootElement + " SYSTEM \"" + systemID + "\">";
<ide> } |
|
JavaScript | apache-2.0 | 52574b5aca2f6032c4788cecdc817be7b43c3cb2 | 0 | lo1tuma/galen,thhiep/galen,thhiep/galen,stefanbirkner/galen,tommywo/galen,Drooids/galen,Drooids/galen,thhiep/galen,lo1tuma/galen,stefanbirkner/galen,thr0w/galen,stefanbirkner/galen,thhiep/galen,Drooids/galen,tommywo/galen,thr0w/galen,lo1tuma/galen,tommywo/galen,stefanbirkner/galen,tommywo/galen,Drooids/galen,thr0w/galen,thr0w/galen,lo1tuma/galen | /*******************************************************************************
* Copyright 2014 Ivan Shubin http://galenframework.com
*
* 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.
* ******************************************************************************/
String.prototype.trim=function(){return this.replace(/^\s+|\s+$/g, '');};
function listToArray(list) {
return GalenUtils.listToArray(list);
}
var GalenPages = {
settings: {
cacheWebElements: true,
allowReporting: true,
},
report: function (name, details) {
if (GalenPages.settings.allowReporting) {
var testSession = TestSession.current();
if (testSession != null) {
var node = testSession.getReport().info(name);
if (details != undefined && details != null) {
node.withDetails(details);
}
}
}
},
Locator: function (type, value) {
this.type = type;
this.value = value;
},
parseLocator: function (locatorText) {
var index = locatorText.indexOf(":");
if (index > 0 ) {
var typeText = locatorText.substr(0, index).trim();
var value = locatorText.substr(index + 1, locatorText.length - 1 - index).trim();
var type = "css";
if (typeText == "id") {
type = typeText;
}
else if (typeText == "xpath") {
type = typeText;
}
else if (typeText == "css") {
type = typeText;
}
else {
throw new Error("Unknown locator type: " + typeText);
}
return new this.Locator(type, value);
}
else return {
type: "css",
value: locatorText
};
},
create: function (driver) {
return new GalenPages.Driver(driver);
},
extendPage: function (page, driver, mainFields, secondaryFields) {
var obj = new GalenPages.Page(driver, mainFields, secondaryFields);
for (key in obj) {
if (obj.hasOwnProperty(key)) {
page[key] = obj[key];
}
}
},
Driver: function (driver) {
this.driver = driver;
this.page = function (mainFields, secondaryFields) {
return new GalenPages.Page(this.driver, mainFields, secondaryFields);
};
this.component = this.page;
//basic functions
this.get = function (url){this.driver.get(url);};
this.refresh = function () {this.driver.navigate().reload();};
this.back = function (){this.driver.navigate().back();};
this.currentUrl = function (){return this.driver.getCurrentUrl();};
this.pageSource = function () {return this.driver.getPageSource();};
this.title = function () {return this.driver.getTitle();};
},
convertLocator: function(galenLocator) {
if (galenLocator.type == "id") {
return By.id(galenLocator.value);
}
else if (galenLocator.type == "css") {
return By.cssSelector(galenLocator.value);
}
else if (galenLocator.type == "xpath") {
return By.xpath(galenLocator.value);
}
},
convertTimeToMillis: function (userTime) {
if (typeof userTime == "string") {
var number = parseInt(userTime);
var type = userTime.replace(new RegExp("([0-9]| )", "g"), "");
if (type == "") {
return number;
}
else {
if (type == "m") {
return number * 60000;
}
else if(type == "s") {
return number * 1000;
}
else throw new Error("Cannot convert time. Uknown metric: " + type);
}
}
else return userTime;
},
Wait: function (settings) {
this.settings = settings;
if (settings.time == undefined) {
throw new Error("time was not defined");
}
var period = settings.period;
if (period == undefined) {
period = 1000;
}
this.message = null;
if (typeof settings.message == "string") {
this.message = settings.message;
}
else this.message = "timeout error waiting for:"
this.time = GalenPages.convertTimeToMillis(settings.time);
this.period = GalenPages.convertTimeToMillis(period);
//conditions is a map of functions which should return boolean
this.untilAll = function (conditions) {
var waitFuncs = [];
for (var property in conditions) {
if (conditions.hasOwnProperty(property)) {
var value = conditions[property];
waitFuncs[waitFuncs.length] = {
message: property,
func: value
};
}
}
if (waitFuncs.length > 0) {
var t = 0;
while (t < this.time) {
t = t + this.period;
if (this._checkAll(waitFuncs)) {
return;
}
GalenPages.sleep(this.period);
}
var errors = "";
for (var i = 0; i<waitFuncs.length; i++) {
if (!this._applyConditionFunc(waitFuncs[i].func)) {
errors = errors + "\n - " + waitFuncs[i].message;
}
}
if (errors.length > 0) {
throw new Error(this.message + errors);
}
}
else throw new Error("You are waiting for nothing");
};
this.forEach = function (items, itemConditionName, conditionFunc) {
var conditions = {};
for (var i=0; i<items.length; i++) {
var name = "#" + (i+1) + " " + itemConditionName;
conditions[name] = {
element: items[i],
conditionFunc: conditionFunc,
apply: function () {
return this.conditionFunc(this.element);
}
};
}
this.untilAll(conditions);
};
this._checkAll = function (waitFuncs) {
for (var i = 0; i<waitFuncs.length; i++) {
if (!this._applyConditionFunc(waitFuncs[i].func)) {
return false;
}
}
return true;
};
//Need this hack since sometimes it could be function and sometimes it could be an object with apply function inside
this._applyConditionFunc = function (conditionFunc) {
if (typeof conditionFunc == "function") {
return conditionFunc();
}
else {
return conditionFunc.apply();
}
};
},
wait: function (settings) {
return new this.Wait(settings);
},
sleep: function (timeInMillis) {
Thread.sleep(timeInMillis);
}
};
GalenPages.Page = function (driver, mainFields, secondaryFields) {
this.driver = driver;
var thisPage = this;
var iterateOverFields = function (fields, apply) {
if (fields != undefined) {
for (var property in fields) {
if (fields.hasOwnProperty(property)) {
var value = fields[property];
if (typeof value == "string") {
thisPage[property] = new GalenPages.PageElement(property, GalenPages.parseLocator(value), thisPage);
apply(property);
}
else {
thisPage[property] = value;
}
}
}
}
}
this.primaryFields = [];
thisPrimaryFields = this.primaryFields;
iterateOverFields(mainFields, function (property) {
thisPrimaryFields.push(property);
});
iterateOverFields(secondaryFields, function (property) {});
};
GalenPages.Page.prototype.waitTimeout = "10s";
GalenPages.Page.prototype.waitPeriod = "1s";
GalenPages.Page.prototype._report = function (name) {
try {
GalenPages.report(name);
}
catch (err) {
}
};
GalenPages.Page.prototype.open = function (url) {
this._report("Open " + url);
this.driver.get(url);
};
GalenPages.Page.prototype.findChild = function (locator) {
if (typeof locator == "string") {
locator = GalenPages.parseLocator(locator);
}
if (this.parent != undefined ) {
return this.parent.findChild(locator);
}
else {
try {
var element = this.driver.findElement(GalenPages.convertLocator(locator));
if (element == null) {
throw new Error("No such element: " + locator.type + " " + locator.value);
}
return element;
}
catch(error) {
throw new Error("No such element: " + locator.type + " " + locator.value);
}
}
};
GalenPages.Page.prototype.findChildren = function (locator) {
if (typeof locator == "string") {
locator = GalenPages.parseLocator(locator);
}
if (this.parent != undefined ) {
return this.parent.findChildren(locator);
}
else {
var list = this.driver.findElements(GalenPages.convertLocator(locator));
return listToArray(list);
}
};
GalenPages.Page.prototype.set = function (props) {
for (var property in props) {
if (props.hasOwnProperty(property)) {
this[property] = props[property];
}
}
return this;
};
GalenPages.Page.prototype.waitForIt = function () {
if (this.primaryFields.length > 0 ) {
var conditions = {};
var primaryFields = this.primaryFields;
var page = this;
for (var i = 0; i<this.primaryFields.length; i++) {
conditions[this.primaryFields[i] + " to be displayed"] = {
field: this[this.primaryFields[i]],
apply: function () {
return this.field.exists();
}
};
}
GalenPages.wait({time: this.waitTimeout, period: this.waitPeriod, message: "timeout waiting for page elements:"}).untilAll(conditions);
}
else throw new Error("You can't wait for page as it does not have any fields defined");
return this;
};
GalenPages.PageElement = function (name, locator, parent) {
this.name = name;
if (typeof parent === "undefined") {
parent = null;
}
this.cachedWebElement = null;
this.locator = locator;
this.parent = parent;
};
GalenPages.PageElement.prototype.isEnabled = function () {
return this.getWebElement().isEnabled();
};
GalenPages.PageElement.prototype.attribute = function(attrName) {
return this.getWebElement().getAttribute(attrName);
};
GalenPages.PageElement.prototype._report = function (name) {
try {
GalenPages.report(name, this.locator.type + ": " + this.locator.value);
}
catch (err) {
}
};
GalenPages.PageElement.prototype.getDriver = function() {
return this.parent.driver;
};
GalenPages.PageElement.prototype.hover = function () {
var actions = new Actions(this.getDriver());
actions.moveToElement(this.getWebElement()).perform();
};
GalenPages.PageElement.prototype.cssValue = function (cssProperty) {
return this.getWebElement().getCssValue(cssProperty);
};
GalenPages.PageElement.prototype.click = function () {
this._report("Click " + this.name);
this.getWebElement().click();
};
GalenPages.PageElement.prototype.typeText = function (text) {
this._report("Type text \"" + text + "\" to " + this.name);
this.getWebElement().sendKeys(text);
};
GalenPages.PageElement.prototype.clear = function () {
this._report("Clear " + this.name);
this.getWebElement().clear();
};
GalenPages.PageElement.prototype.getWebElement = function () {
if (GalenPages.settings.cacheWebElements && this.cachedWebElement == null) {
this.cachedWebElement = this.parent.findChild(this.locator);
}
return this.cachedWebElement;
};
GalenPages.PageElement.prototype.isDisplayed = function () {
return this.getWebElement().isDisplayed();
};
GalenPages.PageElement.prototype.selectByValue = function (value) {
this._report("Select by value \"" + value + "\" in " + this.name);
var option = this.getWebElement().findElement(By.xpath(".//option[@value=\"" + value + "\"]"));
if (option != null) {
option.click();
}
else throw new Error("Cannot find option with value \"" + value + "\"");
};
GalenPages.PageElement.prototype.selectByText = function (text) {
this._report("Select by text \"" + text + "\" in " + this.name);
var option = this.getWebElement().findElement(By.xpath(".//option[normalize-space(.)=\"" + text + "\"]"));
if (option != null) {
option.click();
}
else throw new Error("Cannot find option with text \"" + value + "\"");
};
GalenPages.PageElement.prototype.waitFor = function(func, messageSuffix, time) {
time = typeof time !== 'undefined' ? time : "10s";
var name = typeof this.name !== 'undefined' ? this.name : "";
var msg = name + " " + messageSuffix;
var thisElement = this;
var conditions = {};
conditions[msg] = function (){
return func(thisElement);
};
GalenPages.wait({time: time, period: 200}).untilAll(conditions);
};
GalenPages.PageElement.prototype.waitToBeShown = function (time) {
this.waitFor(function (thisElement){
return thisElement.exists() && thisElement.isDisplayed();
}, "should be shown", time);
};
GalenPages.PageElement.prototype.waitToBeHidden = function (time) {
this.waitFor(function (thisElement){
return !thisElement.exists() || !thisElement.isDisplayed();
}, "should be hidden", time);
},
GalenPages.PageElement.prototype.waitUntilExists = function (time) {
this.waitFor(function (thisElement){
return thisElement.exists();
}, "should exist", time);
};
GalenPages.PageElement.prototype.waitUntilGone = function (time) {
this.waitFor(function (thisElement){
return !thisElement.exists();
}, "should not exist", time);
};
GalenPages.PageElement.prototype.exists = function () {
try {
this.getWebElement();
}
catch(error) {
return false;
}
return true;
};
GalenPages.PageElement.prototype.findChild = function (locator) {
if (typeof locator == "string") {
locator = GalenPages.parseLocator(locator);
}
if (this.parent != undefined ) {
return this.parent.findChild(locator);
}
else {
try {
var element = this.driver.findElement(GalenPages.convertLocator(locator));
if (element == null) {
throw new Error("No such element: " + locator.type + " " + locator.value);
}
return element;
}
catch(error) {
throw new Error("No such element: " + locator.type + " " + locator.value);
}
}
};
GalenPages.PageElement.prototype.findChildren = function (locator) {
if (typeof locator == "string") {
locator = GalenPages.parseLocator(locator);
}
if (this.parent != undefined ) {
return this.parent.findChildren(locator);
}
else {
var list = this.driver.findElements(GalenPages.convertLocator(locator));
return listToArray(list);
}
};
(function (exports) {
exports.GalenPages = GalenPages;
})(this);
| src/main/resources/js/GalenPages.js | /*******************************************************************************
* Copyright 2014 Ivan Shubin http://galenframework.com
*
* 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.
* ******************************************************************************/
String.prototype.trim=function(){return this.replace(/^\s+|\s+$/g, '');};
function listToArray(list) {
return GalenUtils.listToArray(list);
}
var GalenPages = {
settings: {
cacheWebElements: true,
allowReporting: true,
},
report: function (name, details) {
if (GalenPages.settings.allowReporting) {
var testSession = TestSession.current();
if (testSession != null) {
var node = testSession.getReport().info(name);
if (details != undefined && details != null) {
node.withDetails(details);
}
}
}
},
Locator: function (type, value) {
this.type = type;
this.value = value;
},
parseLocator: function (locatorText) {
var index = locatorText.indexOf(":");
if (index > 0 ) {
var typeText = locatorText.substr(0, index).trim();
var value = locatorText.substr(index + 1, locatorText.length - 1 - index).trim();
var type = "css";
if (typeText == "id") {
type = typeText;
}
else if (typeText == "xpath") {
type = typeText;
}
else if (typeText == "css") {
type = typeText;
}
else {
throw new Error("Unknown locator type: " + typeText);
}
return new this.Locator(type, value);
}
else return {
type: "css",
value: locatorText
};
},
Page: function (driver, mainFields, secondaryFields) {
this.driver = driver;
this.waitTimeout = "10s";
this.waitPeriod = "1s";
this._report = function (name) {
try {
GalenPages.report(name);
}
catch (err) {
}
},
this.open = function (url) {
this._report("Open " + url);
this.driver.get(url);
},
this.findChild = function (locator) {
if (typeof locator == "string") {
locator = GalenPages.parseLocator(locator);
}
if (this.parent != undefined ) {
return this.parent.findChild(locator);
}
else {
try {
var element = this.driver.findElement(GalenPages.convertLocator(locator));
if (element == null) {
throw new Error("No such element: " + locator.type + " " + locator.value);
}
return element;
}
catch(error) {
throw new Error("No such element: " + locator.type + " " + locator.value);
}
}
};
this.findChildren = function (locator) {
if (typeof locator == "string") {
locator = GalenPages.parseLocator(locator);
}
if (this.parent != undefined ) {
return this.parent.findChildren(locator);
}
else {
var list = this.driver.findElements(GalenPages.convertLocator(locator));
return listToArray(list);
}
};
this.set = function (props) {
for (var property in props) {
if (props.hasOwnProperty(property)) {
this[property] = props[property];
}
}
return this;
};
this.waitForIt = function () {
if (this.primaryFields.length > 0 ) {
var conditions = {};
var primaryFields = this.primaryFields;
var page = this;
for (var i = 0; i<this.primaryFields.length; i++) {
conditions[this.primaryFields[i] + " to be displayed"] = {
field: this[this.primaryFields[i]],
apply: function () {
return this.field.exists();
}
};
}
GalenPages.wait({time: this.waitTimeout, period: this.waitPeriod, message: "timeout waiting for page elements:"}).untilAll(conditions);
}
else throw new Error("You can't wait for page as it does not have any fields defined");
return this;
};
var thisPage = this;
var iterateOverFields = function (fields, apply) {
if (fields != undefined) {
for (var property in fields) {
if (fields.hasOwnProperty(property)) {
var value = fields[property];
if (typeof value == "string") {
thisPage[property] = new GalenPages.PageElement(property, GalenPages.parseLocator(value), thisPage);
apply(property);
}
else {
thisPage[property] = value;
}
}
}
}
}
this.primaryFields = [];
thisPrimaryFields = this.primaryFields;
iterateOverFields(mainFields, function (property) {
thisPrimaryFields.push(property);
});
iterateOverFields(secondaryFields, function (property) {});
},
create: function (driver) {
return new GalenPages.Driver(driver);
},
extendPage: function (page, driver, mainFields, secondaryFields) {
var obj = new GalenPages.Page(driver, mainFields, secondaryFields);
for (key in obj) {
if (obj.hasOwnProperty(key)) {
page[key] = obj[key];
}
}
},
Driver: function (driver) {
this.driver = driver;
this.page = function (mainFields, secondaryFields) {
return new GalenPages.Page(this.driver, mainFields, secondaryFields);
};
this.component = this.page;
//basic functions
this.get = function (url){this.driver.get(url);};
this.refresh = function () {this.driver.navigate().reload();};
this.back = function (){this.driver.navigate().back();};
this.currentUrl = function (){return this.driver.getCurrentUrl();};
this.pageSource = function () {return this.driver.getPageSource();};
this.title = function () {return this.driver.getTitle();};
},
convertLocator: function(galenLocator) {
if (galenLocator.type == "id") {
return By.id(galenLocator.value);
}
else if (galenLocator.type == "css") {
return By.cssSelector(galenLocator.value);
}
else if (galenLocator.type == "xpath") {
return By.xpath(galenLocator.value);
}
},
convertTimeToMillis: function (userTime) {
if (typeof userTime == "string") {
var number = parseInt(userTime);
var type = userTime.replace(new RegExp("([0-9]| )", "g"), "");
if (type == "") {
return number;
}
else {
if (type == "m") {
return number * 60000;
}
else if(type == "s") {
return number * 1000;
}
else throw new Error("Cannot convert time. Uknown metric: " + type);
}
}
else return userTime;
},
Wait: function (settings) {
this.settings = settings;
if (settings.time == undefined) {
throw new Error("time was not defined");
}
var period = settings.period;
if (period == undefined) {
period = 1000;
}
this.message = null;
if (typeof settings.message == "string") {
this.message = settings.message;
}
else this.message = "timeout error waiting for:"
this.time = GalenPages.convertTimeToMillis(settings.time);
this.period = GalenPages.convertTimeToMillis(period);
//conditions is a map of functions which should return boolean
this.untilAll = function (conditions) {
var waitFuncs = [];
for (var property in conditions) {
if (conditions.hasOwnProperty(property)) {
var value = conditions[property];
waitFuncs[waitFuncs.length] = {
message: property,
func: value
};
}
}
if (waitFuncs.length > 0) {
var t = 0;
while (t < this.time) {
t = t + this.period;
if (this._checkAll(waitFuncs)) {
return;
}
GalenPages.sleep(this.period);
}
var errors = "";
for (var i = 0; i<waitFuncs.length; i++) {
if (!this._applyConditionFunc(waitFuncs[i].func)) {
errors = errors + "\n - " + waitFuncs[i].message;
}
}
if (errors.length > 0) {
throw new Error(this.message + errors);
}
}
else throw new Error("You are waiting for nothing");
};
this.forEach = function (items, itemConditionName, conditionFunc) {
var conditions = {};
for (var i=0; i<items.length; i++) {
var name = "#" + (i+1) + " " + itemConditionName;
conditions[name] = {
element: items[i],
conditionFunc: conditionFunc,
apply: function () {
return this.conditionFunc(this.element);
}
};
}
this.untilAll(conditions);
};
this._checkAll = function (waitFuncs) {
for (var i = 0; i<waitFuncs.length; i++) {
if (!this._applyConditionFunc(waitFuncs[i].func)) {
return false;
}
}
return true;
};
//Need this hack since sometimes it could be function and sometimes it could be an object with apply function inside
this._applyConditionFunc = function (conditionFunc) {
if (typeof conditionFunc == "function") {
return conditionFunc();
}
else {
return conditionFunc.apply();
}
};
},
wait: function (settings) {
return new this.Wait(settings);
},
sleep: function (timeInMillis) {
Thread.sleep(timeInMillis);
}
};
GalenPages.PageElement = function (name, locator, parent) {
this.name = name;
if (typeof parent === "undefined") {
parent = null;
}
this.cachedWebElement = null;
this.locator = locator;
this.parent = parent;
};
GalenPages.PageElement.prototype.isEnabled = function () {
return this.getWebElement().isEnabled();
};
GalenPages.PageElement.prototype.attribute = function(attrName) {
return this.getWebElement().getAttribute(attrName);
};
GalenPages.PageElement.prototype._report = function (name) {
try {
GalenPages.report(name, this.locator.type + ": " + this.locator.value);
}
catch (err) {
}
};
GalenPages.PageElement.prototype.getDriver = function() {
return this.parent.driver;
};
GalenPages.PageElement.prototype.hover = function () {
var actions = new Actions(this.getDriver());
actions.moveToElement(this.getWebElement()).perform();
};
GalenPages.PageElement.prototype.cssValue = function (cssProperty) {
return this.getWebElement().getCssValue(cssProperty);
};
GalenPages.PageElement.prototype.click = function () {
this._report("Click " + this.name);
this.getWebElement().click();
};
GalenPages.PageElement.prototype.typeText = function (text) {
this._report("Type text \"" + text + "\" to " + this.name);
this.getWebElement().sendKeys(text);
};
GalenPages.PageElement.prototype.clear = function () {
this._report("Clear " + this.name);
this.getWebElement().clear();
};
GalenPages.PageElement.prototype.getWebElement = function () {
if (GalenPages.settings.cacheWebElements && this.cachedWebElement == null) {
this.cachedWebElement = this.parent.findChild(this.locator);
}
return this.cachedWebElement;
};
GalenPages.PageElement.prototype.isDisplayed = function () {
return this.getWebElement().isDisplayed();
};
GalenPages.PageElement.prototype.selectByValue = function (value) {
this._report("Select by value \"" + value + "\" in " + this.name);
var option = this.getWebElement().findElement(By.xpath(".//option[@value=\"" + value + "\"]"));
if (option != null) {
option.click();
}
else throw new Error("Cannot find option with value \"" + value + "\"");
};
GalenPages.PageElement.prototype.selectByText = function (text) {
this._report("Select by text \"" + text + "\" in " + this.name);
var option = this.getWebElement().findElement(By.xpath(".//option[normalize-space(.)=\"" + text + "\"]"));
if (option != null) {
option.click();
}
else throw new Error("Cannot find option with text \"" + value + "\"");
};
GalenPages.PageElement.prototype.waitFor = function(func, messageSuffix, time) {
time = typeof time !== 'undefined' ? time : "10s";
var name = typeof this.name !== 'undefined' ? this.name : "";
var msg = name + " " + messageSuffix;
var thisElement = this;
var conditions = {};
conditions[msg] = function (){
return func(thisElement);
};
GalenPages.wait({time: time, period: 200}).untilAll(conditions);
};
GalenPages.PageElement.prototype.waitToBeShown = function (time) {
this.waitFor(function (thisElement){
return thisElement.exists() && thisElement.isDisplayed();
}, "should be shown", time);
};
GalenPages.PageElement.prototype.waitToBeHidden = function (time) {
this.waitFor(function (thisElement){
return !thisElement.exists() || !thisElement.isDisplayed();
}, "should be hidden", time);
},
GalenPages.PageElement.prototype.waitUntilExists = function (time) {
this.waitFor(function (thisElement){
return thisElement.exists();
}, "should exist", time);
};
GalenPages.PageElement.prototype.waitUntilGone = function (time) {
this.waitFor(function (thisElement){
return !thisElement.exists();
}, "should not exist", time);
};
GalenPages.PageElement.prototype.exists = function () {
try {
this.getWebElement();
}
catch(error) {
return false;
}
return true;
};
GalenPages.PageElement.prototype.findChild = function (locator) {
if (typeof locator == "string") {
locator = GalenPages.parseLocator(locator);
}
if (this.parent != undefined ) {
return this.parent.findChild(locator);
}
else {
try {
var element = this.driver.findElement(GalenPages.convertLocator(locator));
if (element == null) {
throw new Error("No such element: " + locator.type + " " + locator.value);
}
return element;
}
catch(error) {
throw new Error("No such element: " + locator.type + " " + locator.value);
}
}
};
GalenPages.PageElement.prototype.findChildren = function (locator) {
if (typeof locator == "string") {
locator = GalenPages.parseLocator(locator);
}
if (this.parent != undefined ) {
return this.parent.findChildren(locator);
}
else {
var list = this.driver.findElements(GalenPages.convertLocator(locator));
return listToArray(list);
}
};
(function (exports) {
exports.GalenPages = GalenPages;
})(this);
| Refactored GalenPages.Page to use prototype
| src/main/resources/js/GalenPages.js | Refactored GalenPages.Page to use prototype | <ide><path>rc/main/resources/js/GalenPages.js
<ide> value: locatorText
<ide> };
<ide> },
<del> Page: function (driver, mainFields, secondaryFields) {
<del> this.driver = driver;
<del> this.waitTimeout = "10s";
<del> this.waitPeriod = "1s";
<del> this._report = function (name) {
<del> try {
<del> GalenPages.report(name);
<del> }
<del> catch (err) {
<del>
<del> }
<del> },
<del> this.open = function (url) {
<del> this._report("Open " + url);
<del> this.driver.get(url);
<del> },
<del> this.findChild = function (locator) {
<del> if (typeof locator == "string") {
<del> locator = GalenPages.parseLocator(locator);
<del> }
<del>
<del> if (this.parent != undefined ) {
<del> return this.parent.findChild(locator);
<del> }
<del> else {
<del> try {
<del> var element = this.driver.findElement(GalenPages.convertLocator(locator));
<del> if (element == null) {
<del> throw new Error("No such element: " + locator.type + " " + locator.value);
<del> }
<del> return element;
<del> }
<del> catch(error) {
<del> throw new Error("No such element: " + locator.type + " " + locator.value);
<del> }
<del> }
<del> };
<del> this.findChildren = function (locator) {
<del> if (typeof locator == "string") {
<del> locator = GalenPages.parseLocator(locator);
<del> }
<del>
<del> if (this.parent != undefined ) {
<del> return this.parent.findChildren(locator);
<del> }
<del> else {
<del> var list = this.driver.findElements(GalenPages.convertLocator(locator));
<del> return listToArray(list);
<del> }
<del> };
<del> this.set = function (props) {
<del> for (var property in props) {
<del> if (props.hasOwnProperty(property)) {
<del> this[property] = props[property];
<del> }
<del> }
<del> return this;
<del> };
<del> this.waitForIt = function () {
<del> if (this.primaryFields.length > 0 ) {
<del> var conditions = {};
<del> var primaryFields = this.primaryFields;
<del> var page = this;
<del>
<del> for (var i = 0; i<this.primaryFields.length; i++) {
<del> conditions[this.primaryFields[i] + " to be displayed"] = {
<del> field: this[this.primaryFields[i]],
<del> apply: function () {
<del> return this.field.exists();
<del> }
<del> };
<del> }
<del>
<del> GalenPages.wait({time: this.waitTimeout, period: this.waitPeriod, message: "timeout waiting for page elements:"}).untilAll(conditions);
<del> }
<del> else throw new Error("You can't wait for page as it does not have any fields defined");
<del> return this;
<del> };
<del>
<del> var thisPage = this;
<del>
<del> var iterateOverFields = function (fields, apply) {
<del> if (fields != undefined) {
<del> for (var property in fields) {
<del> if (fields.hasOwnProperty(property)) {
<del> var value = fields[property];
<del> if (typeof value == "string") {
<del> thisPage[property] = new GalenPages.PageElement(property, GalenPages.parseLocator(value), thisPage);
<del> apply(property);
<del> }
<del> else {
<del> thisPage[property] = value;
<del> }
<del> }
<del> }
<del> }
<del> }
<del>
<del> this.primaryFields = [];
<del> thisPrimaryFields = this.primaryFields;
<del> iterateOverFields(mainFields, function (property) {
<del> thisPrimaryFields.push(property);
<del> });
<del>
<del> iterateOverFields(secondaryFields, function (property) {});
<del> },
<ide> create: function (driver) {
<ide> return new GalenPages.Driver(driver);
<ide> },
<ide> Thread.sleep(timeInMillis);
<ide> }
<ide> };
<add>
<add>GalenPages.Page = function (driver, mainFields, secondaryFields) {
<add> this.driver = driver;
<add> var thisPage = this;
<add>
<add> var iterateOverFields = function (fields, apply) {
<add> if (fields != undefined) {
<add> for (var property in fields) {
<add> if (fields.hasOwnProperty(property)) {
<add> var value = fields[property];
<add> if (typeof value == "string") {
<add> thisPage[property] = new GalenPages.PageElement(property, GalenPages.parseLocator(value), thisPage);
<add> apply(property);
<add> }
<add> else {
<add> thisPage[property] = value;
<add> }
<add> }
<add> }
<add> }
<add> }
<add>
<add> this.primaryFields = [];
<add> thisPrimaryFields = this.primaryFields;
<add> iterateOverFields(mainFields, function (property) {
<add> thisPrimaryFields.push(property);
<add> });
<add> iterateOverFields(secondaryFields, function (property) {});
<add>};
<add>GalenPages.Page.prototype.waitTimeout = "10s";
<add>GalenPages.Page.prototype.waitPeriod = "1s";
<add>GalenPages.Page.prototype._report = function (name) {
<add> try {
<add> GalenPages.report(name);
<add> }
<add> catch (err) {
<add>
<add> }
<add>};
<add>GalenPages.Page.prototype.open = function (url) {
<add> this._report("Open " + url);
<add> this.driver.get(url);
<add>};
<add>GalenPages.Page.prototype.findChild = function (locator) {
<add> if (typeof locator == "string") {
<add> locator = GalenPages.parseLocator(locator);
<add> }
<add>
<add> if (this.parent != undefined ) {
<add> return this.parent.findChild(locator);
<add> }
<add> else {
<add> try {
<add> var element = this.driver.findElement(GalenPages.convertLocator(locator));
<add> if (element == null) {
<add> throw new Error("No such element: " + locator.type + " " + locator.value);
<add> }
<add> return element;
<add> }
<add> catch(error) {
<add> throw new Error("No such element: " + locator.type + " " + locator.value);
<add> }
<add> }
<add>};
<add>GalenPages.Page.prototype.findChildren = function (locator) {
<add> if (typeof locator == "string") {
<add> locator = GalenPages.parseLocator(locator);
<add> }
<add>
<add> if (this.parent != undefined ) {
<add> return this.parent.findChildren(locator);
<add> }
<add> else {
<add> var list = this.driver.findElements(GalenPages.convertLocator(locator));
<add> return listToArray(list);
<add> }
<add>};
<add>GalenPages.Page.prototype.set = function (props) {
<add> for (var property in props) {
<add> if (props.hasOwnProperty(property)) {
<add> this[property] = props[property];
<add> }
<add> }
<add> return this;
<add>};
<add>GalenPages.Page.prototype.waitForIt = function () {
<add> if (this.primaryFields.length > 0 ) {
<add> var conditions = {};
<add> var primaryFields = this.primaryFields;
<add> var page = this;
<add>
<add> for (var i = 0; i<this.primaryFields.length; i++) {
<add> conditions[this.primaryFields[i] + " to be displayed"] = {
<add> field: this[this.primaryFields[i]],
<add> apply: function () {
<add> return this.field.exists();
<add> }
<add> };
<add> }
<add>
<add> GalenPages.wait({time: this.waitTimeout, period: this.waitPeriod, message: "timeout waiting for page elements:"}).untilAll(conditions);
<add> }
<add> else throw new Error("You can't wait for page as it does not have any fields defined");
<add> return this;
<add>};
<add>
<add>
<add>
<add>
<ide> GalenPages.PageElement = function (name, locator, parent) {
<ide> this.name = name;
<ide> if (typeof parent === "undefined") { |
|
Java | lgpl-2.1 | d4a404085c3197decc2230171bb52581a104d066 | 0 | xwiki-contrib/android-authenticator,xwiki-contrib/android-authenticator | /*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* 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.xwiki.android.authenticator.utils;
import android.app.ActivityManager;
import android.app.ActivityManager.MemoryInfo;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.Application;
import android.app.KeyguardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.telephony.TelephonyManager;
import android.util.Log;
import org.xwiki.android.authenticator.exceptions.ReadPhoneStateException;
import java.io.File;
import java.security.MessageDigest;
import java.util.List;
/**
* system tools
*/
public final class SystemTools {
private static final String TAG = "SystemTools";
/**
* Get IMEI
* @throws ReadPhoneStateException - will be thrown in cases when need to get permission to read
* phone state
*/
public static String getPhoneIMEI(Context cxt) throws ReadPhoneStateException{
TelephonyManager tm = (TelephonyManager) cxt
.getSystemService(Context.TELEPHONY_SERVICE);
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
return tm.getImei();
} else {
return tm.getMeid();
}
} catch (SecurityException e) {
throw new ReadPhoneStateException(e);
}
}
/**
* return System version
*
* @return like 2.3.3
*/
public static String getSystemVersion() {
return android.os.Build.VERSION.RELEASE;
}
/**
* check whether network is connected
*/
public static boolean checkNet(Context context) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
if (info != null && info.isAvailable()) return true;
return false;
}
public static boolean checkWifi(Application context) {
WifiManager mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = mWifiManager.getConnectionInfo();
int ipAddress = wifiInfo == null ? 0 : wifiInfo.getIpAddress();
return mWifiManager.isWifiEnabled() && ipAddress != 0;
}
/**
* foreground or background
*/
public static boolean isBackground(Context context) {
ActivityManager activityManager = (ActivityManager) context
.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningAppProcessInfo> appProcesses = activityManager
.getRunningAppProcesses();
for (RunningAppProcessInfo appProcess : appProcesses) {
if (appProcess.processName.equals(context.getPackageName())) {
if (appProcess.importance == RunningAppProcessInfo.IMPORTANCE_BACKGROUND) {
// background
return true;
} else {
// foreground
return false;
}
}
}
return false;
}
/**
* whether phone is sleeping
*/
public static boolean isSleeping(Context context) {
KeyguardManager kgMgr = (KeyguardManager) context
.getSystemService(Context.KEYGUARD_SERVICE);
boolean isSleeping = kgMgr.inKeyguardRestrictedInputMode();
return isSleeping;
}
/**
* apk install
*
* @param context
* @param file
*/
public static void installApk(Context context, File file) {
Intent intent = new Intent();
intent.setAction("android.intent.action.VIEW");
intent.addCategory("android.intent.category.DEFAULT");
intent.setType("application/vnd.android.package-archive");
intent.setData(Uri.fromFile(file));
intent.setDataAndType(Uri.fromFile(file),
"application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
/**
* get app version name
*/
public static String getAppVersionName(Context context) {
String version = "0";
try {
version = context.getPackageManager().getPackageInfo(
context.getPackageName(), 0).versionName;
} catch (NameNotFoundException e) {
throw new RuntimeException(SystemTools.class.getName()
+ "the application not found");
}
return version;
}
/**
* get app version code
*/
public static int getAppVersionCode(Context context) {
int version = 0;
try {
version = context.getPackageManager().getPackageInfo(
context.getPackageName(), 0).versionCode;
} catch (NameNotFoundException e) {
throw new RuntimeException(SystemTools.class.getName()
+ "the application not found");
}
return version;
}
/**
* return Home,run in background
*/
public static void goHome(Context context) {
Intent mHomeIntent = new Intent(Intent.ACTION_MAIN);
mHomeIntent.addCategory(Intent.CATEGORY_HOME);
mHomeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
context.startActivity(mHomeIntent);
}
/**
* get application signature
*
* @param context
* @param pkgName
*/
public static String getSign(Context context, String pkgName) {
try {
PackageInfo pis = context.getPackageManager().getPackageInfo(
pkgName, PackageManager.GET_SIGNATURES);
return hexdigest(pis.signatures[0].toByteArray());
} catch (NameNotFoundException e) {
throw new RuntimeException(SystemTools.class.getName() + "the "
+ pkgName + "'s application not found");
}
}
/**
* transfer signature to 32bit
*/
private static String hexdigest(byte[] paramArrayOfByte) {
final char[] hexDigits = {48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 97,
98, 99, 100, 101, 102};
try {
MessageDigest localMessageDigest = MessageDigest.getInstance("MD5");
localMessageDigest.update(paramArrayOfByte);
byte[] arrayOfByte = localMessageDigest.digest();
char[] arrayOfChar = new char[32];
for (int i = 0, j = 0; ; i++, j++) {
if (i >= 16) {
return new String(arrayOfChar);
}
int k = arrayOfByte[i];
arrayOfChar[j] = hexDigits[(0xF & k >>> 4)];
arrayOfChar[++j] = hexDigits[(k & 0xF)];
}
} catch (Exception e) {
}
return "";
}
/**
* available memory size
*
* @param cxt context
* @return memory size
*/
public static int getDeviceUsableMemory(Context cxt) {
ActivityManager am = (ActivityManager) cxt
.getSystemService(Context.ACTIVITY_SERVICE);
MemoryInfo mi = new MemoryInfo();
am.getMemoryInfo(mi);
return (int) (mi.availMem / (1024 * 1024));
}
/**
* clean services and background
*
* @param cxt context
* @return clean app count
*/
public static int gc(Context cxt) {
long i = getDeviceUsableMemory(cxt);
int count = 0; // clean app count
ActivityManager am = (ActivityManager) cxt
.getSystemService(Context.ACTIVITY_SERVICE);
// get services which are running.
List<RunningServiceInfo> serviceList = am.getRunningServices(100);
if (serviceList != null)
for (RunningServiceInfo service : serviceList) {
if (service.pid == android.os.Process.myPid())
continue;
try {
android.os.Process.killProcess(service.pid);
count++;
} catch (Exception e) {
e.getStackTrace();
continue;
}
}
// get processes which are running
List<RunningAppProcessInfo> processList = am.getRunningAppProcesses();
if (processList != null)
for (RunningAppProcessInfo process : processList) {
// >RunningAppProcessInfo.IMPORTANCE_SERVICE -> NULL process
// >RunningAppProcessInfo.IMPORTANCE_VISIBLE -> background process
if (process.importance > RunningAppProcessInfo.IMPORTANCE_VISIBLE) {
// pkgList get packages in this process
String[] pkgList = process.pkgList;
for (String pkgName : pkgList) {
Log.d(TAG, "======killing:" + pkgName);
try {
am.killBackgroundProcesses(pkgName);
count++;
} catch (Exception e) {
e.getStackTrace();
continue;
}
}
}
}
Log.d(TAG, "Clean" + (getDeviceUsableMemory(cxt) - i) + "M memory!");
return count;
}
} | app/src/main/java/org/xwiki/android/authenticator/utils/SystemTools.java | /*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* 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.xwiki.android.authenticator.utils;
import android.app.ActivityManager;
import android.app.ActivityManager.MemoryInfo;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.Application;
import android.app.KeyguardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.telephony.TelephonyManager;
import android.util.Log;
import org.xwiki.android.authenticator.exceptions.ReadPhoneStateException;
import java.io.File;
import java.security.MessageDigest;
import java.util.List;
/**
* system tools
*/
public final class SystemTools {
private static final String TAG = "SystemTools";
/**
* Get IMEI
* @throws ReadPhoneStateException - will be thrown in cases when need to get permission to read
* phone state
*/
public static String getPhoneIMEI(Context cxt) throws ReadPhoneStateException{
TelephonyManager tm = (TelephonyManager) cxt
.getSystemService(Context.TELEPHONY_SERVICE);
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
return tm.getImei();
} else {
return tm.getMeid();
}
} catch (SecurityException e) {
throw new ReadPhoneStateException(e);
}
}
/**
* return System version
*
* @return like 2.3.3
*/
public static String getSystemVersion() {
return android.os.Build.VERSION.RELEASE;
}
/**
* check whether network is connected
*/
public static boolean checkNet(Context context) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
if (info != null && info.isAvailable()) return true;
return false;
}
public static boolean checkWifi(Context context) {
WifiManager mWifiManager = (WifiManager) context
.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = mWifiManager.getConnectionInfo();
int ipAddress = wifiInfo == null ? 0 : wifiInfo.getIpAddress();
if (mWifiManager.isWifiEnabled() && ipAddress != 0) {
return true;
} else {
return false;
}
}
/**
* foreground or background
*/
public static boolean isBackground(Context context) {
ActivityManager activityManager = (ActivityManager) context
.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningAppProcessInfo> appProcesses = activityManager
.getRunningAppProcesses();
for (RunningAppProcessInfo appProcess : appProcesses) {
if (appProcess.processName.equals(context.getPackageName())) {
if (appProcess.importance == RunningAppProcessInfo.IMPORTANCE_BACKGROUND) {
// background
return true;
} else {
// foreground
return false;
}
}
}
return false;
}
/**
* whether phone is sleeping
*/
public static boolean isSleeping(Context context) {
KeyguardManager kgMgr = (KeyguardManager) context
.getSystemService(Context.KEYGUARD_SERVICE);
boolean isSleeping = kgMgr.inKeyguardRestrictedInputMode();
return isSleeping;
}
/**
* apk install
*
* @param context
* @param file
*/
public static void installApk(Context context, File file) {
Intent intent = new Intent();
intent.setAction("android.intent.action.VIEW");
intent.addCategory("android.intent.category.DEFAULT");
intent.setType("application/vnd.android.package-archive");
intent.setData(Uri.fromFile(file));
intent.setDataAndType(Uri.fromFile(file),
"application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
/**
* get app version name
*/
public static String getAppVersionName(Context context) {
String version = "0";
try {
version = context.getPackageManager().getPackageInfo(
context.getPackageName(), 0).versionName;
} catch (NameNotFoundException e) {
throw new RuntimeException(SystemTools.class.getName()
+ "the application not found");
}
return version;
}
/**
* get app version code
*/
public static int getAppVersionCode(Context context) {
int version = 0;
try {
version = context.getPackageManager().getPackageInfo(
context.getPackageName(), 0).versionCode;
} catch (NameNotFoundException e) {
throw new RuntimeException(SystemTools.class.getName()
+ "the application not found");
}
return version;
}
/**
* return Home,run in background
*/
public static void goHome(Context context) {
Intent mHomeIntent = new Intent(Intent.ACTION_MAIN);
mHomeIntent.addCategory(Intent.CATEGORY_HOME);
mHomeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
context.startActivity(mHomeIntent);
}
/**
* get application signature
*
* @param context
* @param pkgName
*/
public static String getSign(Context context, String pkgName) {
try {
PackageInfo pis = context.getPackageManager().getPackageInfo(
pkgName, PackageManager.GET_SIGNATURES);
return hexdigest(pis.signatures[0].toByteArray());
} catch (NameNotFoundException e) {
throw new RuntimeException(SystemTools.class.getName() + "the "
+ pkgName + "'s application not found");
}
}
/**
* transfer signature to 32bit
*/
private static String hexdigest(byte[] paramArrayOfByte) {
final char[] hexDigits = {48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 97,
98, 99, 100, 101, 102};
try {
MessageDigest localMessageDigest = MessageDigest.getInstance("MD5");
localMessageDigest.update(paramArrayOfByte);
byte[] arrayOfByte = localMessageDigest.digest();
char[] arrayOfChar = new char[32];
for (int i = 0, j = 0; ; i++, j++) {
if (i >= 16) {
return new String(arrayOfChar);
}
int k = arrayOfByte[i];
arrayOfChar[j] = hexDigits[(0xF & k >>> 4)];
arrayOfChar[++j] = hexDigits[(k & 0xF)];
}
} catch (Exception e) {
}
return "";
}
/**
* available memory size
*
* @param cxt context
* @return memory size
*/
public static int getDeviceUsableMemory(Context cxt) {
ActivityManager am = (ActivityManager) cxt
.getSystemService(Context.ACTIVITY_SERVICE);
MemoryInfo mi = new MemoryInfo();
am.getMemoryInfo(mi);
return (int) (mi.availMem / (1024 * 1024));
}
/**
* clean services and background
*
* @param cxt context
* @return clean app count
*/
public static int gc(Context cxt) {
long i = getDeviceUsableMemory(cxt);
int count = 0; // clean app count
ActivityManager am = (ActivityManager) cxt
.getSystemService(Context.ACTIVITY_SERVICE);
// get services which are running.
List<RunningServiceInfo> serviceList = am.getRunningServices(100);
if (serviceList != null)
for (RunningServiceInfo service : serviceList) {
if (service.pid == android.os.Process.myPid())
continue;
try {
android.os.Process.killProcess(service.pid);
count++;
} catch (Exception e) {
e.getStackTrace();
continue;
}
}
// get processes which are running
List<RunningAppProcessInfo> processList = am.getRunningAppProcesses();
if (processList != null)
for (RunningAppProcessInfo process : processList) {
// >RunningAppProcessInfo.IMPORTANCE_SERVICE -> NULL process
// >RunningAppProcessInfo.IMPORTANCE_VISIBLE -> background process
if (process.importance > RunningAppProcessInfo.IMPORTANCE_VISIBLE) {
// pkgList get packages in this process
String[] pkgList = process.pkgList;
for (String pkgName : pkgList) {
Log.d(TAG, "======killing:" + pkgName);
try {
am.killBackgroundProcesses(pkgName);
count++;
} catch (Exception e) {
e.getStackTrace();
continue;
}
}
}
}
Log.d(TAG, "Clean" + (getDeviceUsableMemory(cxt) - i) + "M memory!");
return count;
}
} | make SystemTools#checkWifi to receive Application context for except cases with memory leak
| app/src/main/java/org/xwiki/android/authenticator/utils/SystemTools.java | make SystemTools#checkWifi to receive Application context for except cases with memory leak | <ide><path>pp/src/main/java/org/xwiki/android/authenticator/utils/SystemTools.java
<ide> return false;
<ide> }
<ide>
<del> public static boolean checkWifi(Context context) {
<del> WifiManager mWifiManager = (WifiManager) context
<del> .getSystemService(Context.WIFI_SERVICE);
<add> public static boolean checkWifi(Application context) {
<add> WifiManager mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
<ide> WifiInfo wifiInfo = mWifiManager.getConnectionInfo();
<ide> int ipAddress = wifiInfo == null ? 0 : wifiInfo.getIpAddress();
<del> if (mWifiManager.isWifiEnabled() && ipAddress != 0) {
<del> return true;
<del> } else {
<del> return false;
<del> }
<add> return mWifiManager.isWifiEnabled() && ipAddress != 0;
<ide> }
<ide>
<ide> |
|
Java | mpl-2.0 | ded08b0ea9b9beb62e16eedc30bdb7ac0b734610 | 0 | Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV | package org.helioviewer.jhv.plugins.eveplugin.lines;
import java.util.HashMap;
public class BandType {
private String baseUrl;
private BandGroup group;
private String label;
private String name;
private String unitLabel;
public HashMap<String, Double> warnLevels = new HashMap<String, Double>();
private double min;
private double max;
private boolean isLog = false;
@Override
public String toString() {
return label;
}
public String getBaseUrl() {
return baseUrl;
}
public void setBaseUrl(String baseUrl) {
this.baseUrl = baseUrl;
}
public BandGroup getGroup() {
return group;
}
public void setGroup(BandGroup group) {
this.group = group;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public String getUnitLabel() {
return unitLabel;
}
public void setUnitLabel(String unitLabel) {
this.unitLabel = unitLabel;
}
public HashMap<String, Double> getWarnLevels() {
return warnLevels;
}
public void setWarnLevels(HashMap<String, Double> warnLevels) {
this.warnLevels = warnLevels;
}
public double getMin() {
return min;
}
public void setMin(double min) {
this.min = min;
}
public double getMax() {
return max;
}
public void setMax(double max) {
this.max = max;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setScale(String scale) {
isLog = scale.equals("logarithmic");
}
public boolean isLogScale() {
return isLog;
}
}
| src/plugins/jhv-eveplugin/src/org/helioviewer/jhv/plugins/eveplugin/lines/BandType.java | package org.helioviewer.jhv.plugins.eveplugin.lines;
import java.util.HashMap;
public class BandType {
private String baseUrl;
private BandGroup group;
private String label;
private String name;
private String unitLabel;
public HashMap<String, Double> warnLevels = new HashMap<String, Double>();
private double min;
private double max;
private String scale = "";
private boolean isLog = false;
@Override
public String toString() {
return label;
}
public String getBaseUrl() {
return baseUrl;
}
public void setBaseUrl(String baseUrl) {
this.baseUrl = baseUrl;
}
public BandGroup getGroup() {
return group;
}
public void setGroup(BandGroup group) {
this.group = group;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public String getUnitLabel() {
return unitLabel;
}
public void setUnitLabel(String unitLabel) {
this.unitLabel = unitLabel;
}
public HashMap<String, Double> getWarnLevels() {
return warnLevels;
}
public void setWarnLevels(HashMap<String, Double> warnLevels) {
this.warnLevels = warnLevels;
}
public double getMin() {
return min;
}
public void setMin(double min) {
this.min = min;
}
public double getMax() {
return max;
}
public void setMax(double max) {
this.max = max;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setScale(String scale) {
this.scale = scale;
isLog = scale.equals("logarithmic");
}
public String getScale() {
return scale;
}
public boolean isLogScale() {
return isLog;
}
}
| reduce
git-svn-id: 4e353c0944fe8da334633afc35765ef362dec675@7295 b4e469a2-07ce-4b26-9273-4d7d95a670c7
| src/plugins/jhv-eveplugin/src/org/helioviewer/jhv/plugins/eveplugin/lines/BandType.java | reduce | <ide><path>rc/plugins/jhv-eveplugin/src/org/helioviewer/jhv/plugins/eveplugin/lines/BandType.java
<ide> public HashMap<String, Double> warnLevels = new HashMap<String, Double>();
<ide> private double min;
<ide> private double max;
<del> private String scale = "";
<ide> private boolean isLog = false;
<ide>
<ide> @Override
<ide> }
<ide>
<ide> public void setScale(String scale) {
<del> this.scale = scale;
<ide> isLog = scale.equals("logarithmic");
<del> }
<del>
<del> public String getScale() {
<del> return scale;
<ide> }
<ide>
<ide> public boolean isLogScale() { |
|
Java | mit | 5d9217396f0d2e7b4c6a79855e3625bfcf965054 | 0 | miamiheat710/RandomRestaurant,miamiheat710/RandomRestaurant | package com.chris.randomrestaurantgenerator.fragments;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.arlib.floatingsearchview.FloatingSearchView;
import com.arlib.floatingsearchview.suggestions.model.SearchSuggestion;
import com.chris.randomrestaurantgenerator.BuildConfig;
import com.chris.randomrestaurantgenerator.MainActivity;
import com.chris.randomrestaurantgenerator.R;
import com.chris.randomrestaurantgenerator.managers.UnscrollableLinearLayoutManager;
import com.chris.randomrestaurantgenerator.models.Restaurant;
import com.chris.randomrestaurantgenerator.utils.LocationProviderHelper;
import com.chris.randomrestaurantgenerator.utils.TwoStepOAuth;
import com.chris.randomrestaurantgenerator.utils.TypeOfError;
import com.chris.randomrestaurantgenerator.views.MainRestaurantCardAdapter;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.scribe.builder.ServiceBuilder;
import org.scribe.exceptions.OAuthConnectionException;
import org.scribe.model.OAuthRequest;
import org.scribe.model.Response;
import org.scribe.model.Token;
import org.scribe.model.Verb;
import org.scribe.oauth.OAuthService;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import fr.castorflex.android.circularprogressbar.CircularProgressBar;
import fr.castorflex.android.circularprogressbar.CircularProgressDrawable;
import pub.devrel.easypermissions.EasyPermissions;
import uk.co.deanwild.materialshowcaseview.MaterialShowcaseSequence;
import uk.co.deanwild.materialshowcaseview.MaterialShowcaseView;
import uk.co.deanwild.materialshowcaseview.ShowcaseConfig;
import uk.co.deanwild.materialshowcaseview.shape.CircleShape;
import uk.co.deanwild.materialshowcaseview.shape.RectangleShape;
/**
* A fragment containing the main activity.
* Responsible for displaying to the user a random restaurant based off their location / zip code.
*/
public class MainActivityFragment extends Fragment implements
OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, EasyPermissions.PermissionCallbacks {
FloatingSearchView searchLocationBox;
EditText filterBox;
Button generate;
int generateBtnColor;
RelativeLayout rootLayout;
RecyclerView restaurantView;
LinearLayout mapCardContainer;
MapView mapView;
GoogleMap map;
GoogleApiClient mGoogleApiClient;
MainRestaurantCardAdapter mainRestaurantCardAdapter;
LocationProviderHelper locationHelper;
Restaurant currentRestaurant;
ArrayList<Restaurant> restaurants = new ArrayList<>();
OAuthService service;
Token accessToken;
int errorInQuery;
boolean taskRunning = false;
boolean restartQuery = true;
boolean runBackgroundQueryAfter = true;
String searchQuery = "";
String filterQuery = "";
ArrayList<String> multiFilters = new ArrayList<>();
CircularProgressBar progressBar;
AsyncTask initialYelpQuery;
AsyncTask backgroundYelpQuery;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
rootLayout = (RelativeLayout) inflater.inflate(R.layout.fragment_main, container, false);
restaurantView = (RecyclerView) rootLayout.findViewById(R.id.restaurantView);
restaurantView.setLayoutManager(new UnscrollableLinearLayoutManager(getContext()));
mapCardContainer = (LinearLayout) rootLayout.findViewById(R.id.cardMapLayout);
mapView = (MapView) rootLayout.findViewById(R.id.mapView);
// https://code.google.com/p/gmaps-api-issues/issues/detail?id=6237#c9
final Bundle mapViewSavedInstanceState = savedInstanceState != null ? savedInstanceState.getBundle("mapViewSaveState") : null;
mapView.onCreate(mapViewSavedInstanceState);
filterBox = (EditText) rootLayout.findViewById(R.id.filterBox);
generate = (Button) rootLayout.findViewById(R.id.generate);
generateBtnColor = Color.parseColor("#F6511D");
// Build OAuth service.
service = new ServiceBuilder().provider(TwoStepOAuth.class).apiKey(TwoStepOAuth.getConsumerKey())
.apiSecret(TwoStepOAuth.getConsumerSecret()).build();
accessToken = new Token(TwoStepOAuth.getToken(), TwoStepOAuth.getTokenSecret());
progressBar = (CircularProgressBar) rootLayout.findViewById(R.id.circularProgressBarMainFragment);
ItemTouchHelper.SimpleCallback simpleCallback = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
@Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
return false;
}
@Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
// If user has swiped left, perform a click on the Generate button.
if (direction == 4)
generate.performClick();
// If user has swiped right, open Yelp to current restaurant's page.
if (direction == 8) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(currentRestaurant.getUrl())));
// We don't want to remove the restaurant here, so we add it back to the restaurantView.
mainRestaurantCardAdapter.remove();
mainRestaurantCardAdapter.add(currentRestaurant);
}
}
};
ItemTouchHelper itemTouchHelper = new ItemTouchHelper(simpleCallback);
itemTouchHelper.attachToRecyclerView(restaurantView);
return rootLayout;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Create an instance of GoogleAPIClient.
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.enableAutoManage(getActivity(), this)
.addApi(LocationServices.API)
.build();
}
// Must be defined in onActivityCreated() because searchLocationBox is part of MainActivity.
searchLocationBox = (FloatingSearchView) getActivity().findViewById(R.id.searchBox);
// Create LocationProviderHelper instance.
locationHelper = new LocationProviderHelper(getActivity(), searchLocationBox,
mGoogleApiClient);
// Get Google Map using OnMapReadyCallback
mapView.getMapAsync(this);
if (savedInstanceState != null) {
currentRestaurant = savedInstanceState.getParcelable("currentRestaurant");
searchLocationBox.setSearchText(savedInstanceState.getString("locationQuery"));
filterBox.setText(savedInstanceState.getString("filterQuery"));
restaurants = savedInstanceState.getParcelableArrayList("restaurants");
Log.d("RRG", "restored saved instance state");
}
// Define actions on menu button clicks inside searchLocationBox.
searchLocationBox.setOnMenuItemClickListener(new FloatingSearchView.OnMenuItemClickListener() {
@Override
public void onActionMenuItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.search_box_gps)
locationHelper.requestLocation();
else if (id == R.id.search_box_filter) {
if (filterBox.getVisibility() == View.GONE) {
filterBox.setVisibility(View.VISIBLE);
// Show tutorial about entering multiple filters.
displayShowcaseViewFilterBox();
}
else if (filterBox.getVisibility() == View.VISIBLE)
filterBox.setVisibility(View.GONE);
}
}
});
searchLocationBox.setOnSearchListener(new FloatingSearchView.OnSearchListener() {
@Override
public void onSuggestionClicked(SearchSuggestion searchSuggestion) {}
@Override
public void onSearchAction(String currentQuery) {
searchLocationBox.setSearchText(currentQuery);
searchLocationBox.setSearchBarTitle(currentQuery);
}
});
// Listener for when the user clicks done on keyboard after their input.
filterBox.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
hideSoftKeyboard();
generate.performClick();
return true;
}
return false;
}
});
// When the user clicks the Generate button.
generate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
/**
* If the user doesn't wait on the task to complete, warn them it is still running
* so we can prevent a long stack of requests from piling up.
*/
if (taskRunning) {
Toast.makeText(getActivity(), R.string.string_task_running_msg, Toast.LENGTH_SHORT).show();
return;
}
filterBox.setVisibility(View.GONE);
/**
* Initialize searchQuery and filterQuery if they're empty.
* Else set restartQuery to true if the queries have changed.
*/
if (searchQuery.isEmpty() && filterQuery.isEmpty()) {
searchQuery = searchLocationBox.getQuery();
filterQuery = filterBox.getText().toString();
}
else if (searchQuery.compareTo(searchLocationBox.getQuery()) != 0 ||
filterQuery.compareTo(filterBox.getText().toString()) != 0) {
restartQuery = true;
runBackgroundQueryAfter = true;
restaurants.clear();
searchQuery = searchLocationBox.getQuery();
filterQuery = filterBox.getText().toString();
// We want to use GPS if searchQuery contains the string "Current Location".
LocationProviderHelper.useGPS = searchQuery.contains(getActivity()
.getString(R.string.string_current_location));
}
if (LocationProviderHelper.useGPS) {
/**
* Check to make sure the location is not null before starting.
* Else, begin the AsyncTask.
*/
Location location = locationHelper.getLocation();
if (location == null) {
displayAlertDialog(R.string.string_location_not_found, "Error");
} else {
String filterBoxText = filterBox.getText().toString();
List<String> filterList = Arrays.asList(filterBox.getText().toString().split(","));
/**
* Split the filters by comma if the user wants multiple filters.
* Run separate query for each filter.
*
* If multiFilter contains all of filterList and restaurants is empty,
* that the user has exhausted through all the restaurants, and we
* must restart the query, so clear the multiFilters to start over.
*/
if (multiFilters.containsAll(filterList) && restaurants.isEmpty())
multiFilters.clear();
if (filterBoxText.contains(",") && !multiFilters.containsAll(filterList)) {
multiFilters.clear();
multiFilters.addAll(filterList);
initialYelpQuery = new RunYelpQuery(
false,
String.valueOf(searchLocationBox.getQuery()),
multiFilters.get(0).trim(),
String.valueOf(location.getLatitude()),
String.valueOf(location.getLongitude()))
.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
/**
* Skip the first filter because we run the initial query
* with the first filter above.
* Everything after will be a background query, hence the background
* query AsyncTask being run inside the body of this for loop.
*/
for (String filter : multiFilters.subList(1, multiFilters.size())) {
backgroundYelpQuery = new RunYelpQueryBackground(0)
.executeOnExecutor(
AsyncTask.THREAD_POOL_EXECUTOR,
String.valueOf(searchLocationBox.getQuery()),
filter.trim(),
String.valueOf(location.getLatitude()),
String.valueOf(location.getLongitude()));
}
}
else {
initialYelpQuery = new RunYelpQuery(
runBackgroundQueryAfter,
String.valueOf(searchLocationBox.getQuery()),
String.valueOf(filterBox.getText()),
String.valueOf(location.getLatitude()),
String.valueOf(location.getLongitude()))
.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
}
} else {
String filterBoxText = filterBox.getText().toString();
List<String> filterList = Arrays.asList(filterBox.getText().toString().split(","));
/**
* Verify that the user has actually entered a location.
* Else, begin the AsyncTask.
*/
if (searchLocationBox.getQuery().length() == 0 && restaurants.size() == 0) {
displayAlertDialog(R.string.string_enter_valid_location, "Error");
} else {
/**
* Split the filters by comma if the user wants multiple filters.
* Run separate query for each filter.
*
* If multiFilter contains all of filterList and restaurants is empty,
* that the user has exhausted through all the restaurants, and we
* must restart the query, so clear the multiFilters to start over.
*/
if (multiFilters.containsAll(filterList) && restaurants.isEmpty())
multiFilters.clear();
if (filterBoxText.contains(",") && !multiFilters.containsAll(filterList)) {
multiFilters.clear();
multiFilters.addAll(filterList);
initialYelpQuery = new RunYelpQuery(
false,
String.valueOf(searchLocationBox.getQuery()),
multiFilters.get(0).trim())
.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
/**
* Skip the first filter because we run the initial query
* with the first filter above.
* Everything after will be a background query, hence the background
* query AsyncTask being run inside the body of this for loop.
*/
for (String filter : multiFilters.subList(1, multiFilters.size())) {
backgroundYelpQuery = new RunYelpQueryBackground(0)
.executeOnExecutor(
AsyncTask.THREAD_POOL_EXECUTOR,
String.valueOf(searchLocationBox.getQuery()),
filter.trim());
}
}
else {
initialYelpQuery = new RunYelpQuery(
runBackgroundQueryAfter,
String.valueOf(searchLocationBox.getQuery()),
String.valueOf(filterBox.getText()))
.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
}
}
}
});
if (savedInstanceState != null) {
searchLocationBox.setSearchText(savedInstanceState.getString("locationQuery"));
filterBox.setText(savedInstanceState.getString("filterQuery"));
currentRestaurant = savedInstanceState.getParcelable("currentRestaurant");
restaurants = savedInstanceState.getParcelableArrayList("restaurants");
}
// Reset all cache for showcase id.
//MaterialShowcaseView.resetAll(getContext());
// A tutorial that displays only once explaining the input to the app.
MaterialShowcaseSequence sequence = new MaterialShowcaseSequence(getActivity(), BuildConfig.VERSION_NAME + "MAIN");
ShowcaseConfig config = new ShowcaseConfig();
config.setDelay(250);
sequence.setConfig(config);
sequence.addSequenceItem(buildShowcaseView(searchLocationBox, new RectangleShape(0, 0),
"Enter any zip code, city, or address here.\n\n" +
"Click the GPS icon to use your current location.\n\n" +
"Filter your results by clicking the magnifying glass if you're in the mood for something specific."
));
sequence.start();
}
@Override
public void onSaveInstanceState(Bundle outState) {
// https://code.google.com/p/gmaps-api-issues/issues/detail?id=6237#c9
final Bundle mapViewSaveState = new Bundle(outState);
mapView.onSaveInstanceState(mapViewSaveState);
outState.putBundle("mapViewSaveState", mapViewSaveState);
outState.putString("locationQuery", searchLocationBox.getQuery());
outState.putString("filterQuery", String.valueOf(filterBox.getText()));
outState.putParcelable("currentRestaurant", currentRestaurant);
outState.putParcelableArrayList("restaurants", restaurants);
super.onSaveInstanceState(outState);
}
@Override
public void onPause() {
super.onPause();
mapView.onPause();
// Try to cancel the AsyncTask.
if (initialYelpQuery != null && initialYelpQuery.getStatus() == AsyncTask.Status.RUNNING) {
initialYelpQuery.cancel(true);
enableGenerateButton();
if (mainRestaurantCardAdapter != null) {
mainRestaurantCardAdapter.remove();
mapCardContainer.setVisibility(View.GONE);
}
}
if (backgroundYelpQuery != null && backgroundYelpQuery.getStatus() == AsyncTask.Status.RUNNING)
backgroundYelpQuery.cancel(true);
}
@Override
public void onResume() {
super.onResume();
mapView.onResume();
// Refresh the RecyclerView on resume.
if (mainRestaurantCardAdapter != null)
mainRestaurantCardAdapter.notifyDataSetChanged();
}
@Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
Log.d("RRG", "Destroyed");
// Try to cancel the AsyncTask.
if (initialYelpQuery != null && initialYelpQuery.getStatus() == AsyncTask.Status.RUNNING)
initialYelpQuery.cancel(true);
if (backgroundYelpQuery != null && backgroundYelpQuery.getStatus() == AsyncTask.Status.RUNNING)
backgroundYelpQuery.cancel(true);
}
// Google Maps API callback for MapFragment.
@Override
public void onMapReady(GoogleMap googleMap) {
map = googleMap;
}
// Callback for requesting permissions.
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
// Forward results to EasyPermissions
EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
}
@Override
public void onPermissionsGranted(int requestCode, List<String> perms) {
locationHelper.onPermissionsGranted(requestCode, perms);
}
@Override
public void onPermissionsDenied(int requestCode, List<String> perms) {
locationHelper.onPermissionsDenied(requestCode, perms);
}
// Callback for checking location settings.
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case LocationProviderHelper.MY_REQUEST_CHECK_SETTINGS:
switch (resultCode) {
case Activity.RESULT_OK: {
// All required changes were successfully made
Log.d("RRG", "Location enabled by user!");
locationHelper.requestLocation();
break;
}
case Activity.RESULT_CANCELED: {
// The user was asked to change settings, but chose not to
Log.d("RRG", "Location not enabled, user cancelled.");
locationHelper.dismissLocationUpdater();
break;
}
default: {
Log.d("RRG", "User opted to never ask for location. ");
break;
}
}
break;
}
}
@Override
public void onConnected(@Nullable Bundle bundle) {
Log.d("RRG", "Connected to Google Play Services.");
}
@Override
public void onConnectionSuspended(int i) {
Log.d("RRG", "onConnectionSuspended: " + i);
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
Toast.makeText(getContext(), "Error " + connectionResult.getErrorCode() +
": failed to connect to Google Play Services. This may affect acquiring your location.",
Toast.LENGTH_LONG).show();
}
/**
* Function to hide the keyboard.
*/
private void hideSoftKeyboard() {
Activity activity = getActivity();
if (activity.getCurrentFocus() != null) {
InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
}
}
/**
* Helper function to build a custom ShowcaseView for a sequence.
*
* @param target: the target view that will be highlighted.
* @param shape: the type of shape.
* @param contentText: the text to be displayed.
*/
private MaterialShowcaseView buildShowcaseView(View target, uk.co.deanwild.materialshowcaseview.shape.Shape shape, String contentText) {
return new MaterialShowcaseView.Builder(getActivity())
.setTarget(target)
.setShape(shape)
.setMaskColour(Color.rgb(0, 166, 237))
.setContentText(contentText)
.setDismissText("GOT IT")
.build();
}
/**
* Function to disable the generate button.
*/
private void disableGenerateButton() {
// Signal the task is running
taskRunning = true;
generate.setText(R.string.string_button_text_loading);
generate.setBackgroundColor(Color.GRAY);
generate.setEnabled(false);
}
/**
* Function to enable the generate button.
*/
private void enableGenerateButton() {
// Signal the task is finished
taskRunning = false;
generate.setText(R.string.string_button_text_generate);
generate.setBackgroundColor(generateBtnColor);
generate.setEnabled(true);
progressBar.setVisibility(View.GONE);
progressBar.progressiveStop();
}
/**
* Function to display the MaterialShowcaseView for filterBox.
*/
private void displayShowcaseViewFilterBox() {
MaterialShowcaseSequence filterShowcase = new MaterialShowcaseSequence(getActivity(), BuildConfig.VERSION_NAME + "FILTER");
ShowcaseConfig config = new ShowcaseConfig();
config.setDelay(250);
filterShowcase.setConfig(config);
filterShowcase.addSequenceItem(buildShowcaseView(filterBox, new RectangleShape(0, 0),
"In the mood for multiple things? List your filters separated by a comma to combine the results!"
));
filterShowcase.start();
}
/**
* Helper function to display an AlertDialog
* @param stringToDisplay: the string to display in the alert.
* @param title: the title of the dialog.
*/
private void displayAlertDialog(int stringToDisplay, String title) {
AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
alert.setNeutralButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alert.setTitle(title);
alert.setMessage(getActivity().getString(stringToDisplay));
alert.show();
}
/**
* Function to query Yelp for restaurants. Returns an ArrayList of Restaurants.
*
* @param lat: the user's latitude, null if @param input is not empty.
* @param lon: the user's longitude, null if @param input is not empty.
* @param input the user's location string, e.g. zip, city, etc.
* @param filter the user's filterBox string, e.g. sushi, bbq, etc.
* @param offset the offset for the Yelp query.
* @param whichAsyncTask the AsyncTask to cancel if necessary.
* @return true if successful querying Yelp; false otherwise.
*/
private boolean queryYelp(String lat, String lon, String input,
String filter, int offset, int whichAsyncTask) {
try {
OAuthRequest request;
if (LocationProviderHelper.useGPS) {
request = new OAuthRequest(Verb.GET, "https://api.yelp.com/v2/search?" + filter +
"&ll=" + lat + "," + lon + "&offset=" + offset);
request.setConnectTimeout(10, TimeUnit.SECONDS);
request.setReadTimeout(10, TimeUnit.SECONDS);
Log.d("RRG", "request made: " + "https://api.yelp.com/v2/search?" + filter +
"&ll=" + lat + "," + lon + "&offset=" + offset);
} else {
request = new OAuthRequest(Verb.GET, "https://api.yelp.com/v2/search?" + filter +
"&location=" + input + "&offset=" + offset);
request.setConnectTimeout(10, TimeUnit.SECONDS);
request.setReadTimeout(10, TimeUnit.SECONDS);
Log.d("RRG", "request made: " + "https://api.yelp.com/v2/search?" + filter +
"&location=" + input + "&offset=" + offset);
}
service.signRequest(accessToken, request);
Response response = request.send();
// Get JSON array that holds the restaurants from Yelp.
JSONArray jsonBusinessesArray = new JSONObject(response.getBody())
.getJSONArray("businesses");
int length = jsonBusinessesArray.length();
// This occurs if a network communication error occurs or if no restaurants were found.
if (length <= 0) {
errorInQuery = TypeOfError.NO_RESTAURANTS;
return false;
}
for (int i = 0; i < length; i++) {
if (whichAsyncTask == 0 && initialYelpQuery.isCancelled())
break;
else if (whichAsyncTask == 1 && backgroundYelpQuery.isCancelled())
break;
Restaurant res = convertJSONToRestaurant(jsonBusinessesArray.getJSONObject(i));
if (res != null)
restaurants.add(res);
}
if (restaurants.isEmpty()) {
errorInQuery = TypeOfError.NO_RESTAURANTS;
return false;
}
} catch (OAuthConnectionException e) {
errorInQuery = TypeOfError.NETWORK_CONNECTION_ERROR;
e.printStackTrace();
return false;
} catch (JSONException e) {
if (e.getMessage().contains("No value for businesses"))
errorInQuery = TypeOfError.NO_RESTAURANTS;
else if (e.getMessage().contains("No value for"))
errorInQuery = TypeOfError.MISSING_INFO;
e.printStackTrace();
return false;
} catch (Exception e) {
if (e.getMessage().contains("timed out")) errorInQuery = TypeOfError.TIMED_OUT;
e.printStackTrace();
return false;
}
errorInQuery = TypeOfError.NO_ERROR;
return true;
}
/**
* Convert JSON to a Restaurant object that encapsulates a restaurant from Yelp.
*
* @param obj: JSONObejct that holds all restaurant info.
* @return Restaurant or null if an error occurs.
*/
private Restaurant convertJSONToRestaurant(JSONObject obj) {
try {
// Getting the JSON array of categories
JSONArray categoriesJSON = obj.getJSONArray("categories");
ArrayList<String> categories = new ArrayList<>();
for (int i = 0; i < categoriesJSON.length(); i += 2)
for (int j = 0; j < categoriesJSON.getJSONArray(i).length(); j += 2)
categories.add(categoriesJSON.getJSONArray(i).getString(j));
// Getting the restaurant's location information
JSONObject locationJSON = obj.getJSONObject("location");
double lat = locationJSON.getJSONObject("coordinate").getDouble("latitude");
double lon = locationJSON.getJSONObject("coordinate").getDouble("longitude");
float distance;
Location restaurantLoc = new Location("restaurantLoc");
restaurantLoc.setLatitude(lat);
restaurantLoc.setLongitude(lon);
if (LocationProviderHelper.useGPS) {
distance = locationHelper.getLocation().distanceTo(restaurantLoc);
} else {
Geocoder geocoder = new Geocoder(getContext());
List<Address> addressList;
try {
addressList = geocoder.getFromLocationName(searchLocationBox.getQuery(), 1);
double estimatedLat = addressList.get(0).getLatitude();
double estimatedLon = addressList.get(0).getLongitude();
Location estimatedLocation = new Location("estimatedLocation");
estimatedLocation.setLatitude(estimatedLat);
estimatedLocation.setLongitude(estimatedLon);
distance = estimatedLocation.distanceTo(restaurantLoc);
} catch (IOException io) {
/*
* If we get an IOException, that means geocoder.getFromLocationName() timed out.
* Sometimes it times out, so set distance to 0 if it does.
* See below bug report:
* https://code.google.com/p/gmaps-api-issues/issues/detail?id=9153
*/
distance = 0.0f;
}
}
distance *= 0.000621371; // Convert to miles
// Getting restaurant's address
JSONArray addressJSON = locationJSON.getJSONArray("display_address");
ArrayList<String> address = new ArrayList<>();
for (int i = 0; i < addressJSON.length(); i++)
address.add(addressJSON.getString(i));
// Get deals if JSON contains deals object.
String deals;
try {
JSONArray dealsArray = obj.getJSONArray("deals");
ArrayList<String> dealsList = new ArrayList<>();
for (int i = 0; i < dealsArray.length(); i++) {
JSONObject jsonObject = dealsArray.getJSONObject(i);
dealsList.add(jsonObject.getString("title"));
}
deals = dealsList.toString().replace("[", "").replace("]", "").trim();
} catch (Exception ignored) {
deals = "";
}
// Construct a new Restaurant object with all the info we gathered above and return it
return new Restaurant(obj.getString("name"), (float) obj.getDouble("rating"),
obj.getString("rating_img_url_large"), obj.getString("image_url"), obj.getInt("review_count"),
obj.getString("url"), categories, address, deals, distance, lat, lon);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* Update the map with a new marker based on restaurant's coordinates.
*
* @param restaurant the restaurant that will be on the map.
*/
private void updateMapWithRestaurant(Restaurant restaurant) {
// Clear all the markers on the map.
map.clear();
LatLng latLng = new LatLng(restaurant.getLat(), restaurant.getLon());
map.addMarker(new MarkerOptions().position(latLng).title(String.format("%s: %s",
restaurant.getName(), restaurant.getAddress())
.replace("[", "").replace("]", "").trim()));
map.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 14));
mapCardContainer.setVisibility(View.VISIBLE);
}
// Async task that connects to Yelp's API and queries for restaurants based on location / zip code.
public class RunYelpQuery extends AsyncTask<Void, Void, Restaurant> {
String[] params;
String userInputStr;
String userFilterStr;
boolean successfulQuery;
public RunYelpQuery(boolean runBackgroundQuery, String... params) {
runBackgroundQueryAfter = runBackgroundQuery;
this.params = params;
userInputStr = params[0];
userFilterStr = params[1];
}
@Override
protected void onPreExecute() {
super.onPreExecute();
disableGenerateButton();
if (restartQuery) {
((CircularProgressDrawable) progressBar.getIndeterminateDrawable()).start();
progressBar.setVisibility(View.VISIBLE);
}
}
@Override
protected void onCancelled() {
super.onCancelled();
Log.d("RRG", "Cancelled Yelp AsyncTask");
restartQuery = true;
enableGenerateButton();
}
@Override
protected Restaurant doInBackground(Void... aVoid) {
if (isCancelled()) return null;
// Check for parameters so we can send the appropriate request based on user input.
String lat = "";
String lon = "";
try {
// If the user entered some input, make sure to encode all spaces and "+" for URL query.
if (userInputStr.length() != 0) {
userInputStr = userInputStr.replaceAll(" ", "+");
}
// If the user entered a filterBox, make sure to encode all spaces and "+" for URL query.
if (userFilterStr.length() != 0) {
userFilterStr = userFilterStr.replaceAll(" ", "+");
// Add Yelp API query verb.
userFilterStr = String.format("term=%s", userFilterStr);
} else {
// Default search term.
userFilterStr = "term=food";
}
// If we have 4 parameters, then the user selected location and we must grab the lat / long.
if (params.length == 4) {
lat = params[2];
lon = params[3];
}
} catch (Exception e) {
e.printStackTrace();
}
if (restartQuery) {
restaurants.clear();
restartQuery = false;
}
// Get restaurants only when the restaurants list is empty.
Restaurant chosenRestaurant = null;
if (restaurants == null || restaurants.isEmpty()) {
successfulQuery = queryYelp(lat, lon, userInputStr, userFilterStr, 0, 0);
if (successfulQuery && !restaurants.isEmpty()) {
// Make sure the restaurants list is not empty before accessing it.
chosenRestaurant = restaurants.get(new Random().nextInt(restaurants.size()));
restaurants.remove(chosenRestaurant);
/**
* Run background query only if the following BOTH hold:
* 1) initially set to true from constructor
* 2) and successfulQuery is true
*/
if (runBackgroundQueryAfter)
runBackgroundQueryAfter = true;
}
} else if (restaurants != null && !restaurants.isEmpty()) {
chosenRestaurant = restaurants.get(new Random().nextInt(restaurants.size()));
restaurants.remove(chosenRestaurant);
}
// Return randomly chosen restaurant.
return chosenRestaurant;
}
// Set UI appropriate UI elements to display mRestaurant info.
@Override
protected void onPostExecute(Restaurant restaurant) {
if (restaurant == null) {
if (errorInQuery == TypeOfError.NO_RESTAURANTS) {
Toast.makeText(getContext(),
R.string.string_no_restaurants_found,
Toast.LENGTH_LONG).show();
restaurants.clear();
} else if (errorInQuery == TypeOfError.MISSING_INFO) {
// Try again if the current restaurant has missing info.
generate.performClick();
return;
}
else if (errorInQuery == TypeOfError.NETWORK_CONNECTION_ERROR) {
Toast.makeText(getContext(),
R.string.string_no_network,
Toast.LENGTH_LONG).show();
}
else if (errorInQuery == TypeOfError.TIMED_OUT) {
Toast.makeText(getContext(),
R.string.string_timed_out_msg,
Toast.LENGTH_LONG).show();
}
if (initialYelpQuery!= null) initialYelpQuery.cancel(true);
if (backgroundYelpQuery!= null) backgroundYelpQuery.cancel(true);
enableGenerateButton();
return;
}
currentRestaurant = restaurant;
// If the RecyclerView has not been set yet, set it with the currentRestaurant.
if (mainRestaurantCardAdapter == null) {
mainRestaurantCardAdapter = new MainRestaurantCardAdapter(getContext(), currentRestaurant);
restaurantView.setAdapter(mainRestaurantCardAdapter);
}
// These calls notify the RecyclerView that the data set has changed and we need to refresh.
mainRestaurantCardAdapter.remove();
mainRestaurantCardAdapter.add(currentRestaurant);
updateMapWithRestaurant(currentRestaurant);
enableGenerateButton();
if (runBackgroundQueryAfter) {
backgroundYelpQuery = new RunYelpQueryBackground(20).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, this.params);
runBackgroundQueryAfter = false;
}
// A tutorial that displays only once explaining the action that can be done on the restaurant card.
MaterialShowcaseSequence sequence = new MaterialShowcaseSequence(getActivity(), BuildConfig.VERSION_NAME + "CARD");
ShowcaseConfig config = new ShowcaseConfig();
config.setDelay(100);
sequence.setConfig(config);
sequence.addSequenceItem(buildShowcaseView(restaurantView, new RectangleShape(0, 0),
"Swipe left to dismiss. Swipe right to open in Yelp. Tap bookmark button to save it for later."));
sequence.addSequenceItem(buildShowcaseView(((MainActivity) getActivity()).getMenuItemView(R.id.action_saved_list),
new CircleShape(), "Tap here to view your saved list."));
sequence.start();
}
}
// Async task that runs in the background to query more restaurants from Yelp while the user
// goes through the initial list of restaurants.
public class RunYelpQueryBackground extends AsyncTask<String, Void, Void> {
int offset;
public RunYelpQueryBackground(int offset) {
this.offset = offset;
}
@Override
protected void onCancelled() {
super.onCancelled();
Log.d("RRG", "Cancelled background Yelp AsyncTask");
}
@Override
protected Void doInBackground(String... params) {
if (isCancelled()) return null;
// Check for parameters so we can send the appropriate request based on user input.
String lat = "";
String lon = "";
String userInputStr = params[0];
String userFilterStr = params[1];
try {
// If the user entered some input, make sure to encode all spaces and "+" for URL query.
if (userInputStr.length() != 0) {
userInputStr = userInputStr.replaceAll(" ", "+");
}
// If the user entered a filterBox, make sure to encode all spaces and "+" for URL query.
if (userFilterStr.length() != 0) {
userFilterStr = userFilterStr.replaceAll(" ", "+");
// Add Yelp API query verb.
userFilterStr = String.format("term=%s", userFilterStr);
} else {
// Default search term.
userFilterStr = "term=food";
}
// If we have 4 parameters, then the user selected location and we must grab the lat / long.
if (params.length == 4) {
lat = params[2];
lon = params[3];
}
} catch (Exception e) {
e.printStackTrace();
}
queryYelp(lat, lon, userInputStr, userFilterStr, offset, 1);
return null;
}
}
} | app/src/main/java/com/chris/randomrestaurantgenerator/fragments/MainActivityFragment.java | package com.chris.randomrestaurantgenerator.fragments;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.arlib.floatingsearchview.FloatingSearchView;
import com.arlib.floatingsearchview.suggestions.model.SearchSuggestion;
import com.chris.randomrestaurantgenerator.BuildConfig;
import com.chris.randomrestaurantgenerator.MainActivity;
import com.chris.randomrestaurantgenerator.R;
import com.chris.randomrestaurantgenerator.managers.UnscrollableLinearLayoutManager;
import com.chris.randomrestaurantgenerator.models.Restaurant;
import com.chris.randomrestaurantgenerator.utils.LocationProviderHelper;
import com.chris.randomrestaurantgenerator.utils.TwoStepOAuth;
import com.chris.randomrestaurantgenerator.utils.TypeOfError;
import com.chris.randomrestaurantgenerator.views.MainRestaurantCardAdapter;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.scribe.builder.ServiceBuilder;
import org.scribe.exceptions.OAuthConnectionException;
import org.scribe.model.OAuthRequest;
import org.scribe.model.Response;
import org.scribe.model.Token;
import org.scribe.model.Verb;
import org.scribe.oauth.OAuthService;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import fr.castorflex.android.circularprogressbar.CircularProgressBar;
import fr.castorflex.android.circularprogressbar.CircularProgressDrawable;
import pub.devrel.easypermissions.EasyPermissions;
import uk.co.deanwild.materialshowcaseview.MaterialShowcaseSequence;
import uk.co.deanwild.materialshowcaseview.MaterialShowcaseView;
import uk.co.deanwild.materialshowcaseview.ShowcaseConfig;
import uk.co.deanwild.materialshowcaseview.shape.CircleShape;
import uk.co.deanwild.materialshowcaseview.shape.RectangleShape;
/**
* A fragment containing the main activity.
* Responsible for displaying to the user a random restaurant based off their location / zip code.
*/
public class MainActivityFragment extends Fragment implements
OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, EasyPermissions.PermissionCallbacks {
FloatingSearchView searchLocationBox;
EditText filterBox;
Button generate;
int generateBtnColor;
RelativeLayout rootLayout;
RecyclerView restaurantView;
LinearLayout mapCardContainer;
MapView mapView;
GoogleMap map;
GoogleApiClient mGoogleApiClient;
MainRestaurantCardAdapter mainRestaurantCardAdapter;
LocationProviderHelper locationHelper;
Restaurant currentRestaurant;
ArrayList<Restaurant> restaurants = new ArrayList<>();
OAuthService service;
Token accessToken;
int errorInQuery;
boolean taskRunning = false;
boolean restartQuery = true;
boolean runBackgroundQueryAfter = true;
String searchQuery = "";
String filterQuery = "";
ArrayList<String> multiFilters = new ArrayList<>();
CircularProgressBar progressBar;
AsyncTask initialYelpQuery;
AsyncTask backgroundYelpQuery;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
rootLayout = (RelativeLayout) inflater.inflate(R.layout.fragment_main, container, false);
restaurantView = (RecyclerView) rootLayout.findViewById(R.id.restaurantView);
restaurantView.setLayoutManager(new UnscrollableLinearLayoutManager(getContext()));
mapCardContainer = (LinearLayout) rootLayout.findViewById(R.id.cardMapLayout);
mapView = (MapView) rootLayout.findViewById(R.id.mapView);
// https://code.google.com/p/gmaps-api-issues/issues/detail?id=6237#c9
final Bundle mapViewSavedInstanceState = savedInstanceState != null ? savedInstanceState.getBundle("mapViewSaveState") : null;
mapView.onCreate(mapViewSavedInstanceState);
filterBox = (EditText) rootLayout.findViewById(R.id.filterBox);
generate = (Button) rootLayout.findViewById(R.id.generate);
generateBtnColor = Color.parseColor("#F6511D");
// Build OAuth service.
service = new ServiceBuilder().provider(TwoStepOAuth.class).apiKey(TwoStepOAuth.getConsumerKey())
.apiSecret(TwoStepOAuth.getConsumerSecret()).build();
accessToken = new Token(TwoStepOAuth.getToken(), TwoStepOAuth.getTokenSecret());
progressBar = (CircularProgressBar) rootLayout.findViewById(R.id.circularProgressBarMainFragment);
ItemTouchHelper.SimpleCallback simpleCallback = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
@Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
return false;
}
@Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
// If user has swiped left, perform a click on the Generate button.
if (direction == 4)
generate.performClick();
// If user has swiped right, open Yelp to current restaurant's page.
if (direction == 8) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(currentRestaurant.getUrl())));
// We don't want to remove the restaurant here, so we add it back to the restaurantView.
mainRestaurantCardAdapter.remove();
mainRestaurantCardAdapter.add(currentRestaurant);
}
}
};
ItemTouchHelper itemTouchHelper = new ItemTouchHelper(simpleCallback);
itemTouchHelper.attachToRecyclerView(restaurantView);
return rootLayout;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Create an instance of GoogleAPIClient.
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.enableAutoManage(getActivity(), this)
.addApi(LocationServices.API)
.build();
}
// Must be defined in onActivityCreated() because searchLocationBox is part of MainActivity.
searchLocationBox = (FloatingSearchView) getActivity().findViewById(R.id.searchBox);
// Create LocationProviderHelper instance.
locationHelper = new LocationProviderHelper(getActivity(), searchLocationBox,
mGoogleApiClient);
// Get Google Map using OnMapReadyCallback
mapView.getMapAsync(this);
if (savedInstanceState != null) {
currentRestaurant = savedInstanceState.getParcelable("currentRestaurant");
searchLocationBox.setSearchText(savedInstanceState.getString("locationQuery"));
filterBox.setText(savedInstanceState.getString("filterQuery"));
restaurants = savedInstanceState.getParcelableArrayList("restaurants");
}
// Define actions on menu button clicks inside searchLocationBox.
searchLocationBox.setOnMenuItemClickListener(new FloatingSearchView.OnMenuItemClickListener() {
@Override
public void onActionMenuItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.search_box_gps)
locationHelper.requestLocation();
else if (id == R.id.search_box_filter) {
if (filterBox.getVisibility() == View.GONE) {
filterBox.setVisibility(View.VISIBLE);
// Show tutorial about entering multiple filters.
displayShowcaseViewFilterBox();
}
else if (filterBox.getVisibility() == View.VISIBLE)
filterBox.setVisibility(View.GONE);
}
}
});
searchLocationBox.setOnSearchListener(new FloatingSearchView.OnSearchListener() {
@Override
public void onSuggestionClicked(SearchSuggestion searchSuggestion) {}
@Override
public void onSearchAction(String currentQuery) {
searchLocationBox.setSearchText(currentQuery);
searchLocationBox.setSearchBarTitle(currentQuery);
}
});
// Listener for when the user clicks done on keyboard after their input.
filterBox.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
hideSoftKeyboard();
generate.performClick();
return true;
}
return false;
}
});
// When the user clicks the Generate button.
generate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
/**
* If the user doesn't wait on the task to complete, warn them it is still running
* so we can prevent a long stack of requests from piling up.
*/
if (taskRunning) {
Toast.makeText(getActivity(), R.string.string_task_running_msg, Toast.LENGTH_SHORT).show();
return;
}
filterBox.setVisibility(View.GONE);
/**
* Initialize searchQuery and filterQuery if they're empty.
* Else set restartQuery to true if the queries have changed.
*/
if (searchQuery.isEmpty() && filterQuery.isEmpty()) {
searchQuery = searchLocationBox.getQuery();
filterQuery = filterBox.getText().toString();
}
else if (searchQuery.compareTo(searchLocationBox.getQuery()) != 0 ||
filterQuery.compareTo(filterBox.getText().toString()) != 0) {
restartQuery = true;
runBackgroundQueryAfter = true;
restaurants.clear();
searchQuery = searchLocationBox.getQuery();
filterQuery = filterBox.getText().toString();
// We want to use GPS if searchQuery contains the string "Current Location".
LocationProviderHelper.useGPS = searchQuery.contains(getActivity()
.getString(R.string.string_current_location));
}
if (LocationProviderHelper.useGPS) {
/**
* Check to make sure the location is not null before starting.
* Else, begin the AsyncTask.
*/
Location location = locationHelper.getLocation();
if (location == null) {
displayAlertDialog(R.string.string_location_not_found, "Error");
} else {
String filterBoxText = filterBox.getText().toString();
List<String> filterList = Arrays.asList(filterBox.getText().toString().split(","));
/**
* Split the filters by comma if the user wants multiple filters.
* Run separate query for each filter.
*
* If multiFilter contains all of filterList and restaurants is empty,
* that the user has exhausted through all the restaurants, and we
* must restart the query, so clear the multiFilters to start over.
*/
if (multiFilters.containsAll(filterList) && restaurants.isEmpty())
multiFilters.clear();
if (filterBoxText.contains(",") && !multiFilters.containsAll(filterList)) {
multiFilters.clear();
multiFilters.addAll(filterList);
initialYelpQuery = new RunYelpQuery(
false,
String.valueOf(searchLocationBox.getQuery()),
multiFilters.get(0).trim(),
String.valueOf(location.getLatitude()),
String.valueOf(location.getLongitude()))
.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
/**
* Skip the first filter because we run the initial query
* with the first filter above.
* Everything after will be a background query, hence the background
* query AsyncTask being run inside the body of this for loop.
*/
for (String filter : multiFilters.subList(1, multiFilters.size())) {
backgroundYelpQuery = new RunYelpQueryBackground(0)
.executeOnExecutor(
AsyncTask.THREAD_POOL_EXECUTOR,
String.valueOf(searchLocationBox.getQuery()),
filter.trim(),
String.valueOf(location.getLatitude()),
String.valueOf(location.getLongitude()));
}
}
else {
initialYelpQuery = new RunYelpQuery(
runBackgroundQueryAfter,
String.valueOf(searchLocationBox.getQuery()),
String.valueOf(filterBox.getText()),
String.valueOf(location.getLatitude()),
String.valueOf(location.getLongitude()))
.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
}
} else {
String filterBoxText = filterBox.getText().toString();
List<String> filterList = Arrays.asList(filterBox.getText().toString().split(","));
/**
* Verify that the user has actually entered a location.
* Else, begin the AsyncTask.
*/
if (searchLocationBox.getQuery().length() == 0 && restaurants.size() == 0) {
displayAlertDialog(R.string.string_enter_valid_location, "Error");
} else {
/**
* Split the filters by comma if the user wants multiple filters.
* Run separate query for each filter.
*
* If multiFilter contains all of filterList and restaurants is empty,
* that the user has exhausted through all the restaurants, and we
* must restart the query, so clear the multiFilters to start over.
*/
if (multiFilters.containsAll(filterList) && restaurants.isEmpty())
multiFilters.clear();
if (filterBoxText.contains(",") && !multiFilters.containsAll(filterList)) {
multiFilters.clear();
multiFilters.addAll(filterList);
initialYelpQuery = new RunYelpQuery(
false,
String.valueOf(searchLocationBox.getQuery()),
multiFilters.get(0).trim())
.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
/**
* Skip the first filter because we run the initial query
* with the first filter above.
* Everything after will be a background query, hence the background
* query AsyncTask being run inside the body of this for loop.
*/
for (String filter : multiFilters.subList(1, multiFilters.size())) {
backgroundYelpQuery = new RunYelpQueryBackground(0)
.executeOnExecutor(
AsyncTask.THREAD_POOL_EXECUTOR,
String.valueOf(searchLocationBox.getQuery()),
filter.trim());
}
}
else {
initialYelpQuery = new RunYelpQuery(
runBackgroundQueryAfter,
String.valueOf(searchLocationBox.getQuery()),
String.valueOf(filterBox.getText()))
.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
}
}
}
});
// Reset all cache for showcase id.
//MaterialShowcaseView.resetAll(getContext());
// A tutorial that displays only once explaining the input to the app.
MaterialShowcaseSequence sequence = new MaterialShowcaseSequence(getActivity(), BuildConfig.VERSION_NAME + "MAIN");
ShowcaseConfig config = new ShowcaseConfig();
config.setDelay(250);
sequence.setConfig(config);
sequence.addSequenceItem(buildShowcaseView(searchLocationBox, new RectangleShape(0, 0),
"Enter any zip code, city, or address here.\n\n" +
"Click the GPS icon to use your current location.\n\n" +
"Filter your results by clicking the magnifying glass if you're in the mood for something specific."
));
sequence.start();
}
@Override
public void onSaveInstanceState(Bundle outState) {
// https://code.google.com/p/gmaps-api-issues/issues/detail?id=6237#c9
final Bundle mapViewSaveState = new Bundle(outState);
mapView.onSaveInstanceState(mapViewSaveState);
outState.putBundle("mapViewSaveState", mapViewSaveState);
outState.putString("locationQuery", searchLocationBox.getQuery());
outState.putString("filterQuery", String.valueOf(filterBox.getText()));
outState.putParcelable("currentRestaurant", currentRestaurant);
outState.putParcelableArrayList("restaurants", restaurants);
super.onSaveInstanceState(outState);
}
@Override
public void onPause() {
super.onPause();
mapView.onPause();
// Try to cancel the AsyncTask.
if (initialYelpQuery != null && initialYelpQuery.getStatus() == AsyncTask.Status.RUNNING) {
initialYelpQuery.cancel(true);
enableGenerateButton();
if (mainRestaurantCardAdapter != null) {
mainRestaurantCardAdapter.remove();
mapCardContainer.setVisibility(View.GONE);
}
}
if (backgroundYelpQuery != null && backgroundYelpQuery.getStatus() == AsyncTask.Status.RUNNING)
backgroundYelpQuery.cancel(true);
}
@Override
public void onStart() {
mGoogleApiClient.connect();
super.onStart();
}
@Override
public void onStop() {
mGoogleApiClient.disconnect();
super.onStop();
}
@Override
public void onResume() {
super.onResume();
mapView.onResume();
// Refresh the RecyclerView on resume.
if (mainRestaurantCardAdapter != null)
mainRestaurantCardAdapter.notifyDataSetChanged();
}
@Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
Log.d("RRG", "Destroyed");
// Try to cancel the AsyncTask.
if (initialYelpQuery != null && initialYelpQuery.getStatus() == AsyncTask.Status.RUNNING)
initialYelpQuery.cancel(true);
if (backgroundYelpQuery != null && backgroundYelpQuery.getStatus() == AsyncTask.Status.RUNNING)
backgroundYelpQuery.cancel(true);
}
@Override
public void onDestroyView() {
super.onDestroyView();
}
// Google Maps API callback for MapFragment.
@Override
public void onMapReady(GoogleMap googleMap) {
map = googleMap;
}
// Callback for requesting permissions.
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
// Forward results to EasyPermissions
EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
}
@Override
public void onPermissionsGranted(int requestCode, List<String> perms) {
locationHelper.onPermissionsGranted(requestCode, perms);
}
@Override
public void onPermissionsDenied(int requestCode, List<String> perms) {
locationHelper.onPermissionsDenied(requestCode, perms);
}
// Callback for checking location settings.
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case LocationProviderHelper.MY_REQUEST_CHECK_SETTINGS:
switch (resultCode) {
case Activity.RESULT_OK: {
// All required changes were successfully made
Toast.makeText(getActivity(), "Location enabled by user!", Toast.LENGTH_LONG).show();
locationHelper.requestLocation();
break;
}
case Activity.RESULT_CANCELED: {
// The user was asked to change settings, but chose not to
Toast.makeText(getActivity(), "Location not enabled, user cancelled.", Toast.LENGTH_LONG).show();
locationHelper.dismissLocationUpdater();
break;
}
default: {
Toast.makeText(getActivity(), "Never ask for location. " + requestCode, Toast.LENGTH_LONG).show();
break;
}
}
break;
}
}
@Override
public void onConnected(@Nullable Bundle bundle) {
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
Toast.makeText(getContext(), "Error " + connectionResult.getErrorCode() +
": failed to connect to Google Play Services", Toast.LENGTH_LONG).show();
}
/**
* Function to hide the keyboard.
*/
private void hideSoftKeyboard() {
Activity activity = getActivity();
if (activity.getCurrentFocus() != null) {
InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
}
}
/**
* Helper function to build a custom ShowcaseView for a sequence.
*
* @param target: the target view that will be highlighted.
* @param shape: the type of shape.
* @param contentText: the text to be displayed.
*/
private MaterialShowcaseView buildShowcaseView(View target, uk.co.deanwild.materialshowcaseview.shape.Shape shape, String contentText) {
return new MaterialShowcaseView.Builder(getActivity())
.setTarget(target)
.setShape(shape)
.setMaskColour(Color.rgb(0, 166, 237))
.setContentText(contentText)
.setDismissText("GOT IT")
.build();
}
/**
* Function to disable the generate button.
*/
private void disableGenerateButton() {
// Signal the task is running
taskRunning = true;
generate.setText(R.string.string_button_text_loading);
generate.setBackgroundColor(Color.GRAY);
generate.setEnabled(false);
}
/**
* Function to enable the generate button.
*/
private void enableGenerateButton() {
// Signal the task is finished
taskRunning = false;
generate.setText(R.string.string_button_text_generate);
generate.setBackgroundColor(generateBtnColor);
generate.setEnabled(true);
progressBar.setVisibility(View.GONE);
progressBar.progressiveStop();
}
/**
* Function to display the MaterialShowcaseView for filterBox.
*/
private void displayShowcaseViewFilterBox() {
MaterialShowcaseSequence filterShowcase = new MaterialShowcaseSequence(getActivity(), BuildConfig.VERSION_NAME + "FILTER");
ShowcaseConfig config = new ShowcaseConfig();
config.setDelay(250);
filterShowcase.setConfig(config);
filterShowcase.addSequenceItem(buildShowcaseView(filterBox, new RectangleShape(0, 0),
"In the mood for multiple things? List your filters separated by a comma to combine the results!"
));
filterShowcase.start();
}
/**
* Helper function to display an AlertDialog
* @param stringToDisplay: the string to display in the alert.
* @param title: the title of the dialog.
*/
private void displayAlertDialog(int stringToDisplay, String title) {
AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
alert.setNeutralButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alert.setTitle(title);
alert.setMessage(getActivity().getString(stringToDisplay));
alert.show();
}
/**
* Function to query Yelp for restaurants. Returns an ArrayList of Restaurants.
*
* @param lat: the user's latitude, null if @param input is not empty.
* @param lon: the user's longitude, null if @param input is not empty.
* @param input the user's location string, e.g. zip, city, etc.
* @param filter the user's filterBox string, e.g. sushi, bbq, etc.
* @param offset the offset for the Yelp query.
* @param whichAsyncTask the AsyncTask to cancel if necessary.
* @return true if successful querying Yelp; false otherwise.
*/
private boolean queryYelp(String lat, String lon, String input,
String filter, int offset, int whichAsyncTask) {
try {
OAuthRequest request;
if (LocationProviderHelper.useGPS) {
request = new OAuthRequest(Verb.GET, "https://api.yelp.com/v2/search?" + filter +
"&ll=" + lat + "," + lon + "&offset=" + offset);
request.setConnectTimeout(10, TimeUnit.SECONDS);
request.setReadTimeout(10, TimeUnit.SECONDS);
Log.d("RRG", "request made: " + "https://api.yelp.com/v2/search?" + filter +
"&ll=" + lat + "," + lon + "&offset=" + offset);
} else {
request = new OAuthRequest(Verb.GET, "https://api.yelp.com/v2/search?" + filter +
"&location=" + input + "&offset=" + offset);
request.setConnectTimeout(10, TimeUnit.SECONDS);
request.setReadTimeout(10, TimeUnit.SECONDS);
Log.d("RRG", "request made: " + "https://api.yelp.com/v2/search?" + filter +
"&location=" + input + "&offset=" + offset);
}
service.signRequest(accessToken, request);
Response response = request.send();
// Get JSON array that holds the restaurants from Yelp.
JSONArray jsonBusinessesArray = new JSONObject(response.getBody())
.getJSONArray("businesses");
int length = jsonBusinessesArray.length();
// This occurs if a network communication error occurs or if no restaurants were found.
if (length <= 0) {
errorInQuery = TypeOfError.NO_RESTAURANTS;
return false;
}
for (int i = 0; i < length; i++) {
if (whichAsyncTask == 0 && initialYelpQuery.isCancelled())
break;
else if (whichAsyncTask == 1 && backgroundYelpQuery.isCancelled())
break;
Restaurant res = convertJSONToRestaurant(jsonBusinessesArray.getJSONObject(i));
if (res != null)
restaurants.add(res);
}
if (restaurants.isEmpty()) {
errorInQuery = TypeOfError.NO_RESTAURANTS;
return false;
}
} catch (OAuthConnectionException e) {
errorInQuery = TypeOfError.NETWORK_CONNECTION_ERROR;
e.printStackTrace();
return false;
} catch (JSONException e) {
if (e.getMessage().contains("No value for businesses"))
errorInQuery = TypeOfError.NO_RESTAURANTS;
else if (e.getMessage().contains("No value for"))
errorInQuery = TypeOfError.MISSING_INFO;
e.printStackTrace();
return false;
} catch (Exception e) {
if (e.getMessage().contains("timed out")) errorInQuery = TypeOfError.TIMED_OUT;
e.printStackTrace();
return false;
}
errorInQuery = TypeOfError.NO_ERROR;
return true;
}
/**
* Convert JSON to a Restaurant object that encapsulates a restaurant from Yelp.
*
* @param obj: JSONObejct that holds all restaurant info.
* @return Restaurant or null if an error occurs.
*/
private Restaurant convertJSONToRestaurant(JSONObject obj) {
try {
// Getting the JSON array of categories
JSONArray categoriesJSON = obj.getJSONArray("categories");
ArrayList<String> categories = new ArrayList<>();
for (int i = 0; i < categoriesJSON.length(); i += 2)
for (int j = 0; j < categoriesJSON.getJSONArray(i).length(); j += 2)
categories.add(categoriesJSON.getJSONArray(i).getString(j));
// Getting the restaurant's location information
JSONObject locationJSON = obj.getJSONObject("location");
double lat = locationJSON.getJSONObject("coordinate").getDouble("latitude");
double lon = locationJSON.getJSONObject("coordinate").getDouble("longitude");
float distance;
Location restaurantLoc = new Location("restaurantLoc");
restaurantLoc.setLatitude(lat);
restaurantLoc.setLongitude(lon);
if (LocationProviderHelper.useGPS) {
distance = locationHelper.getLocation().distanceTo(restaurantLoc);
} else {
Geocoder geocoder = new Geocoder(getContext());
List<Address> addressList;
try {
addressList = geocoder.getFromLocationName(searchLocationBox.getQuery(), 1);
double estimatedLat = addressList.get(0).getLatitude();
double estimatedLon = addressList.get(0).getLongitude();
Location estimatedLocation = new Location("estimatedLocation");
estimatedLocation.setLatitude(estimatedLat);
estimatedLocation.setLongitude(estimatedLon);
distance = estimatedLocation.distanceTo(restaurantLoc);
} catch (IOException io) {
/*
* If we get an IOException, that means geocoder.getFromLocationName() timed out.
* Sometimes it times out, so set distance to 0 if it does.
* See below bug report:
* https://code.google.com/p/gmaps-api-issues/issues/detail?id=9153
*/
distance = 0.0f;
}
}
distance *= 0.000621371; // Convert to miles
// Getting restaurant's address
JSONArray addressJSON = locationJSON.getJSONArray("display_address");
ArrayList<String> address = new ArrayList<>();
for (int i = 0; i < addressJSON.length(); i++)
address.add(addressJSON.getString(i));
// Get deals if JSON contains deals object.
String deals;
try {
JSONArray dealsArray = obj.getJSONArray("deals");
ArrayList<String> dealsList = new ArrayList<>();
for (int i = 0; i < dealsArray.length(); i++) {
JSONObject jsonObject = dealsArray.getJSONObject(i);
dealsList.add(jsonObject.getString("title"));
}
deals = dealsList.toString().replace("[", "").replace("]", "").trim();
} catch (Exception ignored) {
deals = "";
}
// Construct a new Restaurant object with all the info we gathered above and return it
return new Restaurant(obj.getString("name"), (float) obj.getDouble("rating"),
obj.getString("rating_img_url_large"), obj.getString("image_url"), obj.getInt("review_count"),
obj.getString("url"), categories, address, deals, distance, lat, lon);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* Update the map with a new marker based on restaurant's coordinates.
*
* @param restaurant the restaurant that will be on the map.
*/
private void updateMapWithRestaurant(Restaurant restaurant) {
// Clear all the markers on the map.
map.clear();
LatLng latLng = new LatLng(restaurant.getLat(), restaurant.getLon());
map.addMarker(new MarkerOptions().position(latLng).title(String.format("%s: %s",
restaurant.getName(), restaurant.getAddress())
.replace("[", "").replace("]", "").trim()));
map.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 14));
mapCardContainer.setVisibility(View.VISIBLE);
}
// Async task that connects to Yelp's API and queries for restaurants based on location / zip code.
public class RunYelpQuery extends AsyncTask<Void, Void, Restaurant> {
String[] params;
String userInputStr;
String userFilterStr;
boolean successfulQuery;
public RunYelpQuery(boolean runBackgroundQuery, String... params) {
runBackgroundQueryAfter = runBackgroundQuery;
this.params = params;
userInputStr = params[0];
userFilterStr = params[1];
}
@Override
protected void onPreExecute() {
super.onPreExecute();
disableGenerateButton();
if (restartQuery) {
((CircularProgressDrawable) progressBar.getIndeterminateDrawable()).start();
progressBar.setVisibility(View.VISIBLE);
}
}
@Override
protected void onCancelled() {
super.onCancelled();
Log.d("RRG", "Cancelled Yelp AsyncTask");
restartQuery = true;
enableGenerateButton();
}
@Override
protected Restaurant doInBackground(Void... aVoid) {
if (isCancelled()) return null;
// Check for parameters so we can send the appropriate request based on user input.
String lat = "";
String lon = "";
try {
// If the user entered some input, make sure to encode all spaces and "+" for URL query.
if (userInputStr.length() != 0) {
userInputStr = userInputStr.replaceAll(" ", "+");
}
// If the user entered a filterBox, make sure to encode all spaces and "+" for URL query.
if (userFilterStr.length() != 0) {
userFilterStr = userFilterStr.replaceAll(" ", "+");
// Add Yelp API query verb.
userFilterStr = String.format("term=%s", userFilterStr);
} else {
// Default search term.
userFilterStr = "term=food";
}
// If we have 4 parameters, then the user selected location and we must grab the lat / long.
if (params.length == 4) {
lat = params[2];
lon = params[3];
}
} catch (Exception e) {
e.printStackTrace();
}
if (restartQuery) {
restaurants.clear();
restartQuery = false;
}
// Get restaurants only when the restaurants list is empty.
Restaurant chosenRestaurant = null;
if (restaurants == null || restaurants.isEmpty()) {
successfulQuery = queryYelp(lat, lon, userInputStr, userFilterStr, 0, 0);
if (successfulQuery && !restaurants.isEmpty()) {
// Make sure the restaurants list is not empty before accessing it.
chosenRestaurant = restaurants.get(new Random().nextInt(restaurants.size()));
restaurants.remove(chosenRestaurant);
/**
* Run background query only if the following BOTH hold:
* 1) initially set to true from constructor
* 2) and successfulQuery is true
*/
if (runBackgroundQueryAfter)
runBackgroundQueryAfter = true;
}
} else if (restaurants != null && !restaurants.isEmpty()) {
chosenRestaurant = restaurants.get(new Random().nextInt(restaurants.size()));
restaurants.remove(chosenRestaurant);
}
// Return randomly chosen restaurant.
return chosenRestaurant;
}
// Set UI appropriate UI elements to display mRestaurant info.
@Override
protected void onPostExecute(Restaurant restaurant) {
if (restaurant == null) {
if (errorInQuery == TypeOfError.NO_RESTAURANTS) {
Toast.makeText(getContext(),
R.string.string_no_restaurants_found,
Toast.LENGTH_LONG).show();
restaurants.clear();
} else if (errorInQuery == TypeOfError.MISSING_INFO) {
// Try again if the current restaurant has missing info.
generate.performClick();
return;
}
else if (errorInQuery == TypeOfError.NETWORK_CONNECTION_ERROR) {
Toast.makeText(getContext(),
R.string.string_no_network,
Toast.LENGTH_LONG).show();
}
else if (errorInQuery == TypeOfError.TIMED_OUT) {
Toast.makeText(getContext(),
R.string.string_timed_out_msg,
Toast.LENGTH_LONG).show();
}
if (initialYelpQuery!= null) initialYelpQuery.cancel(true);
if (backgroundYelpQuery!= null) backgroundYelpQuery.cancel(true);
enableGenerateButton();
return;
}
currentRestaurant = restaurant;
// If the RecyclerView has not been set yet, set it with the currentRestaurant.
if (mainRestaurantCardAdapter == null) {
mainRestaurantCardAdapter = new MainRestaurantCardAdapter(getContext(), currentRestaurant);
restaurantView.setAdapter(mainRestaurantCardAdapter);
}
// These calls notify the RecyclerView that the data set has changed and we need to refresh.
mainRestaurantCardAdapter.remove();
mainRestaurantCardAdapter.add(currentRestaurant);
updateMapWithRestaurant(currentRestaurant);
enableGenerateButton();
if (runBackgroundQueryAfter) {
backgroundYelpQuery = new RunYelpQueryBackground(20).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, this.params);
runBackgroundQueryAfter = false;
}
// A tutorial that displays only once explaining the action that can be done on the restaurant card.
MaterialShowcaseSequence sequence = new MaterialShowcaseSequence(getActivity(), BuildConfig.VERSION_NAME + "CARD");
ShowcaseConfig config = new ShowcaseConfig();
config.setDelay(100);
sequence.setConfig(config);
sequence.addSequenceItem(buildShowcaseView(restaurantView, new RectangleShape(0, 0),
"Swipe left to dismiss. Swipe right to open in Yelp. Tap bookmark button to save it for later."));
sequence.addSequenceItem(buildShowcaseView(((MainActivity) getActivity()).getMenuItemView(R.id.action_saved_list),
new CircleShape(), "Tap here to view your saved list."));
sequence.start();
}
}
// Async task that runs in the background to query more restaurants from Yelp while the user
// goes through the initial list of restaurants.
public class RunYelpQueryBackground extends AsyncTask<String, Void, Void> {
int offset;
public RunYelpQueryBackground(int offset) {
this.offset = offset;
}
@Override
protected void onCancelled() {
super.onCancelled();
Log.d("RRG", "Cancelled background Yelp AsyncTask");
}
@Override
protected Void doInBackground(String... params) {
if (isCancelled()) return null;
// Check for parameters so we can send the appropriate request based on user input.
String lat = "";
String lon = "";
String userInputStr = params[0];
String userFilterStr = params[1];
try {
// If the user entered some input, make sure to encode all spaces and "+" for URL query.
if (userInputStr.length() != 0) {
userInputStr = userInputStr.replaceAll(" ", "+");
}
// If the user entered a filterBox, make sure to encode all spaces and "+" for URL query.
if (userFilterStr.length() != 0) {
userFilterStr = userFilterStr.replaceAll(" ", "+");
// Add Yelp API query verb.
userFilterStr = String.format("term=%s", userFilterStr);
} else {
// Default search term.
userFilterStr = "term=food";
}
// If we have 4 parameters, then the user selected location and we must grab the lat / long.
if (params.length == 4) {
lat = params[2];
lon = params[3];
}
} catch (Exception e) {
e.printStackTrace();
}
queryYelp(lat, lon, userInputStr, userFilterStr, offset, 1);
return null;
}
}
} | Update app to version 1.2
- Add logic to restore instance state
- Make GoogleApiClient manage its lifecycle automatically
- Remove unnecessary lifecycle methods
- Convert Toasts to logs
| app/src/main/java/com/chris/randomrestaurantgenerator/fragments/MainActivityFragment.java | Update app to version 1.2 - Add logic to restore instance state - Make GoogleApiClient manage its lifecycle automatically - Remove unnecessary lifecycle methods - Convert Toasts to logs | <ide><path>pp/src/main/java/com/chris/randomrestaurantgenerator/fragments/MainActivityFragment.java
<ide> searchLocationBox.setSearchText(savedInstanceState.getString("locationQuery"));
<ide> filterBox.setText(savedInstanceState.getString("filterQuery"));
<ide> restaurants = savedInstanceState.getParcelableArrayList("restaurants");
<add> Log.d("RRG", "restored saved instance state");
<ide> }
<ide>
<ide> // Define actions on menu button clicks inside searchLocationBox.
<ide> }
<ide> });
<ide>
<add> if (savedInstanceState != null) {
<add> searchLocationBox.setSearchText(savedInstanceState.getString("locationQuery"));
<add> filterBox.setText(savedInstanceState.getString("filterQuery"));
<add> currentRestaurant = savedInstanceState.getParcelable("currentRestaurant");
<add> restaurants = savedInstanceState.getParcelableArrayList("restaurants");
<add> }
<add>
<ide> // Reset all cache for showcase id.
<ide> //MaterialShowcaseView.resetAll(getContext());
<ide>
<ide> }
<ide>
<ide> @Override
<del> public void onStart() {
<del> mGoogleApiClient.connect();
<del> super.onStart();
<del> }
<del>
<del> @Override
<del> public void onStop() {
<del> mGoogleApiClient.disconnect();
<del> super.onStop();
<del> }
<del>
<del> @Override
<ide> public void onResume() {
<ide> super.onResume();
<ide> mapView.onResume();
<ide>
<ide> if (backgroundYelpQuery != null && backgroundYelpQuery.getStatus() == AsyncTask.Status.RUNNING)
<ide> backgroundYelpQuery.cancel(true);
<del> }
<del>
<del> @Override
<del> public void onDestroyView() {
<del> super.onDestroyView();
<ide> }
<ide>
<ide> // Google Maps API callback for MapFragment.
<ide> switch (resultCode) {
<ide> case Activity.RESULT_OK: {
<ide> // All required changes were successfully made
<del> Toast.makeText(getActivity(), "Location enabled by user!", Toast.LENGTH_LONG).show();
<add> Log.d("RRG", "Location enabled by user!");
<ide> locationHelper.requestLocation();
<ide> break;
<ide> }
<ide> case Activity.RESULT_CANCELED: {
<ide> // The user was asked to change settings, but chose not to
<del> Toast.makeText(getActivity(), "Location not enabled, user cancelled.", Toast.LENGTH_LONG).show();
<add> Log.d("RRG", "Location not enabled, user cancelled.");
<ide> locationHelper.dismissLocationUpdater();
<ide> break;
<ide> }
<ide> default: {
<del> Toast.makeText(getActivity(), "Never ask for location. " + requestCode, Toast.LENGTH_LONG).show();
<add> Log.d("RRG", "User opted to never ask for location. ");
<ide> break;
<ide> }
<ide> }
<ide>
<ide> @Override
<ide> public void onConnected(@Nullable Bundle bundle) {
<del>
<add> Log.d("RRG", "Connected to Google Play Services.");
<ide> }
<ide>
<ide> @Override
<ide> public void onConnectionSuspended(int i) {
<del>
<add> Log.d("RRG", "onConnectionSuspended: " + i);
<ide> }
<ide>
<ide> @Override
<ide> public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
<ide> Toast.makeText(getContext(), "Error " + connectionResult.getErrorCode() +
<del> ": failed to connect to Google Play Services", Toast.LENGTH_LONG).show();
<add> ": failed to connect to Google Play Services. This may affect acquiring your location.",
<add> Toast.LENGTH_LONG).show();
<ide> }
<ide>
<ide> /** |
|
Java | apache-2.0 | cd80b7161130185229327e957a557bf2ec9b2a65 | 0 | atomashpolskiy/bt,atomashpolskiy/bt | /*
* Copyright (c) 2016—2017 Andrei Tomashpolskiy and individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package bt.torrent.selector;
import bt.torrent.PieceStatistics;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.PrimitiveIterator;
import java.util.PriorityQueue;
import java.util.Random;
/**
* Implements the "rarest-first" piece selection algorithm.
* As the name implies, pieces that appear less frequently
* and are generally less available are selected in the first place.
*
* There are two "flavours" of the "rarest-first" strategy: regular and randomized.
* Regular rarest-first selects whichever pieces that are the least available
* (strictly following the order of increasing availability).
*
* Randomized rarest-first selects one of the least available pieces randomly
* (which means that it does not always select THE least available piece, but rather looks at
* some number N of the least available pieces and then randomly picks one of them).
*
* @since 1.1
**/
public class RarestFirstSelector extends BaseStreamSelector {
private static final Comparator<Long> comparator = new PackedIntComparator();
/**
* Regular rarest-first selector.
* Selects whichever pieces that are the least available
* (strictly following the order of increasing availability).
*
* @since 1.1
*/
public static RarestFirstSelector rarest() {
return new RarestFirstSelector(false);
}
/**
* Randomized rarest-first selector.
* Selects one of the least available pieces randomly
* (which means that it does not always select THE least available piece, but rather looks at
* some number N of the least available pieces and then randomly picks one of them).
*
* @since 1.1
*/
public static RarestFirstSelector randomizedRarest() {
return new RarestFirstSelector(true);
}
private Optional<Random> random;
private RarestFirstSelector(boolean randomized) {
this.random = randomized ? Optional.of(new Random(System.currentTimeMillis())) : Optional.empty();
}
@Override
protected PrimitiveIterator.OfInt createIterator(PieceStatistics pieceStatistics) {
List<Long> queue = orderedQueue(pieceStatistics);
return random.isPresent() ?
new RandomizedIteratorOfInt(queue, random.get()) : new SequentialIteratorOfInt(queue);
}
// TODO: this is very inefficient when only a few pieces are needed,
// and this for sure can be moved to PieceStatistics (that will be responsible for maintaining an up-to-date list)
// UPDATE: giving this another thought, amortized costs of maintaining an up-to-date list (from the '# of operations' POV)
// are in fact likely to far exceed the costs of periodically rebuilding the statistics from scratch,
// esp. when there are many connects and disconnects, and statistics are slightly adjusted for each added or removed bitfield.
private List<Long> orderedQueue(PieceStatistics pieceStatistics) {
PriorityQueue<Long> rarestFirst = new PriorityQueue<>(comparator);
int piecesTotal = pieceStatistics.getPiecesTotal();
for (int pieceIndex = 0; pieceIndex < piecesTotal; pieceIndex++) {
int count = pieceStatistics.getCount(pieceIndex);
if (count > 0) {
long zipped = zip(pieceIndex, count);
rarestFirst.add(zipped);
}
}
List<Long> result = new ArrayList<>(rarestFirst.size());
Long l;
while ((l = rarestFirst.poll()) != null) {
result.add(l);
}
return result;
}
private static long zip(int pieceIndex, int count) {
return (((long)pieceIndex) << 32) + count;
}
private static int getPieceIndex(long zipped) {
return (int)(zipped >> 32);
}
private static int getCount(long zipped) {
return (int) zipped;
}
private static class SequentialIteratorOfInt implements PrimitiveIterator.OfInt {
private final List<Long> list;
private int position;
SequentialIteratorOfInt(List<Long> list) {
this.list = list;
}
@Override
public int nextInt() {
return getPieceIndex(list.get(position++));
}
@Override
public boolean hasNext() {
return position < list.size();
}
}
private static class RandomizedIteratorOfInt implements PrimitiveIterator.OfInt {
private static final int SELECTION_MIN_SIZE = 10;
private final List<Long> list;
private final Random random;
private int position;
private int limit;
RandomizedIteratorOfInt(List<Long> list, Random random) {
this.list = list;
this.random = random;
this.limit = calculateLimitAndShuffle(list, 0);
}
/**
* Starting with a given position, iterates over elements of the list,
* while one of the following holds true:
* - each subsequent element's "count" is equal to the initial element's "count",
* - less than {@link #SELECTION_MIN_SIZE} elements were seen
*
* Shuffles the subrange of the list, starting with the initial element at {@code position},
* where all elements have the same "count"
*
* @return index of the first element in the list with "count" different from the initial element's "count"
* or index of the element that is {@link #SELECTION_MIN_SIZE} positions ahead in the list
* than the initial element, whichever is greater
* @see #getCount(long)
*/
private int calculateLimitAndShuffle(List<Long> list, int position) {
if (position >= list.size()) {
return position;
}
int limit = position + 1;
int count = getCount(list.get(position));
int nextCount;
int i = 0;
while (limit < list.size() && (nextCount = getCount(list.get(limit++))) == count) {
count = nextCount;
}
// shuffle elements with the same "count" only,
// because otherwise less available pieces may end up
// being swapped with more available pieces
// (i.e. pushed to the bottom of the queue)
shuffle(list, position, limit);
// do not stop until a certain number of elements were seen
while (++i < SELECTION_MIN_SIZE && ++limit < list.size())
;
return limit;
}
/**
* Shuffle a subrange of the given list, between 'begin' and 'end' (exclusively)
*
* @param begin index of the first element of the subrange
* @param end index of the first element after the last element of the subrange
*/
private void shuffle(List<Long> list, int begin, int end) {
int length = end - begin;
if (length < 2) {
// subrange has no elements or a single element
return;
}
do {
swap(list, begin, begin + random.nextInt(length));
length--;
} while (++begin < end);
}
private void swap(List<Long> list, int i, int j) {
if (i != j) {
Long temp = list.get(i);
list.set(i, list.get(j));
list.set(j, temp);
}
}
@Override
public int nextInt() {
int result = getPieceIndex(list.get(position++));
if (position == limit && position < list.size()) {
limit = calculateLimitAndShuffle(list, position);
}
return result;
}
@Override
public boolean hasNext() {
return position < list.size();
}
}
}
| bt-core/src/main/java/bt/torrent/selector/RarestFirstSelector.java | /*
* Copyright (c) 2016—2017 Andrei Tomashpolskiy and individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package bt.torrent.selector;
import bt.torrent.PieceStatistics;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.PrimitiveIterator;
import java.util.PriorityQueue;
import java.util.Random;
/**
* Implements the "rarest-first" piece selection algorithm.
* As the name implies, pieces that appear less frequently
* and are generally less available are selected in the first place.
*
* There are two "flavours" of the "rarest-first" strategy: regular and randomized.
* Regular rarest-first selects whichever pieces that are the least available
* (strictly following the order of increasing availability).
*
* Randomized rarest-first selects one of the least available pieces randomly
* (which means that it does not always select THE least available piece, but rather looks at
* some number N of the least available pieces and then randomly picks one of them).
*
* @since 1.1
**/
public class RarestFirstSelector extends BaseStreamSelector {
private static final Comparator<Long> comparator = new PackedIntComparator();
/**
* Regular rarest-first selector.
* Selects whichever pieces that are the least available
* (strictly following the order of increasing availability).
*
* @since 1.1
*/
public static RarestFirstSelector rarest() {
return new RarestFirstSelector(false);
}
/**
* Randomized rarest-first selector.
* Selects one of the least available pieces randomly
* (which means that it does not always select THE least available piece, but rather looks at
* some number N of the least available pieces and then randomly picks one of them).
*
* @since 1.1
*/
public static RarestFirstSelector randomizedRarest() {
return new RarestFirstSelector(true);
}
private Optional<Random> random;
private RarestFirstSelector(boolean randomized) {
this.random = randomized ? Optional.of(new Random(System.currentTimeMillis())) : Optional.empty();
}
@Override
protected PrimitiveIterator.OfInt createIterator(PieceStatistics pieceStatistics) {
List<Long> queue = orderedQueue(pieceStatistics);
return random.isPresent() ?
new RandomizedIteratorOfInt(queue, random.get()) : new SequentialIteratorOfInt(queue);
}
// TODO: this is very inefficient when only a few pieces are needed,
// and this for sure can be moved to PieceStatistics (that will be responsible for maintaining an up-to-date list)
// UPDATE: giving this another thought, amortized costs of maintaining an up-to-date list (from the '# of operations' POV)
// are in fact likely to far exceed the costs of periodically rebuilding the statistics from scratch,
// esp. when there are many connects and disconnects, and statistics are slightly adjusted for each added or removed bitfield.
private List<Long> orderedQueue(PieceStatistics pieceStatistics) {
PriorityQueue<Long> rarestFirst = new PriorityQueue<>(comparator);
int piecesTotal = pieceStatistics.getPiecesTotal();
for (int pieceIndex = 0; pieceIndex < piecesTotal; pieceIndex++) {
int count = pieceStatistics.getCount(pieceIndex);
if (count > 0) {
long zipped = zip(pieceIndex, count);
rarestFirst.add(zipped);
}
}
return new ArrayList<>(Arrays.asList(rarestFirst.toArray(new Long[rarestFirst.size()])));
}
private static long zip(int pieceIndex, int count) {
return (((long)pieceIndex) << 32) + count;
}
private static int getPieceIndex(long zipped) {
return (int)(zipped >> 32);
}
private static int getCount(long zipped) {
return (int) zipped;
}
private static class SequentialIteratorOfInt implements PrimitiveIterator.OfInt {
private final List<Long> list;
private int position;
SequentialIteratorOfInt(List<Long> list) {
this.list = list;
}
@Override
public int nextInt() {
return getPieceIndex(list.get(position++));
}
@Override
public boolean hasNext() {
return position < list.size();
}
}
private static class RandomizedIteratorOfInt implements PrimitiveIterator.OfInt {
private static final int SELECTION_MIN_SIZE = 10;
private final List<Long> list;
private final Random random;
private int position;
private int limit;
RandomizedIteratorOfInt(List<Long> list, Random random) {
this.list = list;
this.random = random;
this.limit = calculateLimit(list, 0);
shuffle(list, 0, limit);
}
/**
* Starting with a given position, iterates over elements of the list,
* while one of the following holds true:
* - each subsequent element's "count" is equal to the initial element's "count",
* - less than {@link #SELECTION_MIN_SIZE} elements were seen
*
* @return index of the first element in the list with "count" different from the initial element's "count"
* @see #getCount(long)
*/
private int calculateLimit(List<Long> list, int position) {
if (position >= list.size()) {
return position;
}
int limit = position + 1;
int count = getCount(list.get(position));
int nextCount;
int i = 0;
while (limit < list.size()) {
nextCount = getCount(list.get(limit));
// do not stop until a certain number of elements were seen
if (i >= SELECTION_MIN_SIZE && nextCount != count) {
break;
}
count = nextCount;
limit++;
}
return limit;
}
/**
* Shuffle a subrange of the given list, between 'begin' and 'end' (exclusively)
*
* @param begin index of the first element of the subrange
* @param end index of the first element after the last element of the subrange
*/
private void shuffle(List<Long> list, int begin, int end) {
int length = end - begin;
if (length < 2) {
// subrange has no elements or a single element
return;
}
do {
swap(list, begin, begin + random.nextInt(length));
length--;
} while (++begin < end);
}
private void swap(List<Long> list, int i, int j) {
if (i != j) {
Long temp = list.get(i);
list.set(i, list.get(j));
list.set(j, temp);
}
}
@Override
public int nextInt() {
int result = getPieceIndex(list.get(position++));
if (position == limit && position < list.size()) {
limit = calculateLimit(list, position);
shuffle(list, position, limit);
}
return result;
}
@Override
public boolean hasNext() {
return position < list.size();
}
}
}
| Randomized rarest-first selector behaves like a sequential selector when peers are seeds #53
| bt-core/src/main/java/bt/torrent/selector/RarestFirstSelector.java | Randomized rarest-first selector behaves like a sequential selector when peers are seeds #53 | <ide><path>t-core/src/main/java/bt/torrent/selector/RarestFirstSelector.java
<ide> import bt.torrent.PieceStatistics;
<ide>
<ide> import java.util.ArrayList;
<del>import java.util.Arrays;
<ide> import java.util.Comparator;
<ide> import java.util.List;
<ide> import java.util.Optional;
<ide> }
<ide> }
<ide>
<del> return new ArrayList<>(Arrays.asList(rarestFirst.toArray(new Long[rarestFirst.size()])));
<add> List<Long> result = new ArrayList<>(rarestFirst.size());
<add> Long l;
<add> while ((l = rarestFirst.poll()) != null) {
<add> result.add(l);
<add> }
<add> return result;
<ide> }
<ide>
<ide> private static long zip(int pieceIndex, int count) {
<ide> RandomizedIteratorOfInt(List<Long> list, Random random) {
<ide> this.list = list;
<ide> this.random = random;
<del> this.limit = calculateLimit(list, 0);
<del> shuffle(list, 0, limit);
<add> this.limit = calculateLimitAndShuffle(list, 0);
<ide> }
<ide>
<ide> /**
<ide> * - each subsequent element's "count" is equal to the initial element's "count",
<ide> * - less than {@link #SELECTION_MIN_SIZE} elements were seen
<ide> *
<add> * Shuffles the subrange of the list, starting with the initial element at {@code position},
<add> * where all elements have the same "count"
<add> *
<ide> * @return index of the first element in the list with "count" different from the initial element's "count"
<add> * or index of the element that is {@link #SELECTION_MIN_SIZE} positions ahead in the list
<add> * than the initial element, whichever is greater
<ide> * @see #getCount(long)
<ide> */
<del> private int calculateLimit(List<Long> list, int position) {
<add> private int calculateLimitAndShuffle(List<Long> list, int position) {
<ide> if (position >= list.size()) {
<ide> return position;
<ide> }
<ide> int nextCount;
<ide>
<ide> int i = 0;
<del> while (limit < list.size()) {
<del> nextCount = getCount(list.get(limit));
<del> // do not stop until a certain number of elements were seen
<del> if (i >= SELECTION_MIN_SIZE && nextCount != count) {
<del> break;
<del> }
<add> while (limit < list.size() && (nextCount = getCount(list.get(limit++))) == count) {
<ide> count = nextCount;
<del> limit++;
<del> }
<add> }
<add> // shuffle elements with the same "count" only,
<add> // because otherwise less available pieces may end up
<add> // being swapped with more available pieces
<add> // (i.e. pushed to the bottom of the queue)
<add> shuffle(list, position, limit);
<add>
<add> // do not stop until a certain number of elements were seen
<add> while (++i < SELECTION_MIN_SIZE && ++limit < list.size())
<add> ;
<add>
<ide> return limit;
<ide> }
<ide>
<ide> public int nextInt() {
<ide> int result = getPieceIndex(list.get(position++));
<ide> if (position == limit && position < list.size()) {
<del> limit = calculateLimit(list, position);
<del> shuffle(list, position, limit);
<add> limit = calculateLimitAndShuffle(list, position);
<ide> }
<ide> return result;
<ide> } |
|
JavaScript | mit | d99ba70c492d3cd15ef6aded3f8712976d251f88 | 0 | facebook/react-native,pandiaraj44/react-native,exponent/react-native,arthuralee/react-native,exponentjs/react-native,myntra/react-native,hoangpham95/react-native,myntra/react-native,hammerandchisel/react-native,facebook/react-native,hoastoolshop/react-native,hammerandchisel/react-native,exponent/react-native,hammerandchisel/react-native,javache/react-native,pandiaraj44/react-native,pandiaraj44/react-native,janicduplessis/react-native,facebook/react-native,myntra/react-native,javache/react-native,arthuralee/react-native,exponentjs/react-native,facebook/react-native,exponentjs/react-native,hammerandchisel/react-native,facebook/react-native,pandiaraj44/react-native,hoastoolshop/react-native,hoastoolshop/react-native,pandiaraj44/react-native,arthuralee/react-native,hoangpham95/react-native,pandiaraj44/react-native,javache/react-native,facebook/react-native,hoangpham95/react-native,myntra/react-native,facebook/react-native,hoangpham95/react-native,hoangpham95/react-native,exponent/react-native,javache/react-native,exponentjs/react-native,javache/react-native,exponent/react-native,javache/react-native,hoastoolshop/react-native,janicduplessis/react-native,hoastoolshop/react-native,hammerandchisel/react-native,javache/react-native,myntra/react-native,exponentjs/react-native,exponent/react-native,exponentjs/react-native,janicduplessis/react-native,janicduplessis/react-native,exponentjs/react-native,hoangpham95/react-native,hoangpham95/react-native,janicduplessis/react-native,hammerandchisel/react-native,pandiaraj44/react-native,pandiaraj44/react-native,facebook/react-native,javache/react-native,myntra/react-native,janicduplessis/react-native,arthuralee/react-native,myntra/react-native,exponent/react-native,hammerandchisel/react-native,janicduplessis/react-native,myntra/react-native,hoastoolshop/react-native,janicduplessis/react-native,exponent/react-native,javache/react-native,hammerandchisel/react-native,hoangpham95/react-native,hoastoolshop/react-native,myntra/react-native,exponentjs/react-native,hoastoolshop/react-native,arthuralee/react-native,facebook/react-native,exponent/react-native | /**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule nativeImageSource
* @flow
* @format
*/
'use strict';
const Platform = require('Platform');
// TODO: Change `nativeImageSource` to return this type.
export type NativeImageSource = {|
+deprecated: true,
+height: number,
+uri: string,
+width: number,
|};
type NativeImageSourceSpec = {|
+android?: string,
+ios?: string,
// For more details on width and height, see
// http://facebook.github.io/react-native/docs/images.html#why-not-automatically-size-everything
+height: number,
+width: number,
|};
/**
* In hybrid apps, use `nativeImageSource` to access images that are already
* available on the native side, for example in Xcode Asset Catalogs or
* Android's drawable folder.
*
* However, keep in mind that React Native Packager does not guarantee that the
* image exists. If the image is missing you'll get an empty box. When adding
* new images your app needs to be recompiled.
*
* Prefer Static Image Resources system which provides more guarantees,
* automates measurements and allows adding new images without rebuilding the
* native app. For more details visit:
*
* http://facebook.github.io/react-native/docs/images.html
*
*/
function nativeImageSource(spec: NativeImageSourceSpec): Object {
let uri = Platform.select(spec);
if (uri == null) {
console.warn(
'nativeImageSource(...): No image name supplied for `%s`:\n%s',
Platform.OS,
JSON.stringify(spec, null, 2),
);
uri = '';
}
return {
deprecated: true,
height: spec.height,
uri,
width: spec.width,
};
}
module.exports = nativeImageSource;
| Libraries/Image/nativeImageSource.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule nativeImageSource
* @flow
* @format
*/
'use strict';
const Platform = require('Platform');
type SourceSpec = {
ios?: string,
android?: string,
// For more details on width and height, see
// http://facebook.github.io/react-native/docs/images.html#why-not-automatically-size-everything
width: number,
height: number,
};
/**
* In hybrid apps, use `nativeImageSource` to access images that are already available
* on the native side, for example in Xcode Asset Catalogs or Android's drawable folder.
*
* However, keep in mind that React Native Packager does not guarantee that the image exists. If
* the image is missing you'll get an empty box. When adding new images your app needs to be
* recompiled.
*
* Prefer Static Image Resources system which provides more guarantees, automates measurements and
* allows adding new images without rebuilding the native app. For more details visit:
*
* http://facebook.github.io/react-native/docs/images.html
*
*/
function nativeImageSource(spec: SourceSpec): Object {
const uri = Platform.select(spec);
if (!uri) {
console.warn(
`No image name given for ${Platform.OS}: ${JSON.stringify(spec)}`,
);
}
return {
uri,
width: spec.width,
height: spec.height,
deprecated: true,
};
}
module.exports = nativeImageSource;
| RN: Add NativeImageSource Flow Type
Reviewed By: TheSavior
Differential Revision: D6869985
fbshipit-source-id: 836134ae0919d49b161d1a75d5743e977e6eb3f4
| Libraries/Image/nativeImageSource.js | RN: Add NativeImageSource Flow Type | <ide><path>ibraries/Image/nativeImageSource.js
<ide> * @flow
<ide> * @format
<ide> */
<add>
<ide> 'use strict';
<ide>
<ide> const Platform = require('Platform');
<ide>
<del>type SourceSpec = {
<del> ios?: string,
<del> android?: string,
<add>// TODO: Change `nativeImageSource` to return this type.
<add>export type NativeImageSource = {|
<add> +deprecated: true,
<add> +height: number,
<add> +uri: string,
<add> +width: number,
<add>|};
<add>
<add>type NativeImageSourceSpec = {|
<add> +android?: string,
<add> +ios?: string,
<ide>
<ide> // For more details on width and height, see
<ide> // http://facebook.github.io/react-native/docs/images.html#why-not-automatically-size-everything
<del> width: number,
<del> height: number,
<del>};
<add> +height: number,
<add> +width: number,
<add>|};
<ide>
<ide> /**
<del> * In hybrid apps, use `nativeImageSource` to access images that are already available
<del> * on the native side, for example in Xcode Asset Catalogs or Android's drawable folder.
<add> * In hybrid apps, use `nativeImageSource` to access images that are already
<add> * available on the native side, for example in Xcode Asset Catalogs or
<add> * Android's drawable folder.
<ide> *
<del> * However, keep in mind that React Native Packager does not guarantee that the image exists. If
<del> * the image is missing you'll get an empty box. When adding new images your app needs to be
<del> * recompiled.
<add> * However, keep in mind that React Native Packager does not guarantee that the
<add> * image exists. If the image is missing you'll get an empty box. When adding
<add> * new images your app needs to be recompiled.
<ide> *
<del> * Prefer Static Image Resources system which provides more guarantees, automates measurements and
<del> * allows adding new images without rebuilding the native app. For more details visit:
<add> * Prefer Static Image Resources system which provides more guarantees,
<add> * automates measurements and allows adding new images without rebuilding the
<add> * native app. For more details visit:
<ide> *
<ide> * http://facebook.github.io/react-native/docs/images.html
<ide> *
<ide> */
<del>function nativeImageSource(spec: SourceSpec): Object {
<del> const uri = Platform.select(spec);
<del> if (!uri) {
<add>function nativeImageSource(spec: NativeImageSourceSpec): Object {
<add> let uri = Platform.select(spec);
<add> if (uri == null) {
<ide> console.warn(
<del> `No image name given for ${Platform.OS}: ${JSON.stringify(spec)}`,
<add> 'nativeImageSource(...): No image name supplied for `%s`:\n%s',
<add> Platform.OS,
<add> JSON.stringify(spec, null, 2),
<ide> );
<add> uri = '';
<ide> }
<del>
<ide> return {
<add> deprecated: true,
<add> height: spec.height,
<ide> uri,
<ide> width: spec.width,
<del> height: spec.height,
<del> deprecated: true,
<ide> };
<ide> }
<ide> |
|
Java | mit | 51459bcd48186dccfc2a5721fb218d409d8e7ae5 | 0 | za419/Android-calculator | package com.Ryan.Calculator;
import android.annotation.TargetApi;
import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import java.math.BigInteger;
public class MainActivity extends Activity
{
public Complex currentValue=Complex.ZERO;
/** Called when the activity is first created. */
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB)
{
getActionBar().hide();
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.ICE_CREAM_SANDWICH)
findViewById(R.id.mainLayout).setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE);
}
setZero();
}
public Complex parseComplex(String num)
{
if (num==null || num.indexOf("Error", 0)==0 || num.indexOf("ERROR", 0)==0)
return Complex.ZERO;
if ("Not prime".equals(num) || "Not prime or composite".equals(num) || "Not Gaussian prime".equals(num))
return Complex.ZERO;
if ("Prime".equals(num) || "Gaussian prime".equals(num))
return Complex.ONE;
if (num.charAt(num.length()-1)=='\u03C0')
{
if (num.length()==1)
return Complex.PI;
else if (num.length()==2 && num.charAt(0)=='-') // If the string is two long and the first character is a negation
return Complex.negate(Complex.PI); // Return negative pi
return Complex.multiply(parseComplex(num.substring(0, num.length()-1)), Complex.PI);
}
if (num.charAt(num.length()-1)=='e')
{
if (num.length()==1)
return Complex.E;
else if (num.length()==2 && num.charAt(0)=='-') // If the string is two long and the first character is a negation
return Complex.negate(Complex.E); // Return negative e
return Complex.multiply(parseComplex(num.substring(0, num.length()-1)), Complex.E);
}
try {
return Complex.parseString(num);
}
catch (NumberFormatException e) {
setText("ERROR: Invalid number");
View v=findViewById(R.id.mainCalculateButton);
v.setOnClickListener(null); // Cancel existing computation
v.setVisibility(View.GONE); // Remove the button
return Complex.ERROR;
}
}
public String inIntTermsOfPi(double num)
{
if (num==0)
return "0";
double tmp=num/Math.PI;
int n=(int)tmp;
if (n==tmp)
{
if (n==-1) // If it is a negative, but otherwise 1
return "-\u03C0"; // Return negative pi
return (n==1 ? "" : Integer.toString(n))+"\u03C0";
}
else
return Double.toString(num);
}
public String inIntTermsOfPi(Complex num)
{
if (num.equals(Complex.ZERO)) // Special case: Prevents "0+0i"
return "0";
if (num.isReal())
return inIntTermsOfPi(num.real);
if (num.isImaginary()) {
if (num.imaginary==1)
return "i";
else if (num.imaginary==-1)
return "-i";
return inIntTermsOfPi(num.imaginary) + 'i';
}
String out=inIntTermsOfPi(num.real);
if (num.imaginary>0)
out+="+";
out+=inIntTermsOfPi(num.imaginary)+'i';
return out;
}
public String inIntTermsOfE(double num)
{
if (num==0)
return "0";
double tmp=num/Math.E;
int n=(int)tmp;
if (n==tmp)
{
if (n==-1) // If it is a negative, but otherwise 1
return "-e"; // Return negative e
return (n==1 ? "" : Integer.toString((int)tmp))+"e";
}
else
return Double.toString(num);
}
public String inIntTermsOfE(Complex num)
{
if (num.equals(Complex.ZERO)) // Special case: Prevents "0+0i"
return "0";
if (num.isReal())
return inIntTermsOfE(num.real);
if (num.isImaginary()) {
if (num.imaginary==1)
return "i";
else if (num.imaginary==-1)
return "-i";
return inIntTermsOfE(num.imaginary) + 'i';
}
String out=inIntTermsOfE(num.real);
if (num.imaginary>0)
out+="+";
out+=inIntTermsOfE(num.imaginary)+'i';
return out;
}
public String inIntTermsOfAny(double num)
{
if (Double.isNaN(num)) // "Last-resort" check
return "ERROR: Nonreal or non-numeric result."; // Trap NaN and return a generic error for it.
// Because of that check, we can guarantee that NaN's will not be floating around for more than one expression.
String out=inIntTermsOfPi(num);
if (!out.equals(Double.toString(num)))
return out;
else
return inIntTermsOfE(num);
}
public String inIntTermsOfAny(Complex num)
{
if (num.equals(Complex.ZERO)) // Special case: Prevents "0+0i"
return "0";
if (num.isReal())
return inIntTermsOfAny(num.real);
if (num.isImaginary()) {
if (num.imaginary==1)
return "i";
else if (num.imaginary==-1)
return "-i";
return inIntTermsOfAny(num.imaginary) + 'i';
}
String out=inIntTermsOfAny(num.real);
if (num.imaginary>0)
out+="+";
out+=inIntTermsOfAny(num.imaginary)+'i';
return out;
}
public void zero(View v)
{
setZero();
}
public void setZero(EditText ev)
{
setText("0", ev);
}
public void setZero()
{
setZero((EditText) findViewById(R.id.mainTextField));
}
public void setText(String n, EditText ev)
{
ev.setText(n);
ev.setSelection(0, n.length()); // Ensure the cursor is at the end
}
public void setText(String n)
{
setText(n, (EditText) findViewById(R.id.mainTextField));
}
public void terms(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
setText(inIntTermsOfAny(parseComplex(ev.getText().toString())), ev);
}
public void decimal(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
setText(Complex.toString(parseComplex(ev.getText().toString())), ev);
}
public Complex getValue(final EditText ev) // Parses the content of ev into a double.
{
return parseComplex(ev.getText().toString().trim());
}
public void doCalculate(final EditText ev, OnClickListener ocl) // Common code for buttons that use the mainCalculateButton.
{
doCalculate(ev, ocl, Complex.ZERO);
}
public void doCalculate(final EditText ev, OnClickListener ocl, Complex n) // Common code for buttons that use the mainCalculateButton, setting the default value to n rather than zero.
{
setText(inIntTermsOfAny(n), ev);
final Button b=(Button)findViewById(R.id.mainCalculateButton);
b.setVisibility(View.VISIBLE);
b.setOnClickListener(ocl);
}
public void add(View v)
{
final EditText ev=(EditText)findViewById(R.id.mainTextField);
currentValue=getValue(ev);
doCalculate(ev, new OnClickListener() {
@Override
public void onClick(View v) {
v.setOnClickListener(null);
String num = ev.getText().toString().trim();
if ("".equals(num))
return;
setText(inIntTermsOfAny(currentValue.addTo(parseComplex(num))), ev);
v.setVisibility(View.GONE);
}
});
}
public void subtract(View v)
{
final EditText ev=(EditText)findViewById(R.id.mainTextField);
currentValue=getValue(ev);
doCalculate(ev, new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
String num=ev.getText().toString().trim();
if ("".equals(num))
return;
setText(inIntTermsOfAny(currentValue.subtractTo(parseComplex(num))), ev);
v.setVisibility(View.GONE);
}
});
}
public void subtract2(View v)
{
final EditText ev=(EditText)findViewById(R.id.mainTextField);
currentValue=getValue(ev);
doCalculate(ev, new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
String num=ev.getText().toString().trim();
if ("".equals(num))
return;
setText(inIntTermsOfAny(parseComplex(num).subtractTo(currentValue)), ev);
v.setVisibility(View.GONE);
}
});
}
public void multiply(View v)
{
final EditText ev=(EditText)findViewById(R.id.mainTextField);
currentValue=getValue(ev);
doCalculate(ev, new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
String num=ev.getText().toString().trim();
if ("".equals(num))
return;
setText(inIntTermsOfAny(currentValue.multiplyTo(parseComplex(num))), ev);
v.setVisibility(View.GONE);
}
});
}
public void divide(View v)
{
final EditText ev=(EditText)findViewById(R.id.mainTextField);
currentValue=getValue(ev);
doCalculate(ev, new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
String num=ev.getText().toString().trim();
if ("".equals(num))
return;
Complex n=parseComplex(num);
if (n.equals(Complex.ZERO))
setText("Error: Divide by zero.");
else
setText(inIntTermsOfAny(currentValue.divideTo(n)), ev);
v.setVisibility(View.GONE);
}
}, Complex.ONE);
}
public void divide2(View v)
{
final EditText ev=(EditText)findViewById(R.id.mainTextField);
currentValue=getValue(ev);
doCalculate(ev, new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
String num=ev.getText().toString().trim();
if ("".equals(num))
return;
Complex n=parseComplex(num);
if (n.equals(Complex.ZERO))
setText("Error: Divide by zero.");
else
setText(inIntTermsOfAny(n.divideTo(currentValue)), ev);
v.setVisibility(View.GONE);
}
}, Complex.ONE);
}
public void remainder(View v)
{
final EditText ev=(EditText)findViewById(R.id.mainTextField);
currentValue=getValue(ev);
if (!Complex.round(currentValue).equals(currentValue))
{
setText("Error: Parameter is not an integer: "+ev.getText(), ev);
return;
}
doCalculate(ev, new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
String num=ev.getText().toString().trim();
if ("".equals(num))
return;
v.setVisibility(View.GONE);
Complex tmp=parseComplex(num);
if (!Complex.round(tmp).equals(tmp))
setText("Error: Parameter is not an integer: "+num, ev);
else if (Complex.round(tmp).equals(Complex.ZERO))
setText("Error: Divide by zero.");
else
setText(inIntTermsOfAny(Complex.round(currentValue).modulo(Complex.round(tmp))), ev);
}
}, Complex.ONE);
}
public void remainder2(View v)
{
final EditText ev=(EditText)findViewById(R.id.mainTextField);
currentValue=getValue(ev);
if (!Complex.round(currentValue).equals(currentValue))
{
setText("Error: Parameter is not an integer: "+ev.getText(), ev);
return;
}
doCalculate(ev, new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
String num=ev.getText().toString().trim();
if ("".equals(num))
return;
v.setVisibility(View.GONE);
Complex tmp=parseComplex(num);
if (!Complex.round(tmp).equals(tmp))
setText("Error: Parameter is not an integer: "+num, ev);
else if (Complex.round(currentValue).equals(Complex.ZERO))
setText("Error: Divide by zero.");
else
setText(inIntTermsOfAny(Complex.round(tmp).modulo(Complex.round(currentValue))), ev);
}
}, Complex.ONE);
}
public void e(View v)
{
setText("e");
}
public void pi(View v)
{
setText("\u03C0");
}
public void i(View v) { setText("i"); }
public void negate(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
setText(inIntTermsOfAny(Complex.negate(parseComplex(ev.getText().toString()))), ev);
}
public void sin(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
setText(inIntTermsOfPi(Complex.sin(parseComplex(ev.getText().toString()))), ev);
}
public void cos(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
setText(inIntTermsOfPi(Complex.cos(parseComplex(ev.getText().toString()))), ev);
}
public void tan(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
setText(inIntTermsOfPi(Complex.tan(parseComplex(ev.getText().toString()))), ev);
}
public void arcsin(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
setText(inIntTermsOfPi(Complex.asin(parseComplex(ev.getText().toString()))), ev);
}
public void arccos(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
setText(inIntTermsOfPi(Complex.acos(parseComplex(ev.getText().toString()))), ev);
}
public void arctan(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
setText(inIntTermsOfPi(Complex.atan(parseComplex(ev.getText().toString()))), ev);
}
public void exp(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
setText(inIntTermsOfE(Complex.exp(parseComplex(ev.getText().toString()))), ev);
}
public void degrees(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
setText((Complex.toDegrees(parseComplex(ev.getText().toString()))).toString(), ev);
}
public void radians(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
setText(inIntTermsOfPi(Complex.toRadians(parseComplex(ev.getText().toString()))), ev);
}
public void radians2(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
Complex tmp=parseComplex(ev.getText().toString());
tmp=Complex.divide(tmp, new Complex(180));
setText(Complex.toString(tmp)+'\u03C0', ev);
}
public void ln(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
setText(inIntTermsOfE(Complex.ln(parseComplex(ev.getText().toString()))), ev);
}
public void log(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
setText(inIntTermsOfAny(Complex.log10(parseComplex(ev.getText().toString()))), ev);
}
public void logb(View v)
{
final EditText ev=(EditText)findViewById(R.id.mainTextField);
currentValue=parseComplex(ev.getText().toString());
doCalculate(ev, new OnClickListener() {
@Override
public void onClick(View v) {
v.setOnClickListener(null);
String num = ev.getText().toString();
if ("".equals(num))
return;
setText(inIntTermsOfAny(Complex.log(currentValue, parseComplex(num))), ev);
v.setVisibility(View.GONE);
}
}, new Complex(10));
}
public void logb2(View v)
{
final EditText ev=(EditText)findViewById(R.id.mainTextField);
currentValue=parseComplex(ev.getText().toString());
doCalculate(ev,new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
String num=ev.getText().toString();
if ("".equals(num))
return;
setText(inIntTermsOfAny(Complex.log(parseComplex(num), currentValue)), ev);
v.setVisibility(View.GONE);
}
}, new Complex(10));
}
public void round(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
setText(Complex.toString(Complex.round(parseComplex(ev.getText().toString()))));
}
public void sqrt(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
Complex n=parseComplex(ev.getText().toString());
setText(inIntTermsOfAny(Complex.sqrt(n)), ev);
}
public void cbrt(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
setText(inIntTermsOfAny(Complex.cbrt(parseComplex(ev.getText().toString()))), ev);
}
public void ceil(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
setText(Complex.toString(Complex.ceil(parseComplex(ev.getText().toString()))), ev);
}
public void floor(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
setText(Complex.toString(Complex.floor(parseComplex(ev.getText().toString()))), ev);
}
public void pow(View v)
{
final EditText ev=(EditText)findViewById(R.id.mainTextField);
currentValue=parseComplex(ev.getText().toString());
doCalculate(ev, new OnClickListener() {
@Override
public void onClick(View v) {
v.setOnClickListener(null);
String num = ev.getText().toString();
if (!"".equals(num))
setText(inIntTermsOfAny(Complex.pow(currentValue, parseComplex(num))), ev);
v.setVisibility(View.GONE);
}
}, currentValue);
}
public void pow2(View v)
{
final EditText ev=(EditText)findViewById(R.id.mainTextField);
currentValue=parseComplex(ev.getText().toString());
doCalculate(ev, new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
String num=ev.getText().toString();
if (!"".equals(num))
setText(inIntTermsOfAny(Complex.pow(parseComplex(num), currentValue)), ev);
v.setVisibility(View.GONE);
}
}, currentValue);
}
public void abs (View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
setText(inIntTermsOfAny(Complex.abs(parseComplex(ev.getText().toString()))), ev);
}
public void sinh(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
setText(inIntTermsOfAny(Complex.sinh(parseComplex(ev.getText().toString()))), ev);
}
public void expm(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
setText(inIntTermsOfAny(Complex.expm1(parseComplex(ev.getText().toString()))), ev);
}
public void cosh(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
setText(inIntTermsOfAny(Complex.cosh(parseComplex(ev.getText().toString()))), ev);
}
public void tanh(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
setText(inIntTermsOfAny(Complex.tanh(parseComplex(ev.getText().toString()))), ev);
}
public void lnp(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
setText(inIntTermsOfAny(Complex.ln1p(parseComplex(ev.getText().toString()))), ev);
}
public void square(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
Complex num=parseComplex(ev.getText().toString());
setText(inIntTermsOfAny(num.square()), ev);
}
public void cube(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
Complex num=parseComplex(ev.getText().toString());
setText(inIntTermsOfAny(Complex.multiply(num.square(), num)), ev);
}
public void isPrime(View v) // Standard primality, not Gaussian
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
Complex m=parseComplex(ev.getText().toString());
if (!m.isReal())
{
if (!m.isImaginary()) // M is zero
setText("Not prime");
else
setText("Error: Cannot compute standard is prime for complex numbers");
return;
}
double num=m.real;
int n=(int)Math.floor(num);
if (n!=num || n<1 || isDivisible(n,2)) {
setText("Not prime");
return;
}
if (n==1) {
setText("Not prime or composite");
return;
}
for (int i=3; i<=Math.sqrt(n); i+=2) {
if (isDivisible(n, i)) {
setText("Not prime");
return;
}
}
setText("Prime");
}
public void isGaussianPrime(View v) // Computes whether a prime number is a Gaussian prime
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
Complex m=parseComplex(ev.getText().toString());
boolean prime=false;
if (Math.floor(m.real)==m.real && Math.floor(m.imaginary)==m.imaginary)
{
if (m.isReal())
{
int n=(int)Math.abs(m.real);
if (isDivisible(n-3, 4))
{
prime=true;
for (int i = 3; i <= Math.sqrt(n); i += 2) {
if (isDivisible(n, i)) {
prime = false;
break;
}
}
}
}
else if (m.isImaginary())
{
int n=(int)Math.abs(m.imaginary);
if (isDivisible(n-3, 4))
{
prime=true;
for (int i=3; i<=Math.sqrt(n); i+=2) {
if (isDivisible(n, i)) {
prime=false;
break;
}
}
}
}
else
{
double norm=m.magnitude();
int n=(int) Math.floor(norm);
if (n==norm)
{
if (n!=1 && !isDivisible(n, 2))
{
prime=true;
for (int i=3; i<=Math.sqrt(n); i+=2) {
if (isDivisible(n, i)) {
prime=false;
break;
}
}
}
}
}
}
setText(prime ? "Gaussian prime" : "Not Gaussian prime");
}
public boolean isDivisible(int num, int den) {
return num%den==0;
}
public double fastPow(double val, int power)
{
if (val==2)
return fastPow(power).doubleValue();
switch (power)
{
case 0:
return 1;
case 1:
return val;
case 2:
return val*val;
default:
if (power<0)
return 1/fastPow(val, -1*power);
if (power%2==0)
return fastPow(fastPow(val, 2), power>>1);
return val*fastPow(val, power-1);
}
}
public BigInteger fastPow(int pow) // 2 as base
{
return BigInteger.ZERO.flipBit(pow);
}
public void raise2(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
Complex num=parseComplex(ev.getText().toString());
if (num.isReal() && Math.round(num.real)==num.real) // Integer power. Use the fastpow() and a BigInteger.
setText(fastPow((int)Math.round(num.real)).toString(), ev);
else
setText(Complex.toString(Complex.pow(2, num)), ev);
}
}
| app/src/main/java/com/Ryan/Calculator/MainActivity.java | package com.Ryan.Calculator;
import android.annotation.TargetApi;
import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import java.math.BigInteger;
public class MainActivity extends Activity
{
public Complex currentValue=Complex.ZERO;
/** Called when the activity is first created. */
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB)
{
getActionBar().hide();
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.ICE_CREAM_SANDWICH)
findViewById(R.id.mainLayout).setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE);
}
setZero();
}
public Complex parseComplex(String num)
{
if (num==null || num.indexOf("Error", 0)==0 || num.indexOf("ERROR", 0)==0)
return Complex.ZERO;
if ("Not prime".equals(num) || "Not prime or composite".equals(num) || "Not Gaussian prime".equals(num))
return Complex.ZERO;
if ("Prime".equals(num) || "Gaussian prime".equals(num))
return Complex.ONE;
if (num.charAt(num.length()-1)=='\u03C0')
{
if (num.length()==1)
return Complex.PI;
else if (num.length()==2 && num.charAt(0)=='-') // If the string is two long and the first character is a negation
return Complex.negate(Complex.PI); // Return negative pi
return Complex.multiply(parseComplex(num.substring(0, num.length()-1)), Complex.PI);
}
if (num.charAt(num.length()-1)=='e')
{
if (num.length()==1)
return Complex.E;
else if (num.length()==2 && num.charAt(0)=='-') // If the string is two long and the first character is a negation
return Complex.negate(Complex.E); // Return negative e
return Complex.multiply(parseComplex(num.substring(0, num.length()-1)), Complex.E);
}
try {
return Complex.parseString(num);
}
catch (NumberFormatException e) {
setText("ERROR: Invalid number");
View v=findViewById(R.id.mainCalculateButton);
v.setOnClickListener(null); // Cancel existing computation
v.setVisibility(View.GONE); // Remove the button
return Complex.ZERO;
}
}
public String inIntTermsOfPi(double num)
{
if (num==0)
return "0";
double tmp=num/Math.PI;
int n=(int)tmp;
if (n==tmp)
{
if (n==-1) // If it is a negative, but otherwise 1
return "-\u03C0"; // Return negative pi
return (n==1 ? "" : Integer.toString(n))+"\u03C0";
}
else
return Double.toString(num);
}
public String inIntTermsOfPi(Complex num)
{
if (num.equals(Complex.ZERO)) // Special case: Prevents "0+0i"
return "0";
if (num.isReal())
return inIntTermsOfPi(num.real);
if (num.isImaginary()) {
if (num.imaginary==1)
return "i";
else if (num.imaginary==-1)
return "-i";
return inIntTermsOfPi(num.imaginary) + 'i';
}
String out=inIntTermsOfPi(num.real);
if (num.imaginary>0)
out+="+";
out+=inIntTermsOfPi(num.imaginary)+'i';
return out;
}
public String inIntTermsOfE(double num)
{
if (num==0)
return "0";
double tmp=num/Math.E;
int n=(int)tmp;
if (n==tmp)
{
if (n==-1) // If it is a negative, but otherwise 1
return "-e"; // Return negative e
return (n==1 ? "" : Integer.toString((int)tmp))+"e";
}
else
return Double.toString(num);
}
public String inIntTermsOfE(Complex num)
{
if (num.equals(Complex.ZERO)) // Special case: Prevents "0+0i"
return "0";
if (num.isReal())
return inIntTermsOfE(num.real);
if (num.isImaginary()) {
if (num.imaginary==1)
return "i";
else if (num.imaginary==-1)
return "-i";
return inIntTermsOfE(num.imaginary) + 'i';
}
String out=inIntTermsOfE(num.real);
if (num.imaginary>0)
out+="+";
out+=inIntTermsOfE(num.imaginary)+'i';
return out;
}
public String inIntTermsOfAny(double num)
{
if (Double.isNaN(num)) // "Last-resort" check
return "ERROR: Nonreal or non-numeric result."; // Trap NaN and return a generic error for it.
// Because of that check, we can guarantee that NaN's will not be floating around for more than one expression.
String out=inIntTermsOfPi(num);
if (!out.equals(Double.toString(num)))
return out;
else
return inIntTermsOfE(num);
}
public String inIntTermsOfAny(Complex num)
{
if (num.equals(Complex.ZERO)) // Special case: Prevents "0+0i"
return "0";
if (num.isReal())
return inIntTermsOfAny(num.real);
if (num.isImaginary()) {
if (num.imaginary==1)
return "i";
else if (num.imaginary==-1)
return "-i";
return inIntTermsOfAny(num.imaginary) + 'i';
}
String out=inIntTermsOfAny(num.real);
if (num.imaginary>0)
out+="+";
out+=inIntTermsOfAny(num.imaginary)+'i';
return out;
}
public void zero(View v)
{
setZero();
}
public void setZero(EditText ev)
{
setText("0", ev);
}
public void setZero()
{
setZero((EditText) findViewById(R.id.mainTextField));
}
public void setText(String n, EditText ev)
{
ev.setText(n);
ev.setSelection(0, n.length()); // Ensure the cursor is at the end
}
public void setText(String n)
{
setText(n, (EditText) findViewById(R.id.mainTextField));
}
public void terms(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
setText(inIntTermsOfAny(parseComplex(ev.getText().toString())), ev);
}
public void decimal(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
setText(Complex.toString(parseComplex(ev.getText().toString())), ev);
}
public Complex getValue(final EditText ev) // Parses the content of ev into a double.
{
return parseComplex(ev.getText().toString().trim());
}
public void doCalculate(final EditText ev, OnClickListener ocl) // Common code for buttons that use the mainCalculateButton.
{
doCalculate(ev, ocl, Complex.ZERO);
}
public void doCalculate(final EditText ev, OnClickListener ocl, Complex n) // Common code for buttons that use the mainCalculateButton, setting the default value to n rather than zero.
{
setText(inIntTermsOfAny(n), ev);
final Button b=(Button)findViewById(R.id.mainCalculateButton);
b.setVisibility(View.VISIBLE);
b.setOnClickListener(ocl);
}
public void add(View v)
{
final EditText ev=(EditText)findViewById(R.id.mainTextField);
currentValue=getValue(ev);
doCalculate(ev, new OnClickListener() {
@Override
public void onClick(View v) {
v.setOnClickListener(null);
String num = ev.getText().toString().trim();
if ("".equals(num))
return;
setText(inIntTermsOfAny(currentValue.addTo(parseComplex(num))), ev);
v.setVisibility(View.GONE);
}
});
}
public void subtract(View v)
{
final EditText ev=(EditText)findViewById(R.id.mainTextField);
currentValue=getValue(ev);
doCalculate(ev, new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
String num=ev.getText().toString().trim();
if ("".equals(num))
return;
setText(inIntTermsOfAny(currentValue.subtractTo(parseComplex(num))), ev);
v.setVisibility(View.GONE);
}
});
}
public void subtract2(View v)
{
final EditText ev=(EditText)findViewById(R.id.mainTextField);
currentValue=getValue(ev);
doCalculate(ev, new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
String num=ev.getText().toString().trim();
if ("".equals(num))
return;
setText(inIntTermsOfAny(parseComplex(num).subtractTo(currentValue)), ev);
v.setVisibility(View.GONE);
}
});
}
public void multiply(View v)
{
final EditText ev=(EditText)findViewById(R.id.mainTextField);
currentValue=getValue(ev);
doCalculate(ev, new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
String num=ev.getText().toString().trim();
if ("".equals(num))
return;
setText(inIntTermsOfAny(currentValue.multiplyTo(parseComplex(num))), ev);
v.setVisibility(View.GONE);
}
});
}
public void divide(View v)
{
final EditText ev=(EditText)findViewById(R.id.mainTextField);
currentValue=getValue(ev);
doCalculate(ev, new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
String num=ev.getText().toString().trim();
if ("".equals(num))
return;
Complex n=parseComplex(num);
if (n.equals(Complex.ZERO))
setText("Error: Divide by zero.");
else
setText(inIntTermsOfAny(currentValue.divideTo(n)), ev);
v.setVisibility(View.GONE);
}
}, Complex.ONE);
}
public void divide2(View v)
{
final EditText ev=(EditText)findViewById(R.id.mainTextField);
currentValue=getValue(ev);
doCalculate(ev, new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
String num=ev.getText().toString().trim();
if ("".equals(num))
return;
Complex n=parseComplex(num);
if (n.equals(Complex.ZERO))
setText("Error: Divide by zero.");
else
setText(inIntTermsOfAny(n.divideTo(currentValue)), ev);
v.setVisibility(View.GONE);
}
}, Complex.ONE);
}
public void remainder(View v)
{
final EditText ev=(EditText)findViewById(R.id.mainTextField);
currentValue=getValue(ev);
if (!Complex.round(currentValue).equals(currentValue))
{
setText("Error: Parameter is not an integer: "+ev.getText(), ev);
return;
}
doCalculate(ev, new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
String num=ev.getText().toString().trim();
if ("".equals(num))
return;
v.setVisibility(View.GONE);
Complex tmp=parseComplex(num);
if (!Complex.round(tmp).equals(tmp))
setText("Error: Parameter is not an integer: "+num, ev);
else if (Complex.round(tmp).equals(Complex.ZERO))
setText("Error: Divide by zero.");
else
setText(inIntTermsOfAny(Complex.round(currentValue).modulo(Complex.round(tmp))), ev);
}
}, Complex.ONE);
}
public void remainder2(View v)
{
final EditText ev=(EditText)findViewById(R.id.mainTextField);
currentValue=getValue(ev);
if (!Complex.round(currentValue).equals(currentValue))
{
setText("Error: Parameter is not an integer: "+ev.getText(), ev);
return;
}
doCalculate(ev, new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
String num=ev.getText().toString().trim();
if ("".equals(num))
return;
v.setVisibility(View.GONE);
Complex tmp=parseComplex(num);
if (!Complex.round(tmp).equals(tmp))
setText("Error: Parameter is not an integer: "+num, ev);
else if (Complex.round(currentValue).equals(Complex.ZERO))
setText("Error: Divide by zero.");
else
setText(inIntTermsOfAny(Complex.round(tmp).modulo(Complex.round(currentValue))), ev);
}
}, Complex.ONE);
}
public void e(View v)
{
setText("e");
}
public void pi(View v)
{
setText("\u03C0");
}
public void i(View v) { setText("i"); }
public void negate(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
setText(inIntTermsOfAny(Complex.negate(parseComplex(ev.getText().toString()))), ev);
}
public void sin(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
setText(inIntTermsOfPi(Complex.sin(parseComplex(ev.getText().toString()))), ev);
}
public void cos(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
setText(inIntTermsOfPi(Complex.cos(parseComplex(ev.getText().toString()))), ev);
}
public void tan(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
setText(inIntTermsOfPi(Complex.tan(parseComplex(ev.getText().toString()))), ev);
}
public void arcsin(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
setText(inIntTermsOfPi(Complex.asin(parseComplex(ev.getText().toString()))), ev);
}
public void arccos(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
setText(inIntTermsOfPi(Complex.acos(parseComplex(ev.getText().toString()))), ev);
}
public void arctan(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
setText(inIntTermsOfPi(Complex.atan(parseComplex(ev.getText().toString()))), ev);
}
public void exp(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
setText(inIntTermsOfE(Complex.exp(parseComplex(ev.getText().toString()))), ev);
}
public void degrees(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
setText((Complex.toDegrees(parseComplex(ev.getText().toString()))).toString(), ev);
}
public void radians(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
setText(inIntTermsOfPi(Complex.toRadians(parseComplex(ev.getText().toString()))), ev);
}
public void radians2(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
Complex tmp=parseComplex(ev.getText().toString());
tmp=Complex.divide(tmp, new Complex(180));
setText(Complex.toString(tmp)+'\u03C0', ev);
}
public void ln(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
setText(inIntTermsOfE(Complex.ln(parseComplex(ev.getText().toString()))), ev);
}
public void log(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
setText(inIntTermsOfAny(Complex.log10(parseComplex(ev.getText().toString()))), ev);
}
public void logb(View v)
{
final EditText ev=(EditText)findViewById(R.id.mainTextField);
currentValue=parseComplex(ev.getText().toString());
doCalculate(ev, new OnClickListener() {
@Override
public void onClick(View v) {
v.setOnClickListener(null);
String num = ev.getText().toString();
if ("".equals(num))
return;
setText(inIntTermsOfAny(Complex.log(currentValue, parseComplex(num))), ev);
v.setVisibility(View.GONE);
}
}, new Complex(10));
}
public void logb2(View v)
{
final EditText ev=(EditText)findViewById(R.id.mainTextField);
currentValue=parseComplex(ev.getText().toString());
doCalculate(ev,new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
String num=ev.getText().toString();
if ("".equals(num))
return;
setText(inIntTermsOfAny(Complex.log(parseComplex(num), currentValue)), ev);
v.setVisibility(View.GONE);
}
}, new Complex(10));
}
public void round(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
setText(Complex.toString(Complex.round(parseComplex(ev.getText().toString()))));
}
public void sqrt(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
Complex n=parseComplex(ev.getText().toString());
setText(inIntTermsOfAny(Complex.sqrt(n)), ev);
}
public void cbrt(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
setText(inIntTermsOfAny(Complex.cbrt(parseComplex(ev.getText().toString()))), ev);
}
public void ceil(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
setText(Complex.toString(Complex.ceil(parseComplex(ev.getText().toString()))), ev);
}
public void floor(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
setText(Complex.toString(Complex.floor(parseComplex(ev.getText().toString()))), ev);
}
public void pow(View v)
{
final EditText ev=(EditText)findViewById(R.id.mainTextField);
currentValue=parseComplex(ev.getText().toString());
doCalculate(ev, new OnClickListener() {
@Override
public void onClick(View v) {
v.setOnClickListener(null);
String num = ev.getText().toString();
if (!"".equals(num))
setText(inIntTermsOfAny(Complex.pow(currentValue, parseComplex(num))), ev);
v.setVisibility(View.GONE);
}
}, currentValue);
}
public void pow2(View v)
{
final EditText ev=(EditText)findViewById(R.id.mainTextField);
currentValue=parseComplex(ev.getText().toString());
doCalculate(ev, new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
String num=ev.getText().toString();
if (!"".equals(num))
setText(inIntTermsOfAny(Complex.pow(parseComplex(num), currentValue)), ev);
v.setVisibility(View.GONE);
}
}, currentValue);
}
public void abs (View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
setText(inIntTermsOfAny(Complex.abs(parseComplex(ev.getText().toString()))), ev);
}
public void sinh(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
setText(inIntTermsOfAny(Complex.sinh(parseComplex(ev.getText().toString()))), ev);
}
public void expm(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
setText(inIntTermsOfAny(Complex.expm1(parseComplex(ev.getText().toString()))), ev);
}
public void cosh(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
setText(inIntTermsOfAny(Complex.cosh(parseComplex(ev.getText().toString()))), ev);
}
public void tanh(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
setText(inIntTermsOfAny(Complex.tanh(parseComplex(ev.getText().toString()))), ev);
}
public void lnp(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
setText(inIntTermsOfAny(Complex.ln1p(parseComplex(ev.getText().toString()))), ev);
}
public void square(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
Complex num=parseComplex(ev.getText().toString());
setText(inIntTermsOfAny(num.square()), ev);
}
public void cube(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
Complex num=parseComplex(ev.getText().toString());
setText(inIntTermsOfAny(Complex.multiply(num.square(), num)), ev);
}
public void isPrime(View v) // Standard primality, not Gaussian
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
Complex m=parseComplex(ev.getText().toString());
if (!m.isReal())
{
if (!m.isImaginary()) // M is zero
setText("Not prime");
else
setText("Error: Cannot compute standard is prime for complex numbers");
return;
}
double num=m.real;
int n=(int)Math.floor(num);
if (n!=num || n<1 || isDivisible(n,2)) {
setText("Not prime");
return;
}
if (n==1) {
setText("Not prime or composite");
return;
}
for (int i=3; i<=Math.sqrt(n); i+=2) {
if (isDivisible(n, i)) {
setText("Not prime");
return;
}
}
setText("Prime");
}
public void isGaussianPrime(View v) // Computes whether a prime number is a Gaussian prime
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
Complex m=parseComplex(ev.getText().toString());
boolean prime=false;
if (Math.floor(m.real)==m.real && Math.floor(m.imaginary)==m.imaginary)
{
if (m.isReal())
{
int n=(int)Math.abs(m.real);
if (isDivisible(n-3, 4))
{
prime=true;
for (int i = 3; i <= Math.sqrt(n); i += 2) {
if (isDivisible(n, i)) {
prime = false;
break;
}
}
}
}
else if (m.isImaginary())
{
int n=(int)Math.abs(m.imaginary);
if (isDivisible(n-3, 4))
{
prime=true;
for (int i=3; i<=Math.sqrt(n); i+=2) {
if (isDivisible(n, i)) {
prime=false;
break;
}
}
}
}
else
{
double norm=m.magnitude();
int n=(int) Math.floor(norm);
if (n==norm)
{
if (n!=1 && !isDivisible(n, 2))
{
prime=true;
for (int i=3; i<=Math.sqrt(n); i+=2) {
if (isDivisible(n, i)) {
prime=false;
break;
}
}
}
}
}
}
setText(prime ? "Gaussian prime" : "Not Gaussian prime");
}
public boolean isDivisible(int num, int den) {
return num%den==0;
}
public double fastPow(double val, int power)
{
if (val==2)
return fastPow(power).doubleValue();
switch (power)
{
case 0:
return 1;
case 1:
return val;
case 2:
return val*val;
default:
if (power<0)
return 1/fastPow(val, -1*power);
if (power%2==0)
return fastPow(fastPow(val, 2), power>>1);
return val*fastPow(val, power-1);
}
}
public BigInteger fastPow(int pow) // 2 as base
{
return BigInteger.ZERO.flipBit(pow);
}
public void raise2(View v)
{
EditText ev=(EditText)findViewById(R.id.mainTextField);
Complex num=parseComplex(ev.getText().toString());
if (num.isReal() && Math.round(num.real)==num.real) // Integer power. Use the fastpow() and a BigInteger.
setText(fastPow((int)Math.round(num.real)).toString(), ev);
else
setText(Complex.toString(Complex.pow(2, num)), ev);
}
}
| Fix parseComplex handling
It really should output NaN instead of 0 for an invalid number.
| app/src/main/java/com/Ryan/Calculator/MainActivity.java | Fix parseComplex handling | <ide><path>pp/src/main/java/com/Ryan/Calculator/MainActivity.java
<ide> View v=findViewById(R.id.mainCalculateButton);
<ide> v.setOnClickListener(null); // Cancel existing computation
<ide> v.setVisibility(View.GONE); // Remove the button
<del> return Complex.ZERO;
<add> return Complex.ERROR;
<ide> }
<ide> }
<ide> |
|
JavaScript | agpl-3.0 | cccab3b6b14af96230b8e7ee96246c9cd9f7d5b1 | 0 | zhx828/cbioportal,kalletlak/cbioportal,fcriscuo/cbioportal,bengusty/cbioportal,cBioPortal/cbioportal,IntersectAustralia/cbioportal,adamabeshouse/cbioportal,jjgao/cbioportal,inodb/cbioportal,xmao/cbioportal,shrumit/cbioportal-gsoc-final,mandawilson/cbioportal,IntersectAustralia/cbioportal,shrumit/cbioportal-gsoc-final,onursumer/cbioportal,yichaoS/cbioportal,adamabeshouse/cbioportal,leedonghn4/cbio-portal-webgl,zheins/cbioportal,kalletlak/cbioportal,IntersectAustralia/cbioportal,gsun83/cbioportal,yichaoS/cbioportal,leedonghn4/cbio-portal-webgl,bengusty/cbioportal,adamabeshouse/cbioportal,angelicaochoa/cbioportal,inodb/cbioportal,jjgao/cbioportal,gsun83/cbioportal,d3b-center/pedcbioportal,bihealth/cbioportal,bihealth/cbioportal,xmao/cbioportal,zheins/cbioportal,j-hudecek/cbioportal,j-hudecek/cbioportal,xmao/cbioportal,n1zea144/cbioportal,adamabeshouse/cbioportal,onursumer/cbioportal,zhx828/cbioportal,shrumit/cbioportal-gsoc-final,j-hudecek/cbioportal,adamabeshouse/cbioportal,n1zea144/cbioportal,adamabeshouse/cbioportal,zhx828/cbioportal,fcriscuo/cbioportal,n1zea144/cbioportal,gsun83/cbioportal,yichaoS/cbioportal,n1zea144/cbioportal,inodb/cbioportal,gsun83/cbioportal,bihealth/cbioportal,angelicaochoa/cbioportal,xmao/cbioportal,pughlab/cbioportal,xmao/cbioportal,j-hudecek/cbioportal,shrumit/cbioportal-gsoc-final,yichaoS/cbioportal,cBioPortal/cbioportal,cBioPortal/cbioportal,gsun83/cbioportal,n1zea144/cbioportal,fcriscuo/cbioportal,gsun83/cbioportal,kalletlak/cbioportal,d3b-center/pedcbioportal,bengusty/cbioportal,zhx828/cbioportal,pughlab/cbioportal,leedonghn4/cbio-portal-webgl,pughlab/cbioportal,sheridancbio/cbioportal,pughlab/cbioportal,zhx828/cbioportal,onursumer/cbioportal,angelicaochoa/cbioportal,pughlab/cbioportal,zheins/cbioportal,IntersectAustralia/cbioportal,j-hudecek/cbioportal,d3b-center/pedcbioportal,cBioPortal/cbioportal,mandawilson/cbioportal,bengusty/cbioportal,angelicaochoa/cbioportal,inodb/cbioportal,n1zea144/cbioportal,cBioPortal/cbioportal,IntersectAustralia/cbioportal,cBioPortal/cbioportal,zheins/cbioportal,kalletlak/cbioportal,jjgao/cbioportal,yichaoS/cbioportal,xmao/cbioportal,mandawilson/cbioportal,mandawilson/cbioportal,pughlab/cbioportal,sheridancbio/cbioportal,fcriscuo/cbioportal,angelicaochoa/cbioportal,d3b-center/pedcbioportal,leedonghn4/cbio-portal-webgl,sheridancbio/cbioportal,jjgao/cbioportal,bihealth/cbioportal,zheins/cbioportal,IntersectAustralia/cbioportal,jjgao/cbioportal,bengusty/cbioportal,mandawilson/cbioportal,onursumer/cbioportal,d3b-center/pedcbioportal,yichaoS/cbioportal,sheridancbio/cbioportal,shrumit/cbioportal-gsoc-final,inodb/cbioportal,sheridancbio/cbioportal,bihealth/cbioportal,bengusty/cbioportal,yichaoS/cbioportal,zheins/cbioportal,shrumit/cbioportal-gsoc-final,inodb/cbioportal,pughlab/cbioportal,jjgao/cbioportal,inodb/cbioportal,angelicaochoa/cbioportal,leedonghn4/cbio-portal-webgl,zhx828/cbioportal,fcriscuo/cbioportal,kalletlak/cbioportal,j-hudecek/cbioportal,mandawilson/cbioportal,d3b-center/pedcbioportal,shrumit/cbioportal-gsoc-final,jjgao/cbioportal,bihealth/cbioportal,angelicaochoa/cbioportal,fcriscuo/cbioportal,mandawilson/cbioportal,adamabeshouse/cbioportal,kalletlak/cbioportal,onursumer/cbioportal,n1zea144/cbioportal,IntersectAustralia/cbioportal,leedonghn4/cbio-portal-webgl,kalletlak/cbioportal,zhx828/cbioportal,gsun83/cbioportal,d3b-center/pedcbioportal,onursumer/cbioportal,sheridancbio/cbioportal,bihealth/cbioportal | /*
* Copyright (c) 2015 Memorial Sloan-Kettering Cancer Center.
*
* 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. The software and documentation provided hereunder
* is on an "as is" basis, and Memorial Sloan-Kettering Cancer Center has no
* obligations to provide maintenance, support, updates, enhancements or
* modifications. In no event shall Memorial Sloan-Kettering Cancer Center be
* liable to any party for direct, indirect, special, incidental or
* consequential damages, including lost profits, arising out of the use of this
* software and its documentation, even if Memorial Sloan-Kettering Cancer
* Center has been advised of the possibility of such damage.
*/
/*
* This file is part of cBioPortal.
*
* cBioPortal is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/******************************************************************************************
* Dynamic Query Javascript, built with JQuery
* @author Ethan Cerami, Caitlin Byrne.
*
* This code performs the following functions:
*
* 1. Connects to the portal via AJAX and downloads a JSON document containing information
* regarding all cancer studies and gene sets stored in the CGDS.
* 2. Creates event handler for when user selects a cancer study. This triggers updates
in the genomic profiles and case lists displayed.
* 3. Creates event handler for when user selects a gene set. This triggers updates to the
gene set text area.
******************************************************************************************/
// Create Constants
var PROFILE_MUTATION = "PROFILE_MUTATION";
var PROFILE_MUTATION_EXTENDED = "PROFILE_MUTATION_EXTENDED";
var PROFILE_COPY_NUMBER_ALTERATION = "PROFILE_COPY_NUMBER_ALTERATION"
var PROFILE_MRNA_EXPRESSION = "PROFILE_MRNA_EXPRESSION";
var PROFILE_PROTEIN = "PROFILE_PROTEIN";
var PROFILE_RPPA = "PROFILE_RPPA";
var PROFILE_METHYLATION = "PROFILE_METHYLATION"
var caseSetSelectionOverriddenByUser = false;
var selectedStudiesStorageKey = "cbioportal_selected_studies";
// Create Log Function, if FireBug is not Installed.
if(typeof(console) === "undefined" || typeof(console.log) === "undefined")
var console = { log: function() { } };
// Triggered only when document is ready.
$(document).ready(function(){
// Load Portal JSON Meta Data while showing loader image in place of query form
loadMetaData();
// Set up Event Handler for User Selecting Cancer Study from Pull-Down Menu
$("#select_single_study").change(function() {
caseSetSelectionOverriddenByUser = false; // reset
console.log("#select_single_study change ( cancerStudySelected() )");
cancerStudySelected();
caseSetSelected();
$('#custom_case_set_ids').empty(); // reset the custom case set textarea
$('#select_single_study').trigger('doneChanging');
});
// Set up Event Handler for User Selecting a Case Set
$("#select_case_set").change(function() {
caseSetSelected();
caseSetSelectionOverriddenByUser = true;
});
// Set up Event Handler for User Selecting a Get Set
$("#select_gene_set").change(function() {
geneSetSelected();
});
// Set up Event Handler for View/Hide JSON Debug Information
$("#json_cancer_studies").click(function(event) {
event.preventDefault();
$('#cancer_results').toggle();
});
// Set up an Event Handler to intercept form submission
$("#main_form").submit(chooseAction);
// Set up an Event Handler for the Query / Data Download Tabs
$("#query_tab").click(function(event) {
event.preventDefault();
userClickedMainTab("tab_visualize")
});
$("#download_tab").click(function(event) {
event.preventDefault();
userClickedMainTab("tab_download");
});
// Set up custom case set related GUI & event handlers (step 3)
initCustomCaseSetUI();
// set toggle Step 5: Optional arguments
//$("#optional_args").hide();
/*$("#step5_toggle").click(function(event) {
event.preventDefault();
$("#optional_args").toggle( "blind" );
});*/
$('.netsize_help').tipTip();
$('#step5 > .step_header').click(function(){
$(".ui-icon", this).toggle();
$("#optional_args").toggle();
});
// unset cookie for results tabs, so that a new query
// always goes to summary tab first
$.cookie("results-tab",null);
}); // end document ready function
function supportsHTML5Storage() {
// from diveintohtml5.info/storage.html
try {
return 'localStorage' in window && window['localStorage'] !== null;
} catch (e) {
return false;
}
}
// Load study Meta Data, i.e. everything except the name, which we load earlier to
// populate the dropdown menu.
function loadStudyMetaData(cancerStudyId) {
console.log("loadStudyMetaData ("+cancerStudyId+")");
$('.main_query_panel').fadeTo("fast",0.6);
$.getJSON("portal_meta_data.json?study_id="+cancerStudyId, function(json){
window.metaDataJson.cancer_studies[cancerStudyId] = json;
updateCancerStudyInformation();
$('.main_query_panel').stop().fadeTo("fast",1);
});
}
// Load geneset gene list
function loadGeneList(geneSetId) {
$('.main_query_panel').fadeTo("fast",0.6);
$.getJSON("portal_meta_data.json?geneset_id="+geneSetId.replace(/\//g,""), function(json){
window.metaDataJson.gene_sets[geneSetId].gene_list = json.list;
$("#gene_list").val(json.list);
$('.main_query_panel').stop().fadeTo("fast",1);
});
}
// Load Portal JSON Meta Data, while showing loader image
function loadMetaData() {
$('#load').remove();
// show ajax loader image; loader is background image of div 'load' as set in css
$('.main_query_panel').append('<div id="load"> </div>');
$('#load').fadeIn('slow');
// hide the main query form until all meta data is loaded and added to page
$('#main_query_form').hide('fast',loadContent);
function loadContent() {
// Get Portal JSON Meta Data via JQuery AJAX
window.metaDataPromise = $.Deferred();
jQuery.getJSON("portal_meta_data.json?partial_studies=true&partial_genesets=true",function(json){
// Store JSON Data in global variable for later use
window.metaDataJson = json;
window.metaDataPromise.resolve(json);
// Load data of selected study right at the outset before continuing
$.getJSON("portal_meta_data.json?study_id="+window.cancer_study_id_selected, function(json) {
console.log("Loading metadata for "+window.cancer_study_id_selected);
// this code should be about the same as in loadStudyMetaData
window.metaDataJson.cancer_studies[window.cancer_study_id_selected] = json;
// Add Meta Data to current page
addMetaDataToPage();
showNewContent();
});
});
}
function showNewContent() {
//show content, hide loader only after content is shown
$('#main_query_form').fadeIn('fast', hideLoader);
}
function hideLoader() {
//hide loader image
$('#load').fadeOut('fast',removeLoader());
}
function removeLoader() {
// remove loader image so that it will not appear in the
// modify-query section on results page
$('#load').remove();
}
}
// Triggered when the User Selects one of the Main Query or Download Tabs
function userClickedMainTab(tabAction) {
window.changingTabs = true;
// Change hidden field value
$("#tab_index").val(tabAction);
// Then, submit the form
$("#main_form").submit();
}
// When the page is first loaded, the default query will be a cross-cancer type
// search in which the user will enter ONLY a gene list; Also when "All Cancer Studies"
// is selected in Step 1
function crossCancerStudySelected() {
$('#step2').hide();
$('#step2cross').show();
$('#step3').hide();
$('#step5').hide();
}
// Display extra steps when an individual cancer study is selected
function singleCancerStudySelected() {
$("#step2").show();
$('#step2cross').hide();
$("#step3").show();
//$("#step5").show();
}
// Select default genomic profiles
function makeDefaultSelections(){
$('.' + PROFILE_MUTATION_EXTENDED).prop('checked',true);
$('.' + PROFILE_COPY_NUMBER_ALTERATION +':checkbox').prop('checked',true);
$('.' + PROFILE_COPY_NUMBER_ALTERATION +':radio').first().prop('checked',true);
}
// Triggered after meta data is added to page in case page is
// re-drawn after query error and also any time a new cancer
// type is selected; Assesses the need for default selections
// and sets the visibility of each step based on current selections
function reviewCurrentSelections(){
//HACK TO DEAL WITH ASYNCHRONOUS STUFF SO WE DONT DO THIS UNTIL AFTER METADATA ADDED
if (window.metaDataAdded === true) {
// Unless the download tab has been chosen or 'All Cancer Studies' is
// selected, iterate through checkboxes to see if any are selected; if not,
// make default selections
if (window.tab_index !== "tab_download" && $("#select_single_study").val() !== 'all'){
var setDefaults = true;
// if no checkboxes are checked, make default selections
$('#genomic_profiles input:checkbox').each(function(){
if ($(this).prop('checked')){
setDefaults = false;
return;
}
});
if (setDefaults){
console.log("reviewCurrentSelections ( makeDefaultSelections() )");
makeDefaultSelections();
}
}
updateDefaultCaseList();
// determine whether mRNA threshold field should be shown or hidden
// based on which, if any mRNA profiles are selected
toggleThresholdPanel($("." + PROFILE_MRNA_EXPRESSION+"[type=checkbox]"), PROFILE_MRNA_EXPRESSION, "#z_score_threshold");
// similarly with RPPA
toggleThresholdPanel($("." + PROFILE_RPPA+"[type=checkbox]"), PROFILE_RPPA, "#rppa_score_threshold");
// determine whether optional arguments section should be shown or hidden
// if ($("#optional_args > input").length >= 1){
// $("#optional_args > input").each(function(){
// if ($(this).prop('checked')){
// // hide/show is ugly, but not sure exactly how toggle works
// // and couldn't get it to work.. this will do for now
// $("#step5 > .step_header > .ui-icon-triangle-1-e").hide();
// $("#step5 > .step_header > .ui-icon-triangle-1-s").show();
// $("#optional_args").toggle();
// return;
// }
// });
// }
}
}
// Determine whether to submit a cross-cancer query or
// a study-specific query
function chooseAction(evt) {
var haveExpInQuery = $("#gene_list").val().toUpperCase().search("EXP") > -1;
$("#error_box").remove();
var selected_studies = $("#jstree").jstree(true).get_selected_leaves();
while (selected_studies.length === 0 && !window.changingTabs) {
// select all by default
$("#jstree").jstree(true).select_node(window.jstree_root_id);
selected_studies = $("#jstree").jstree(true).get_selected_leaves()
}
if (selected_studies.length > 1) {
$("#main_form").find("#select_multiple_studies").val("");
if ($("#tab_index").val() == 'tab_download') {
$("#main_form").get(0).setAttribute('action','index.do');
}
else {
var dataPriority = $('#main_form').find('input[name=data_priority]:checked').val();
var newSearch = $('#main_form').serialize() + '&Action=Submit#crosscancer/overview/'+dataPriority+'/'+encodeURIComponent($('#gene_list').val())+'/'+encodeURIComponent(selected_studies.join(","));
evt.preventDefault();
window.location = 'cross_cancer.do?' + newSearch;
//$("#main_form").get(0).setAttribute('action','cross_cancer.do');
}
if ( haveExpInQuery ) {
createAnError("Expression filtering in the gene list is not supported when doing cross cancer queries.", $('#gene_list'));
evt.preventDefault();
}
} else if (selected_studies.length === 1) {
$("#main_form").find("#select_single_study").val(selected_studies[0]);
$("#main_form").get(0).setAttribute('action','index.do');
if ( haveExpInQuery ) {
var expCheckBox = $("." + PROFILE_MRNA_EXPRESSION);
if( expCheckBox.length > 0 && expCheckBox.prop('checked') == false) {
createAnError("Expression specified in the list of genes, but not selected in the" +
" Genetic Profile Checkboxes.", $('#gene_list'));
evt.preventDefault();
} else if( expCheckBox.length == 0 ) {
createAnError("Expression specified in the list of genes, but not selected in the" +
" Genetic Profile Checkboxes.", $('#gene_list'));
evt.preventDefault();
}
}
}
}
function createAnError(errorText, targetElt) {
var errorBox = $("<div id='error_box'>").addClass("ui-state-error ui-corner-all exp_error_box");
var errorButton = $("<span>").addClass("ui-icon ui-icon-alert exp_error_button");
var strongErrorText = $("<small>").html("Error: " + errorText + "<br>");
var errorTextBox = $("<span>").addClass("exp_error_text");
errorButton.appendTo(errorBox);
strongErrorText.appendTo(errorTextBox);
errorTextBox.appendTo(errorBox);
errorBox.insertBefore(targetElt);
errorBox.slideDown();
}
// Triggered when a genomic profile radio button is selected
function genomicProfileRadioButtonSelected(subgroupClicked) {
var subgroupClass = subgroupClicked.attr('class');
if (subgroupClass != undefined && subgroupClass != "") {
var checkboxSelector = "input."+subgroupClass+"[type=checkbox]";
if (checkboxSelector != undefined) {
$(checkboxSelector).prop('checked',true);
}
}
updateDefaultCaseList();
}
// Triggered when a genomic profile group check box is selected.
function profileGroupCheckBoxSelected(profileGroup) {
var profileClass = profileGroup.attr('class');
$("input."+profileClass+"[type=radio]").prop('checked',false);
if (profileGroup.prop('checked')) {
var rnaSeqRadios = $("input."+profileClass+"[type=radio][value*='rna_seq']");
if (rnaSeqRadios.length>0) {
rnaSeqRadios.first().prop('checked',true);
} else {
$("input."+profileClass+"[type=radio]").first().prop('checked',true);
}
}
updateDefaultCaseList();
}
// update default case list based on selected profiles
function updateDefaultCaseList() {
if (caseSetSelectionOverriddenByUser) return;
var mutSelect = $("input.PROFILE_MUTATION_EXTENDED[type=checkbox]").prop('checked');
var cnaSelect = $("input.PROFILE_COPY_NUMBER_ALTERATION[type=checkbox]").prop('checked');
var expSelect = $("input.PROFILE_MRNA_EXPRESSION[type=checkbox]").prop('checked');
var rppaSelect = $("input.PROFILE_RPPA[type=checkbox]").prop('checked');
var selectedCancerStudy = $('#select_single_study').val();
var defaultCaseList = selectedCancerStudy+"_all";
if (mutSelect && cnaSelect && !expSelect && !rppaSelect) {
defaultCaseList = selectedCancerStudy+"_cnaseq";
if ($("#select_case_set option[value='"+defaultCaseList+"']").length == 0) {
defaultCaseList = selectedCancerStudy+"_cna_seq"; //TODO: Better to unify to this one
}
} else if (mutSelect && !cnaSelect && !expSelect && !rppaSelect) {
defaultCaseList = selectedCancerStudy+"_sequenced";
} else if (!mutSelect && cnaSelect && !expSelect && !rppaSelect) {
defaultCaseList = selectedCancerStudy+"_acgh";
} else if (!mutSelect && !cnaSelect && expSelect && !rppaSelect) {
if ($('#'+selectedCancerStudy+'_mrna_median_Zscores').prop('checked')) {
defaultCaseList = selectedCancerStudy+"_mrna";
} else if ($('#'+selectedCancerStudy+'_rna_seq_mrna_median_Zscores').prop('checked')) {
defaultCaseList = selectedCancerStudy+"_rna_seq_mrna";
} else if ($('#'+selectedCancerStudy+'_rna_seq_v2_mrna_median_Zscores').prop('checked')) {
defaultCaseList = selectedCancerStudy+"_rna_seq_v2_mrna";
}
} else if ((mutSelect || cnaSelect) && expSelect && !rppaSelect) {
defaultCaseList = selectedCancerStudy+"_3way_complete";
} else if (!mutSelect && !cnaSelect && !expSelect && rppaSelect) {
defaultCaseList = selectedCancerStudy+"_rppa";
}
$('#select_case_set').val(defaultCaseList);
// HACKY CODE START -- TO SOLVE THE PROBLEM THAT WE HAVE BOTH _complete and _3way_complete
if (!$('#select_case_set').val()) {
if (defaultCaseList===selectedCancerStudy+"_3way_complete") {
$('#select_case_set').val(selectedCancerStudy+"_complete");
}
}// HACKY CODE END
if (!$('#select_case_set').val()) {
// in case no match
$('#select_case_set').val(selectedCancerStudy+"_all");
}
updateCaseListSmart();
}
// Print message and disable submit if use choosed a cancer type
// for which no genomic profiles are available
function genomicProfilesUnavailable(){
$("#genomic_profiles").html("<strong>No Genomic Profiles available for this Cancer Study</strong>");
$('#main_submit').attr('disabled',true);
}
// Show or hide mRNA threshold field based on mRNA profile selected
function toggleThresholdPanel(profileClicked, profile, threshold_div) {
var selectedProfile = profileClicked.val();
var inputType = profileClicked.attr('type');
// when a radio button is clicked, show threshold input unless user chooses expression outliers
if(inputType == 'radio'){
if(selectedProfile.indexOf("outlier")==-1){
$(threshold_div).slideDown();
} else {
$(threshold_div).slideUp();
}
} else if(inputType == 'checkbox'){
// if there are NO subgroups, show threshold input when mRNA checkbox is selected.
if (profileClicked.prop('checked')){
$(threshold_div).slideDown();
}
// if checkbox is unselected, hide threshold input regardless of whether there are subgroups
else {
$(threshold_div).slideUp();
}
}
}
// toggle:
// gistic button
// mutsig button
// according to the cancer_study
function toggleByCancerStudy(cancer_study) {
var mutsig = $('#toggle_mutsig_dialog');
var gistic = $('#toggle_gistic_dialog_button');
if (cancer_study.has_mutsig_data) {
mutsig.show();
} else {
mutsig.hide();
}
if (cancer_study.has_gistic_data) {
gistic.show();
} else {
gistic.hide();
}
}
function updateCaseListSmart() {
$("#select_case_set").trigger("liszt:updated");
$("#select_case_set_chzn .chzn-drop ul.chzn-results li")
.each(function(i, e) {
$(e).qtip({
content: "<font size='2'>" + $($("#select_case_set option")[i]).attr("title") + "</font>",
style: {
classes: 'qtip-light qtip-rounded qtip-shadow qtip-lightyellow'
},
position: {
my: 'left middle',
at: 'middle right',
viewport: $(window)
},
show: "mouseover",
hide: "mouseout"
});
}
);
}
// Called when and only when a cancer study is selected from the dropdown menu
function updateCancerStudyInformation() {
var cancerStudyId = $("#main_form").find("#select_single_study").val();
var cancer_study = window.metaDataJson.cancer_studies[cancerStudyId];
// toggle every time a new cancer study is selected
toggleByCancerStudy(cancer_study);
if (cancerStudyId=='all'){
crossCancerStudySelected();
return;
}
// Update Cancer Study Description
var citation = cancer_study.citation;
if (!citation) {
citation="";
}
else {
var pmid = cancer_study.pmid;
if (pmid) {
citation = " <a href='http://www.ncbi.nlm.nih.gov/pubmed/"+pmid+"'>"+citation+"</a>";
}
}
// Iterate through all genomic profiles
// Add all non-expression profiles where show_in_analysis_tab = true
// First, clear all existing options
$("#genomic_profiles").html("");
// Add Genomic Profiles, in this order
addGenomicProfiles(cancer_study.genomic_profiles, "MUTATION", PROFILE_MUTATION, "Mutation");
addGenomicProfiles(cancer_study.genomic_profiles, "MUTATION_EXTENDED", PROFILE_MUTATION_EXTENDED, "Mutation");
addGenomicProfiles(cancer_study.genomic_profiles, "COPY_NUMBER_ALTERATION", PROFILE_COPY_NUMBER_ALTERATION, "Copy Number");
addGenomicProfiles(cancer_study.genomic_profiles, "MRNA_EXPRESSION", PROFILE_MRNA_EXPRESSION, "mRNA Expression");
addGenomicProfiles(cancer_study.genomic_profiles, "METHYLATION", PROFILE_METHYLATION, "DNA Methylation");
addGenomicProfiles(cancer_study.genomic_profiles, "METHYLATION_BINARY", PROFILE_METHYLATION, "DNA Methylation");
//addGenomicProfiles(cancer_study.genomic_profiles, "PROTEIN_LEVEL", PROFILE_PROTEIN, "Protein Level");
addGenomicProfiles(cancer_study.genomic_profiles, "PROTEIN_ARRAY_PROTEIN_LEVEL", PROFILE_RPPA, "Protein/phosphoprotein level (by RPPA)");
// if no genomic profiles available, set message and disable submit button
if ($("#genomic_profiles").html()==""){
console.log("cancerStudySelected ( genomicProfilesUnavailable() )");
genomicProfilesUnavailable();
}
// Update the Case Set Pull-Down Menu
// First, clear all existing pull-down menus
$("#select_case_set").html("");
// Iterate through all case sets
// Add each case set as an option, and include description as title, so that it appears
// as a tool-tip.
jQuery.each(cancer_study.case_sets,function(i, case_set) {
$("#select_case_set").append("<option class='case_set_option' value='"
+ case_set.id + "' title='"
+ case_set.description + "'>" + case_set.name + " ("+ case_set.size +")" + "</option>");
}); // end for each case study loop
// Add the user-defined case list option
$("#select_case_set").append("<option class='case_set_option' value='-1' "
+ "title='Specify you own case list'>User-defined Case List</option>");
updateCaseListSmart();
// Set up Tip-Tip Event Handler for Case Set Pull-Down Menu
// commented out for now, as this did not work in Chrome or Safari
// $(".case_set_option").tipTip({defaultPosition: "right", delay:"100", edgeOffset: 25});
// Set up Tip-Tip Event Handler for Genomic Profiles help
$(".profile_help").tipTip({defaultPosition: "right", delay:"100", edgeOffset: 25});
// Set up Event Handler for user selecting a genomic profile radio button
$("input[type='radio'][name*='genetic_profile_']").click(function(){
genomicProfileRadioButtonSelected($(this));
});
// Set up an Event Handler for user selecting a genomic profile checkbox
$("input[type='checkbox'][class*='PROFILE_']").click(function(){
profileGroupCheckBoxSelected($(this));
});
// Set up an Event Handler for showing/hiding mRNA threshold input
$("." + PROFILE_MRNA_EXPRESSION).click(function(){
toggleThresholdPanel($(this), PROFILE_MRNA_EXPRESSION, "#z_score_threshold");
});
// Set up an Event Handler for showing/hiding RPPA threshold input
$("." + PROFILE_RPPA).click(function(){
toggleThresholdPanel($(this), PROFILE_RPPA, "#rppa_score_threshold");
});
// Set default selections and make sure all steps are visible
console.log("cancerStudySelected ( singleCancerStudySelected() )");
singleCancerStudySelected();
console.log("cancerStudySelected ( reviewCurrentSelections() )");
reviewCurrentSelections();
// check if cancer study has a clinical_free_form data to filter,
// if there is data to filter, then enable "build custom case set" link,
// otherwise disable the button
jQuery.getJSON("ClinicalFreeForm.json",
{studyId: $("#select_single_study").val()},
function(json){
var noDataToFilter = false;
if (json.freeFormData.length == 0)
{
noDataToFilter = true;
}
else
{
noDataToFilter = true;
var categorySet = json.categoryMap;
// check if there is at least one category to filter
for (var category in categorySet)
{
// continue if the category is qualified as a filter parameter
if (isEligibleForFiltering(categorySet[category]))
{
noDataToFilter = false;
break;
}
}
}
if (noDataToFilter)
{
// no clinical_free_form data to filter for the current
// cancer study, so disable the button
$("#build_custom_case_set").hide();
}
else
{
$("#build_custom_case_set").tipTip({defaultPosition: "right",
delay:"100",
edgeOffset: 10,
maxWidth: 100});
$("#build_custom_case_set").hide();//.show(); temporarily disabled build case list
}
});
}
// Triggered when a cancer study has been selected, either by the user
// or programatically.
function cancerStudySelected() {
// make sure submit button is enabled unless determined otherwise by lack of data
$("#main_submit").attr("disabled",false);
var cancerStudyId = $("#select_single_study").val() || "all";
if (window.metaDataJson.cancer_studies[cancerStudyId].partial==="true") {
console.log("cancerStudySelected( loadStudyMetaData )");
loadStudyMetaData(cancerStudyId);
} else {
updateCancerStudyInformation();
}
}
// Triggered when a case set has been selected, either by the user
// or programatically.
function caseSetSelected() {
var caseSetId = $("#select_case_set").val();
// If user has selected the user-defined option, show the case list div
// Otherwise, make sure to hide it.
if (caseSetId == "-1") {
$("#custom_case_list_section").show();
// if custom case list was selected, post to avoid long url problem.
$("#main_form").attr("method","post");
} else {
$("#custom_case_list_section").hide();
$("#main_form").attr("method","get");
}
}
// Triggered when a gene set has been selected, either by the user
// or programatically.
function geneSetSelected() {
// Get the selected ID from the pull-down menu
var geneSetId = $("#select_gene_set").val();
if (window.metaDataJson.gene_sets[geneSetId].gene_list == "") {
loadGeneList(geneSetId);
} else {
// Get the gene set meta data from global JSON variable
var gene_set = window.metaDataJson.gene_sets[geneSetId];
// Set the gene list text area
$("#gene_list").val(gene_set.gene_list);
}
}
// Adds Meta Data to the Page.
// Tiggered at the end of successful AJAX/JSON request.
function addMetaDataToPage() {
console.log("Adding Meta Data to Query Form");
json = window.metaDataJson;
// Construct oncotree
var oncotree = {'tissue':{code:'tissue', studies:[], children:[], parent: false, desc_studies_count:0, tissue:''}};
var parents = json.parent_type_of_cancers;
// First add everything to the tree
for (var tumortype in parents) {
if (parents.hasOwnProperty(tumortype)) {
oncotree[tumortype] = {code:tumortype, studies:[], children:[], parent: false, desc_studies_count: 0, tissue: false};
}
}
// Link parents and insert initial tissue info
for (var tumortype in oncotree) {
if (oncotree.hasOwnProperty(tumortype) && tumortype !== 'tissue') {
oncotree[tumortype].parent = oncotree[parents[tumortype]];
oncotree[tumortype].parent.children.push(oncotree[tumortype]);
if (parents[tumortype] === "tissue") {
oncotree[tumortype].tissue = tumortype;
}
}
}
// Insert tissue information in a "union-find" type way
for (var elt in oncotree) {
if (oncotree.hasOwnProperty(elt) && elt !== 'tissue') {
var to_modify = [];
var currelt = oncotree[elt];
while (!currelt.tissue && currelt.code !== 'tissue') {
to_modify.push(currelt);
currelt = currelt.parent;
}
for (var i=0; i<to_modify.length; i++) {
to_modify[i].tissue = currelt.tissue;
}
}
}
// Add studies to tree, and climb up adding one to each level's descendant studies
// DMP hack
var dmp_studies = [];
for (var study in json.cancer_studies) {
if (study.indexOf("mskimpact") !== -1) {
// DMP hack
dmp_studies.push(study);
} else if (json.cancer_studies.hasOwnProperty(study) && study !== 'all') { // don't re-add 'all'
try {
var code = json.cancer_studies[study].type_of_cancer.toLowerCase();
var lineage = [];
var currCode = code;
while (currCode !== 'tissue') {
lineage.push(currCode);
currCode = oncotree[currCode].parent.code;
}
oncotree[code].studies.push({id:study, lineage:lineage});
var node = oncotree[code];
while (node) {
node.desc_studies_count += 1;
node = node.parent;
}
} catch (err) {
console.log("Unable to add study");
console.log(json.cancer_studies[study]);
}
}
}
// Sort dmp by number if there is one in the name
dmp_studies.sort(function(a,b) {
var matchA = a.match(/\d+/);
var matchB = b.match(/\d+/);
var numberA = (matchA === null ? NaN : parseInt(a.match(/\d+/)[0], 10));
var numberB = (matchB === null ? NaN : parseInt(b.match(/\d+/)[0], 10));
if (isNaN(numberA) && isNaN(numberB)) {
return a.localeCompare(b);
} else if (isNaN(numberA)) {
return -1;
} else if (isNaN(numberB)) {
return 1;
} else {
return numberA-numberB;
}
});
dmp_studies.reverse();
// Sort all the children alphabetically
for (var node in oncotree) {
if (oncotree.hasOwnProperty(node)) {
oncotree[node].children.sort(function(a,b) {
try {
return json.type_of_cancers[a.code].localeCompare(json.type_of_cancers[b.code]);
} catch(err) {
return a.code.localeCompare(b.code);
}
});
oncotree[node].studies.sort(function(a,b) {
return a.id.localeCompare(b.id);
});
}
}
var splitAndCapitalize = function(s) {
return s.split("_").map(function(x) { return (x.length > 0 ? x[0].toUpperCase()+x.slice(1) : x);}).join(" ");
};
var truncateStudyName = function(n) {
var maxLength = 80;
if (n.length < maxLength) {
return n;
} else {
var suffix = '';
var suffixStart = n.indexOf('(');
if (suffixStart !== -1) {
suffix = n.slice(suffixStart);
}
var ellipsis = '... ';
return n.slice(0,maxLength-suffix.length-ellipsis.length)+ellipsis+suffix;
}
};
window.jstree_root_id = 'tissue';
var jstree_data = [];
var flat_jstree_data = [];
jstree_data.push({'id':jstree_root_id, parent:'#', text:'All', state:{opened:true}, li_attr:{name:'All'}});
flat_jstree_data.push({'id':jstree_root_id, parent:'#', text:'All', state:{opened:true}, li_attr:{name:'All'}});
var node_queue = [].concat(oncotree['tissue'].children);
var currNode;
if (dmp_studies.length > 0) {
jstree_data.push({'id':'mskimpact-study-group', 'parent':jstree_root_id, 'text':'MSKCC DMP', 'li_attr':{name:'MSKCC DMP'}});
var studyName;
$.each(dmp_studies, function(ind, id) {
studyName = truncateStudyName(json.cancer_studies[id].name);
jstree_data.push({'id':id, 'parent':'mskimpact-study-group', 'text':studyName,
'li_attr':{name: studyName, description: metaDataJson.cancer_studies[id].description}});
flat_jstree_data.push({'id':id, 'parent':jstree_root_id, 'text':truncateStudyName(json.cancer_studies[id].name),
'li_attr':{name: studyName, description: metaDataJson.cancer_studies[id].description, search_terms: 'MSKCC DMP'}});
});
}
while (node_queue.length > 0) {
currNode = node_queue.shift();
if (currNode.desc_studies_count > 0) {
var name = splitAndCapitalize(metaDataJson.type_of_cancers[currNode.code] || currNode.code);
jstree_data.push({'id':currNode.code,
'parent':((currNode.parent && currNode.parent.code) || '#'),
'text':name,
'li_attr':{name:name}
});
$.each(currNode.studies, function(ind, elt) {
name = truncateStudyName(splitAndCapitalize(metaDataJson.cancer_studies[elt.id].name));
jstree_data.push({'id':elt.id,
'parent':currNode.code,
'text':name,
'li_attr':{name: name, description:metaDataJson.cancer_studies[elt.id].description}});
flat_jstree_data.push({'id':elt.id,
'parent':jstree_root_id,
'text':name,
'li_attr':{name: name, description:metaDataJson.cancer_studies[elt.id].description, search_terms: elt.lineage.join(" ")}});
});
node_queue = node_queue.concat(currNode.children);
}
}
var precomputed_search = {query: '', results: {}};
var parse_search_query = function(query) {
// First eliminate trailing whitespace and reduce every whitespace
// to a single space.
query = query.toLowerCase().trim().split(/\s+/g).join(' ');
// Now factor out quotation marks and inter-token spaces
var phrases = [];
var currInd = 0;
var nextSpace, nextQuote;
while (currInd < query.length) {
if (query[currInd] === '"') {
nextQuote = query.indexOf('"', currInd+1);
if (nextQuote === -1) {
phrases.push(query.substring(currInd + 1));
currInd = query.length;
} else {
phrases.push(query.substring(currInd + 1, nextQuote));
currInd = nextQuote + 1;
}
} else if (query[currInd] === ' ') {
currInd += 1;
} else if (query[currInd] === '-') {
phrases.push('-');
currInd += 1;
} else {
nextSpace = query.indexOf(' ', currInd);
if (nextSpace === -1) {
phrases.push(query.substring(currInd));
currInd = query.length;
} else {
phrases.push(query.substring(currInd, nextSpace));
currInd = nextSpace + 1;
}
}
}
// Now get the conjunctive clauses, and the negative clauses
var clauses = [];
currInd = 0;
var nextOr, nextDash;
while (currInd < phrases.length) {
if (phrases[currInd] === '-') {
if (currInd < phrases.length - 1) {
clauses.push({"type":"not", "data":phrases[currInd+1]});
}
currInd = currInd + 2;
} else {
nextOr = phrases.indexOf('or', currInd);
nextDash = phrases.indexOf('-', currInd);
if (nextOr === -1 && nextDash === -1) {
clauses.push({"type":"and","data":phrases.slice(currInd)});
currInd = phrases.length;
} else if (nextOr === -1 && nextDash > 0) {
clauses.push({"type":"and", "data":phrases.slice(currInd, nextDash)});
currInd = nextDash;
} else if (nextOr > 0 && nextDash === -1) {
clauses.push({"type":"and", "data":phrases.slice(currInd, nextOr)});
currInd = nextOr + 1;
} else {
if (nextOr < nextDash) {
clauses.push({"type":"and", "data":phrases.slice(currInd, nextOr)});
currInd = nextOr + 1;
} else {
clauses.push({"type":"and", "data":phrases.slice(currInd, nextDash)});
currInd = nextDash;
}
}
}
}
return clauses;
};
var matchPhrase = function(phrase, node) {
phrase = phrase.toLowerCase();
return !!((node.li_attr && node.li_attr.name && node.li_attr.name.toLowerCase().indexOf(phrase) > -1)
|| (node.li_attr && node.li_attr.description && node.li_attr.description.toLowerCase().indexOf(phrase) > -1)
|| (node.li_attr && node.li_attr.search_terms && node.li_attr.search_terms.toLowerCase().indexOf(phrase) > -1));
};
var perform_search_single = function(parsed_query, node) {
// in: a jstree node
// text to search is node.text and node.li_attr.description and node.li_attr.search_terms
// return true iff the query, considering quotation marks, 'and' and 'or' logic, matches
var match = false;
var hasPositiveClauseType = false;
var forced = false;
$.each(parsed_query, function(ind, clause) {
if (clause.type !== 'not') {
hasPositiveClauseType = true;
return 0;
}
});
if (!hasPositiveClauseType) {
// if only negative clauses, match by default
match = true;
}
$.each(parsed_query, function(ind, clause) {
if (clause.type === 'not') {
if (matchPhrase(clause.data, node)) {
match = false;
forced = true;
return 0;
}
} else if (clause.type === 'and') {
hasPositiveClauseType = true;
var clauseMatch = true;
$.each(clause.data, function(ind2, phrase) {
clauseMatch = clauseMatch && matchPhrase(phrase, node);
});
match = match || clauseMatch;
}
});
return {result:match, forced:forced};
};
var perform_search = function(query) {
// IN: query, a string
// void method
// when this ends, the object precomputed_search has been updated
// so that results[node.id] = true iff the query directly matches it
var parsed_query = parse_search_query(query);
$.each($('#jstree').jstree(true)._model.data, function(key, node) {
precomputed_search.results[node.id] = perform_search_single(parsed_query, node);
});
precomputed_search.query = query;
};
var jstree_search = function(query, node) {
if (query === "") {
return true;
}
if (precomputed_search.query !== query) {
perform_search(query);
}
if (!precomputed_search.results[node.id].result && precomputed_search.results[node.id].forced) {
return false;
}
var nodes_to_consider = [node.id].concat(node.parents.slice());
var ret = false;
$.each(nodes_to_consider, function(ind, elt) {
if (elt === jstree_root_id || elt === '#') {
return 0;
}
if (!precomputed_search.results[elt].result && precomputed_search.results[elt].forced) {
ret = false;
return 0;
}
ret = ret || precomputed_search.results[elt].result;
});
return ret;
};
var initialize_jstree = function (data) {
console.log("Initializing jstree");
$("#jstree").jstree({
"themes": {
"theme": "default",
"dots": false,
"icons": false,
"url": "../../css/jstree.style.css"
},
"plugins": ['checkbox','search'],
"search": {'show_only_matches': true,
'search_callback': jstree_search,
'search_leaves_only': true},
"checkbox": {},
'core': {'data': data, 'check_callback': true, 'dblclick_toggle': false, 'multiple': (window.tab_index !== "tab_download")}
});
$('#jstree').on('ready.jstree', function () {
$('#jstree').jstree(true).num_leaves = $('#jstree').jstree(true).get_leaves().length;
$('#jstree').jstree(true).get_matching_nodes = function (phrase) {
var ret = [];
$.each($('#jstree').jstree(true)._model.data, function (key, node) {
if (matchPhrase(phrase, node)) {
ret.push(key);
}
});
return ret;
};
$('#jstree').jstree(true).get_node(jstree_root_id, true).children('.jstree-anchor').after($jstree_flatten_btn());
$('#jstree').jstree(true).open_all();
});
$('#jstree').on('changed.jstree', function() { onJSTreeChange(); /*saveSelectedStudiesLocalStorage();*/ });
$('#jstree').jstree(true).hide_icons();
}
initialize_jstree(window.tab_index === "tab_download" ? flat_jstree_data : jstree_data);
var jstree_is_flat = false;
var $jstree_flatten_btn = (function() {
if (window.tab_index === "tab_download") {
return false;
}
var ret = $('<i class="fa fa-lg fa-code-fork jstree-external-node-decorator" style="display:none; cursor:pointer; padding-left:0.6em"></i>');
ret.mouseenter(function () {
ret.fadeTo('fast', 0.7);
});
ret.mouseleave(function () {
ret.fadeTo('fast', 1);
});
ret.click(function () {
var selected_studies = $("#jstree").jstree(true).get_selected_leaves();
$('#jstree').jstree(true).destroy();
jstree_is_flat = !jstree_is_flat;
initialize_jstree((jstree_is_flat ? flat_jstree_data : jstree_data));
$('#jstree').on('ready.jstree', function () {
$('#jstree').jstree(true).select_node(selected_studies);
if ($("#jstree_search_input").val() !== "") {
precomputed_search.query = false; // force re-search
do_jstree_search();
}
});
});
ret.qtip({
content: {text: (jstree_is_flat ? "Unflatten tree" : "Flatten tree")},
style: {classes: 'qtip-light qtip-rounded'},
position: {my: 'bottom center', at: 'top center', viewport: $(window)},
show: {delay: 600},
hide: {delay: 10, fixed: true},
});
return ret;
});
var do_jstree_search = function() {
$("#jstree").jstree(true).search($("#jstree_search_input").val());
$('#jstree').jstree(true).get_node(jstree_root_id, true).children('.jstree-anchor').after($jstree_flatten_btn());
}
var jstree_search_timeout = null;
$("#jstree_search_input").on('input', function () {
if (jstree_search_timeout) {
clearTimeout(jstree_search_timeout);
}
jstree_search_timeout = setTimeout(function () {
if ($("#jstree_search_input").val() === "") {
$("#step_header_first_line_empty_search").css("display", "none");
$("#jstree").jstree(true)._model.data['tissue'].li_attr.name = "All";
} else {
$("#step_header_first_line_empty_search").css("display", "block");
$("#jstree").jstree(true)._model.data['tissue'].li_attr.name = "All Search Results";
}
$("#jstree").fadeTo(100, 0.5, function () {
$('#jstree_search_none_found_msg').hide();
do_jstree_search();
if ($('#jstree_search_input').val() !== "" && $('#jstree').jstree(true)._data.search.res.length === 0) {
$('#jstree_search_none_found_msg').show();
}
$("#jstree").fadeTo(100, 1);
});
}, 400); // wait for a bit with no typing before searching
});
$('#step_header_first_line_empty_search').click(function() {
$("#jstree_search_input").val("");
$("#step_header_first_line_empty_search").css("display", "none");
$("#jstree").fadeTo(100, 0.5, function () {
do_jstree_search();
$("#jstree").fadeTo(100, 1);
});
});
var saveSelectedStudiesLocalStorage = function() {
if (!supportsHTML5Storage()) {
return false;
}
var selected_studies = $("#jstree").jstree(true).get_selected_leaves();
// selectedStudiesStorageKey
window.localStorage.setItem(selectedStudiesStorageKey, selected_studies.join(","));
//$.removeCookie(selectedStudiesCookieName);
//$.cookie(selectedStudiesCookieName, selected_studies.join(","), {expires:10});
return true;
};
var getSelectedStudiesLocalStorage = function() {
if (!supportsHTML5Storage()) {
return false;
}
return window.localStorage.getItem(selectedStudiesStorageKey);
}
var onJSTreeChange = function () {
$("#error_box").remove();
var select_single_study = $("#main_form").find("#select_single_study");
var select_multiple_studies = $("#main_form").find("#select_multiple_studies");
var selected_studies = $("#jstree").jstree(true).get_selected_leaves();
var selected_ct = selected_studies.length;
$('#jstree_selected_study_count').html((selected_ct === 0 ? "No" : (selected_ct === $('#jstree').jstree(true).num_leaves ? "All" : selected_ct)) + " stud" + (selected_ct === 1 ? "y" : "ies") + " selected.");
$('#jstree_deselect_all_btn')[selected_ct > 0 ? 'show' : 'hide']();
var old_select_single_study_val = select_single_study.val();
if (selected_studies.length === 1) {
select_single_study.val(selected_studies[0]);
} else {
select_single_study.val("all");
}
select_multiple_studies.val(selected_studies.join(","));
if (select_single_study.val() !== old_select_single_study_val) {
select_single_study.trigger('change');
}
select_multiple_studies.trigger('change');
};
// Add Gene Sets to Pull-down Menu
jQuery.each(json.gene_sets,function(key,gene_set){
$("#select_gene_set").append("<option value='" + key + "'>"
+ gene_set.name + "</option>");
}); // end for each gene set loop
// Set the placeholder for the autocomplete select box
$("#example_gene_set").children("span:first").children("input:first")
.attr("placeholder", $("#select_gene_set").children("option:first").text());
// Set things up, based on currently selected cancer type
// hacky; order of preference
var selected_study_map = {};
if (!window.cancer_study_list_selected || window.cancer_study_list_selected === '') {
var windowParams = window.location.search.substring(1).split("&");
$.each(windowParams, function(ind, elt) {
var pair = elt.split("=");
if (pair[0] === window.cancer_study_list_param) {
window.cancer_study_list_selected = pair[1];
return 0;
}
});
}
if (!window.cancer_study_list_selected || window.cancer_study_list_selected === '') {
var split_url_on_hash = window.location.href.split('#');
if (split_url_on_hash.length > 1) {
window.cancer_study_list_selected = split_url_on_hash[1].split("/")[4];
}
}
if (!window.cancer_study_list_selected || window.cancer_study_list_selected === '') {
var windowParams = window.location.search.substring(1).split("&");
$.each(windowParams, function(ind, elt) {
var pair = elt.split("=");
if (pair[0] === 'cancer_study_id') {
window.cancer_study_list_selected = pair[1];
return 0;
}
});
}
//var selected_study_list = decodeURIComponent(window.selected_cancer_study_list || ( getSelectedStudiesLocalStorage() || '')).split(",");
var selected_study_list = (window.tab_index !== "tab_download" ? decodeURIComponent(window.cancer_study_list_selected || '').split(",") : []);
$.each(selected_study_list, function(ind, elt) {
if (elt !== '') {
selected_study_map[elt] = false;
}
});
if (window.cancer_study_id_selected !== 'all') {
selected_study_map[window.cancer_study_id_selected] = false;
}
jQuery.each(json.cancer_studies,function(key,cancer_study){
// Set Selected Cancer Type, Based on User Parameter
if (selected_study_map.hasOwnProperty(key)) {
selected_study_map[key] = true;
}
});
$("#jstree").on('ready.jstree', function() {
// Chosenize the select boxes
var minSearchableItems = 10;
$("#select_gene_set").chosen({ width: '620px', search_contains: true});
$("#select_case_set").chosen({ width: '420px', disable_search_threshold: minSearchableItems, search_contains: true });
$.each(selected_study_map, function(key, val) {
if (val) {
$("#jstree").jstree(true).select_node(key, true);
}
});
// Set things up, based on currently selected case set id
$('#select_single_study').one('doneChanging', function() {
if (window.case_set_id_selected != null && window.case_set_id_selected != "") {
$("#select_case_set").val(window.case_set_id_selected);
$("#select_case_set").trigger('liszt:updated');
caseSetSelectionOverriddenByUser = true;
}
caseSetSelected();
if (window.case_ids_selected !== '') {
$('#custom_case_set_ids').val(window.case_ids_selected);
}
// Set things up, based on currently selected gene set id
if (window.gene_set_id_selected != null && window.gene_set_id_selected != "") {
$("#select_gene_set").val(window.gene_set_id_selected);
} else {
$("#select_gene_set").val("user-defined-list");
}
$("#select_gene_set").trigger('liszt:updated');
// Set things up, based on all currently selected genomic profiles
// To do so, we iterate through all input elements with the name = 'genetic_profile_ids*'
$("input[name^=genetic_profile_ids]").each(function (index) {
// val() is the value that or stable ID of the genetic profile ID
var currentValue = $(this).val();
// if the user has this stable ID already selected, mark it as checked
if (window.genomic_profile_id_selected[currentValue] == 1) {
console.log("Checking " + $(this).attr('id') + "... (inside addMetaDataToPage())");
$(this).prop('checked', true);
// Select the surrounding checkbox
genomicProfileRadioButtonSelected($(this));
}
}); // end for each genomic profile option
// HACK TO DEAL WITH ASYNCHRONOUS STUFF
window.metaDataAdded = true;
// determine whether any selections have already been made
// to make sure all of the fields are shown/hidden as appropriate
console.log("addMetaDataToPage ( reviewCurrentSelections() )");
reviewCurrentSelections();
});
onJSTreeChange();
});
}
// Adds the specified genomic profiles to the page.
// Code checks for three possibilities:
// 1. 0 profiles of targetType --> show nothing
// 2. 1 profile of targetType --> show as checkbox
// 3. >1 profiles of targetType --> show group checkbox plus radio buttons
function addGenomicProfiles (genomic_profiles, targetAlterationType, targetClass, targetTitle) {
var numProfiles = 0;
var profileHtml = "";
var downloadTab = false;
// Determine whether we are in the download tab
if (window.tab_index == "tab_download") {
downloadTab = true;
}
// First count how many profiles match the targetAltertion type
jQuery.each(genomic_profiles,function(key, genomic_profile) {
if (genomic_profile.alteration_type == targetAlterationType) {
if (downloadTab || genomic_profile.show_in_analysis_tab == true) {
numProfiles++;
}
}
}); // end for each genomic profile loop
if (numProfiles == 0) {
return;
} else if(numProfiles >1 && downloadTab == false) {
// enable submit button
$('#main_submit').attr('disabled', false);
// If we have more than 1 profile, output group checkbox
// assign a class to associate the checkbox with any subgroups (radio buttons)
profileHtml += "<input type='checkbox' class='" + targetClass + "'>"
+ targetTitle + " data."
+ " Select one of the profiles below:";
profileHtml += "<div class='genomic_profiles_subgroup'>";
}
// Iterate through all genomic profiles
jQuery.each(genomic_profiles,function(key, genomic_profile) {
if (genomic_profile.alteration_type == targetAlterationType) {
if (downloadTab || genomic_profile.show_in_analysis_tab == true) {
// Branch depending on number of profiles
var optionType = "checkbox";
if (downloadTab) {
optionType = "radio";
} else {
if (numProfiles == 1) {
optionType = "checkbox";
} else if (numProfiles > 1) {
optionType = "radio";
}
}
profileHtml += outputGenomicProfileOption (downloadTab, optionType,
targetClass, genomic_profile.id, genomic_profile.name, genomic_profile.description);
}
}
}); // end for each genomic profile loop
if(numProfiles >1) {
// If we have more than 1 profile, output the end div tag
profileHtml += "</div>";
}
if(targetClass == PROFILE_MRNA_EXPRESSION && downloadTab == false){
var inputName = 'Z_SCORE_THRESHOLD';
profileHtml += "<div id='z_score_threshold' class='score_threshold'>Enter a z-score threshold ±: "
+ "<input type='text' name='" + inputName + "' size='6' value='"
+ window.zscore_threshold + "'>"
+ "</div>";
}
if(targetClass == PROFILE_RPPA && downloadTab == false){
var inputName = 'RPPA_SCORE_THRESHOLD';
profileHtml += "<div id='rppa_score_threshold' class='score_threshold'>Enter a RPPA z-score threshold ±: "
+ "<input type='text' name='" + inputName + "' size='6' value='"
+ window.rppa_score_threshold + "'>"
+ "</div>";
}
$("#genomic_profiles").append(profileHtml);
}
// Outputs a Single Genomic Profile Options
function outputGenomicProfileOption (downloadTab, optionType, targetClass, id, name,
description) {
// This following if/else requires some explanation.
// If we are in the download tab, all the input fields must use the same name.
// This enforces all inputs to work as a single group of radio buttons.
// If we are in the query tab, the input fields must be specified by alteration type.
// This enforces all the inputs of the same alteration type to work as a single group of radio
// buttons.
var paramName;
if (downloadTab) {
paramName = "genetic_profile_ids";
} else {
paramName = "genetic_profile_ids_" + targetClass;
}
var html = "<input type='" + optionType + "' "
+ "id='" + id + "'"
+ " name='" + paramName + "'"
+ " class='" + targetClass + "'"
+ " value='" + id +"'>" + ' ' + name + "</input>"
+ " <img class='profile_help' src='images/help.png' title='"
+ description + "'><br/>";
return html;
}
| portal/src/main/webapp/js/src/dynamicQuery.js | /*
* Copyright (c) 2015 Memorial Sloan-Kettering Cancer Center.
*
* 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. The software and documentation provided hereunder
* is on an "as is" basis, and Memorial Sloan-Kettering Cancer Center has no
* obligations to provide maintenance, support, updates, enhancements or
* modifications. In no event shall Memorial Sloan-Kettering Cancer Center be
* liable to any party for direct, indirect, special, incidental or
* consequential damages, including lost profits, arising out of the use of this
* software and its documentation, even if Memorial Sloan-Kettering Cancer
* Center has been advised of the possibility of such damage.
*/
/*
* This file is part of cBioPortal.
*
* cBioPortal is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/******************************************************************************************
* Dynamic Query Javascript, built with JQuery
* @author Ethan Cerami, Caitlin Byrne.
*
* This code performs the following functions:
*
* 1. Connects to the portal via AJAX and downloads a JSON document containing information
* regarding all cancer studies and gene sets stored in the CGDS.
* 2. Creates event handler for when user selects a cancer study. This triggers updates
in the genomic profiles and case lists displayed.
* 3. Creates event handler for when user selects a gene set. This triggers updates to the
gene set text area.
******************************************************************************************/
// Create Constants
var PROFILE_MUTATION = "PROFILE_MUTATION";
var PROFILE_MUTATION_EXTENDED = "PROFILE_MUTATION_EXTENDED";
var PROFILE_COPY_NUMBER_ALTERATION = "PROFILE_COPY_NUMBER_ALTERATION"
var PROFILE_MRNA_EXPRESSION = "PROFILE_MRNA_EXPRESSION";
var PROFILE_PROTEIN = "PROFILE_PROTEIN";
var PROFILE_RPPA = "PROFILE_RPPA";
var PROFILE_METHYLATION = "PROFILE_METHYLATION"
var caseSetSelectionOverriddenByUser = false;
var selectedStudiesStorageKey = "cbioportal_selected_studies";
// Create Log Function, if FireBug is not Installed.
if(typeof(console) === "undefined" || typeof(console.log) === "undefined")
var console = { log: function() { } };
// Triggered only when document is ready.
$(document).ready(function(){
// Load Portal JSON Meta Data while showing loader image in place of query form
loadMetaData();
// Set up Event Handler for User Selecting Cancer Study from Pull-Down Menu
$("#select_single_study").change(function() {
caseSetSelectionOverriddenByUser = false; // reset
console.log("#select_single_study change ( cancerStudySelected() )");
cancerStudySelected();
caseSetSelected();
$('#custom_case_set_ids').empty(); // reset the custom case set textarea
$('#select_single_study').trigger('doneChanging');
});
// Set up Event Handler for User Selecting a Case Set
$("#select_case_set").change(function() {
caseSetSelected();
caseSetSelectionOverriddenByUser = true;
});
// Set up Event Handler for User Selecting a Get Set
$("#select_gene_set").change(function() {
geneSetSelected();
});
// Set up Event Handler for View/Hide JSON Debug Information
$("#json_cancer_studies").click(function(event) {
event.preventDefault();
$('#cancer_results').toggle();
});
// Set up an Event Handler to intercept form submission
$("#main_form").submit(chooseAction);
// Set up an Event Handler for the Query / Data Download Tabs
$("#query_tab").click(function(event) {
event.preventDefault();
userClickedMainTab("tab_visualize")
});
$("#download_tab").click(function(event) {
event.preventDefault();
userClickedMainTab("tab_download");
});
// Set up custom case set related GUI & event handlers (step 3)
initCustomCaseSetUI();
// set toggle Step 5: Optional arguments
//$("#optional_args").hide();
/*$("#step5_toggle").click(function(event) {
event.preventDefault();
$("#optional_args").toggle( "blind" );
});*/
$('.netsize_help').tipTip();
$('#step5 > .step_header').click(function(){
$(".ui-icon", this).toggle();
$("#optional_args").toggle();
});
// unset cookie for results tabs, so that a new query
// always goes to summary tab first
$.cookie("results-tab",null);
}); // end document ready function
function supportsHTML5Storage() {
// from diveintohtml5.info/storage.html
try {
return 'localStorage' in window && window['localStorage'] !== null;
} catch (e) {
return false;
}
}
// Load study Meta Data, i.e. everything except the name, which we load earlier to
// populate the dropdown menu.
function loadStudyMetaData(cancerStudyId) {
console.log("loadStudyMetaData ("+cancerStudyId+")");
$('.main_query_panel').fadeTo("fast",0.6);
$.getJSON("portal_meta_data.json?study_id="+cancerStudyId, function(json){
window.metaDataJson.cancer_studies[cancerStudyId] = json;
updateCancerStudyInformation();
$('.main_query_panel').stop().fadeTo("fast",1);
});
}
// Load geneset gene list
function loadGeneList(geneSetId) {
$('.main_query_panel').fadeTo("fast",0.6);
$.getJSON("portal_meta_data.json?geneset_id="+geneSetId.replace(/\//g,""), function(json){
window.metaDataJson.gene_sets[geneSetId].gene_list = json.list;
$("#gene_list").val(json.list);
$('.main_query_panel').stop().fadeTo("fast",1);
});
}
// Load Portal JSON Meta Data, while showing loader image
function loadMetaData() {
$('#load').remove();
// show ajax loader image; loader is background image of div 'load' as set in css
$('.main_query_panel').append('<div id="load"> </div>');
$('#load').fadeIn('slow');
// hide the main query form until all meta data is loaded and added to page
$('#main_query_form').hide('fast',loadContent);
function loadContent() {
// Get Portal JSON Meta Data via JQuery AJAX
window.metaDataPromise = $.Deferred();
jQuery.getJSON("portal_meta_data.json?partial_studies=true&partial_genesets=true",function(json){
// Store JSON Data in global variable for later use
window.metaDataJson = json;
window.metaDataPromise.resolve(json);
// Load data of selected study right at the outset before continuing
$.getJSON("portal_meta_data.json?study_id="+window.cancer_study_id_selected, function(json) {
console.log("Loading metadata for "+window.cancer_study_id_selected);
// this code should be about the same as in loadStudyMetaData
window.metaDataJson.cancer_studies[window.cancer_study_id_selected] = json;
// Add Meta Data to current page
addMetaDataToPage();
showNewContent();
});
});
}
function showNewContent() {
//show content, hide loader only after content is shown
$('#main_query_form').fadeIn('fast', hideLoader);
}
function hideLoader() {
//hide loader image
$('#load').fadeOut('fast',removeLoader());
}
function removeLoader() {
// remove loader image so that it will not appear in the
// modify-query section on results page
$('#load').remove();
}
}
// Triggered when the User Selects one of the Main Query or Download Tabs
function userClickedMainTab(tabAction) {
window.changingTabs = true;
// Change hidden field value
$("#tab_index").val(tabAction);
// Then, submit the form
$("#main_form").submit();
}
// When the page is first loaded, the default query will be a cross-cancer type
// search in which the user will enter ONLY a gene list; Also when "All Cancer Studies"
// is selected in Step 1
function crossCancerStudySelected() {
$('#step2').hide();
$('#step2cross').show();
$('#step3').hide();
$('#step5').hide();
}
// Display extra steps when an individual cancer study is selected
function singleCancerStudySelected() {
$("#step2").show();
$('#step2cross').hide();
$("#step3").show();
//$("#step5").show();
}
// Select default genomic profiles
function makeDefaultSelections(){
$('.' + PROFILE_MUTATION_EXTENDED).prop('checked',true);
$('.' + PROFILE_COPY_NUMBER_ALTERATION +':checkbox').prop('checked',true);
$('.' + PROFILE_COPY_NUMBER_ALTERATION +':radio').first().prop('checked',true);
}
// Triggered after meta data is added to page in case page is
// re-drawn after query error and also any time a new cancer
// type is selected; Assesses the need for default selections
// and sets the visibility of each step based on current selections
function reviewCurrentSelections(){
//HACK TO DEAL WITH ASYNCHRONOUS STUFF SO WE DONT DO THIS UNTIL AFTER METADATA ADDED
if (window.metaDataAdded === true) {
// Unless the download tab has been chosen or 'All Cancer Studies' is
// selected, iterate through checkboxes to see if any are selected; if not,
// make default selections
if (window.tab_index !== "tab_download" && $("#select_single_study").val() !== 'all'){
var setDefaults = true;
// if no checkboxes are checked, make default selections
$('#genomic_profiles input:checkbox').each(function(){
if ($(this).prop('checked')){
setDefaults = false;
return;
}
});
if (setDefaults){
console.log("reviewCurrentSelections ( makeDefaultSelections() )");
makeDefaultSelections();
}
}
updateDefaultCaseList();
// determine whether mRNA threshold field should be shown or hidden
// based on which, if any mRNA profiles are selected
toggleThresholdPanel($("." + PROFILE_MRNA_EXPRESSION+"[type=checkbox]"), PROFILE_MRNA_EXPRESSION, "#z_score_threshold");
// similarly with RPPA
toggleThresholdPanel($("." + PROFILE_RPPA+"[type=checkbox]"), PROFILE_RPPA, "#rppa_score_threshold");
// determine whether optional arguments section should be shown or hidden
// if ($("#optional_args > input").length >= 1){
// $("#optional_args > input").each(function(){
// if ($(this).prop('checked')){
// // hide/show is ugly, but not sure exactly how toggle works
// // and couldn't get it to work.. this will do for now
// $("#step5 > .step_header > .ui-icon-triangle-1-e").hide();
// $("#step5 > .step_header > .ui-icon-triangle-1-s").show();
// $("#optional_args").toggle();
// return;
// }
// });
// }
}
}
// Determine whether to submit a cross-cancer query or
// a study-specific query
function chooseAction(evt) {
var haveExpInQuery = $("#gene_list").val().toUpperCase().search("EXP") > -1;
$("#error_box").remove();
var selected_studies = $("#jstree").jstree(true).get_selected_leaves();
while (selected_studies.length === 0 && !window.changingTabs) {
// select all by default
$("#jstree").jstree(true).select_node(window.jstree_root_id);
selected_studies = $("#jstree").jstree(true).get_selected_leaves()
}
if (selected_studies.length > 1) {
$("#main_form").find("#select_multiple_studies").val("");
if ($("#tab_index").val() == 'tab_download') {
$("#main_form").get(0).setAttribute('action','index.do');
}
else {
var dataPriority = $('#main_form').find('input[name=data_priority]:checked').val();
var newSearch = $('#main_form').serialize() + '&Action=Submit#crosscancer/overview/'+dataPriority+'/'+encodeURIComponent($('#gene_list').val())+'/'+encodeURIComponent(selected_studies.join(","));
evt.preventDefault();
window.location = 'cross_cancer.do?' + newSearch;
//$("#main_form").get(0).setAttribute('action','cross_cancer.do');
}
if ( haveExpInQuery ) {
createAnError("Expression filtering in the gene list is not supported when doing cross cancer queries.", $('#gene_list'));
evt.preventDefault();
}
} else if (selected_studies.length === 1) {
$("#main_form").find("#select_single_study").val(selected_studies[0]);
$("#main_form").get(0).setAttribute('action','index.do');
if ( haveExpInQuery ) {
var expCheckBox = $("." + PROFILE_MRNA_EXPRESSION);
if( expCheckBox.length > 0 && expCheckBox.prop('checked') == false) {
createAnError("Expression specified in the list of genes, but not selected in the" +
" Genetic Profile Checkboxes.", $('#gene_list'));
evt.preventDefault();
} else if( expCheckBox.length == 0 ) {
createAnError("Expression specified in the list of genes, but not selected in the" +
" Genetic Profile Checkboxes.", $('#gene_list'));
evt.preventDefault();
}
}
}
}
function createAnError(errorText, targetElt) {
var errorBox = $("<div id='error_box'>").addClass("ui-state-error ui-corner-all exp_error_box");
var errorButton = $("<span>").addClass("ui-icon ui-icon-alert exp_error_button");
var strongErrorText = $("<small>").html("Error: " + errorText + "<br>");
var errorTextBox = $("<span>").addClass("exp_error_text");
errorButton.appendTo(errorBox);
strongErrorText.appendTo(errorTextBox);
errorTextBox.appendTo(errorBox);
errorBox.insertBefore(targetElt);
errorBox.slideDown();
}
// Triggered when a genomic profile radio button is selected
function genomicProfileRadioButtonSelected(subgroupClicked) {
var subgroupClass = subgroupClicked.attr('class');
if (subgroupClass != undefined && subgroupClass != "") {
var checkboxSelector = "input."+subgroupClass+"[type=checkbox]";
if (checkboxSelector != undefined) {
$(checkboxSelector).prop('checked',true);
}
}
updateDefaultCaseList();
}
// Triggered when a genomic profile group check box is selected.
function profileGroupCheckBoxSelected(profileGroup) {
var profileClass = profileGroup.attr('class');
$("input."+profileClass+"[type=radio]").prop('checked',false);
if (profileGroup.prop('checked')) {
var rnaSeqRadios = $("input."+profileClass+"[type=radio][value*='rna_seq']");
if (rnaSeqRadios.length>0) {
rnaSeqRadios.first().prop('checked',true);
} else {
$("input."+profileClass+"[type=radio]").first().prop('checked',true);
}
}
updateDefaultCaseList();
}
// update default case list based on selected profiles
function updateDefaultCaseList() {
if (caseSetSelectionOverriddenByUser) return;
var mutSelect = $("input.PROFILE_MUTATION_EXTENDED[type=checkbox]").prop('checked');
var cnaSelect = $("input.PROFILE_COPY_NUMBER_ALTERATION[type=checkbox]").prop('checked');
var expSelect = $("input.PROFILE_MRNA_EXPRESSION[type=checkbox]").prop('checked');
var rppaSelect = $("input.PROFILE_RPPA[type=checkbox]").prop('checked');
var selectedCancerStudy = $('#select_single_study').val();
var defaultCaseList = selectedCancerStudy+"_all";
if (mutSelect && cnaSelect && !expSelect && !rppaSelect) {
defaultCaseList = selectedCancerStudy+"_cnaseq";
if ($("#select_case_set option[value='"+defaultCaseList+"']").length == 0) {
defaultCaseList = selectedCancerStudy+"_cna_seq"; //TODO: Better to unify to this one
}
} else if (mutSelect && !cnaSelect && !expSelect && !rppaSelect) {
defaultCaseList = selectedCancerStudy+"_sequenced";
} else if (!mutSelect && cnaSelect && !expSelect && !rppaSelect) {
defaultCaseList = selectedCancerStudy+"_acgh";
} else if (!mutSelect && !cnaSelect && expSelect && !rppaSelect) {
if ($('#'+selectedCancerStudy+'_mrna_median_Zscores').prop('checked')) {
defaultCaseList = selectedCancerStudy+"_mrna";
} else if ($('#'+selectedCancerStudy+'_rna_seq_mrna_median_Zscores').prop('checked')) {
defaultCaseList = selectedCancerStudy+"_rna_seq_mrna";
} else if ($('#'+selectedCancerStudy+'_rna_seq_v2_mrna_median_Zscores').prop('checked')) {
defaultCaseList = selectedCancerStudy+"_rna_seq_v2_mrna";
}
} else if ((mutSelect || cnaSelect) && expSelect && !rppaSelect) {
defaultCaseList = selectedCancerStudy+"_3way_complete";
} else if (!mutSelect && !cnaSelect && !expSelect && rppaSelect) {
defaultCaseList = selectedCancerStudy+"_rppa";
}
$('#select_case_set').val(defaultCaseList);
// HACKY CODE START -- TO SOLVE THE PROBLEM THAT WE HAVE BOTH _complete and _3way_complete
if (!$('#select_case_set').val()) {
if (defaultCaseList===selectedCancerStudy+"_3way_complete") {
$('#select_case_set').val(selectedCancerStudy+"_complete");
}
}// HACKY CODE END
if (!$('#select_case_set').val()) {
// in case no match
$('#select_case_set').val(selectedCancerStudy+"_all");
}
updateCaseListSmart();
}
// Print message and disable submit if use choosed a cancer type
// for which no genomic profiles are available
function genomicProfilesUnavailable(){
$("#genomic_profiles").html("<strong>No Genomic Profiles available for this Cancer Study</strong>");
$('#main_submit').attr('disabled',true);
}
// Show or hide mRNA threshold field based on mRNA profile selected
function toggleThresholdPanel(profileClicked, profile, threshold_div) {
var selectedProfile = profileClicked.val();
var inputType = profileClicked.attr('type');
// when a radio button is clicked, show threshold input unless user chooses expression outliers
if(inputType == 'radio'){
if(selectedProfile.indexOf("outlier")==-1){
$(threshold_div).slideDown();
} else {
$(threshold_div).slideUp();
}
} else if(inputType == 'checkbox'){
// if there are NO subgroups, show threshold input when mRNA checkbox is selected.
if (profileClicked.prop('checked')){
$(threshold_div).slideDown();
}
// if checkbox is unselected, hide threshold input regardless of whether there are subgroups
else {
$(threshold_div).slideUp();
}
}
}
// toggle:
// gistic button
// mutsig button
// according to the cancer_study
function toggleByCancerStudy(cancer_study) {
var mutsig = $('#toggle_mutsig_dialog');
var gistic = $('#toggle_gistic_dialog_button');
if (cancer_study.has_mutsig_data) {
mutsig.show();
} else {
mutsig.hide();
}
if (cancer_study.has_gistic_data) {
gistic.show();
} else {
gistic.hide();
}
}
function updateCaseListSmart() {
$("#select_case_set").trigger("liszt:updated");
$("#select_case_set_chzn .chzn-drop ul.chzn-results li")
.each(function(i, e) {
$(e).qtip({
content: "<font size='2'>" + $($("#select_case_set option")[i]).attr("title") + "</font>",
style: {
classes: 'qtip-light qtip-rounded qtip-shadow qtip-lightyellow'
},
position: {
my: 'left middle',
at: 'middle right',
viewport: $(window)
},
show: "mouseover",
hide: "mouseout"
});
}
);
}
// Called when and only when a cancer study is selected from the dropdown menu
function updateCancerStudyInformation() {
var cancerStudyId = $("#main_form").find("#select_single_study").val();
var cancer_study = window.metaDataJson.cancer_studies[cancerStudyId];
// toggle every time a new cancer study is selected
toggleByCancerStudy(cancer_study);
if (cancerStudyId=='all'){
crossCancerStudySelected();
return;
}
// Update Cancer Study Description
var citation = cancer_study.citation;
if (!citation) {
citation="";
}
else {
var pmid = cancer_study.pmid;
if (pmid) {
citation = " <a href='http://www.ncbi.nlm.nih.gov/pubmed/"+pmid+"'>"+citation+"</a>";
}
}
// Iterate through all genomic profiles
// Add all non-expression profiles where show_in_analysis_tab = true
// First, clear all existing options
$("#genomic_profiles").html("");
// Add Genomic Profiles, in this order
addGenomicProfiles(cancer_study.genomic_profiles, "MUTATION", PROFILE_MUTATION, "Mutation");
addGenomicProfiles(cancer_study.genomic_profiles, "MUTATION_EXTENDED", PROFILE_MUTATION_EXTENDED, "Mutation");
addGenomicProfiles(cancer_study.genomic_profiles, "COPY_NUMBER_ALTERATION", PROFILE_COPY_NUMBER_ALTERATION, "Copy Number");
addGenomicProfiles(cancer_study.genomic_profiles, "PROTEIN_LEVEL", PROFILE_PROTEIN, "Protein Level");
addGenomicProfiles(cancer_study.genomic_profiles, "MRNA_EXPRESSION", PROFILE_MRNA_EXPRESSION, "mRNA Expression");
addGenomicProfiles(cancer_study.genomic_profiles, "METHYLATION", PROFILE_METHYLATION, "DNA Methylation");
addGenomicProfiles(cancer_study.genomic_profiles, "METHYLATION_BINARY", PROFILE_METHYLATION, "DNA Methylation");
addGenomicProfiles(cancer_study.genomic_profiles, "PROTEIN_ARRAY_PROTEIN_LEVEL", PROFILE_RPPA, "Protein/phosphoprotein level (by RPPA)");
// if no genomic profiles available, set message and disable submit button
if ($("#genomic_profiles").html()==""){
console.log("cancerStudySelected ( genomicProfilesUnavailable() )");
genomicProfilesUnavailable();
}
// Update the Case Set Pull-Down Menu
// First, clear all existing pull-down menus
$("#select_case_set").html("");
// Iterate through all case sets
// Add each case set as an option, and include description as title, so that it appears
// as a tool-tip.
jQuery.each(cancer_study.case_sets,function(i, case_set) {
$("#select_case_set").append("<option class='case_set_option' value='"
+ case_set.id + "' title='"
+ case_set.description + "'>" + case_set.name + " ("+ case_set.size +")" + "</option>");
}); // end for each case study loop
// Add the user-defined case list option
$("#select_case_set").append("<option class='case_set_option' value='-1' "
+ "title='Specify you own case list'>User-defined Case List</option>");
updateCaseListSmart();
// Set up Tip-Tip Event Handler for Case Set Pull-Down Menu
// commented out for now, as this did not work in Chrome or Safari
// $(".case_set_option").tipTip({defaultPosition: "right", delay:"100", edgeOffset: 25});
// Set up Tip-Tip Event Handler for Genomic Profiles help
$(".profile_help").tipTip({defaultPosition: "right", delay:"100", edgeOffset: 25});
// Set up Event Handler for user selecting a genomic profile radio button
$("input[type='radio'][name*='genetic_profile_']").click(function(){
genomicProfileRadioButtonSelected($(this));
});
// Set up an Event Handler for user selecting a genomic profile checkbox
$("input[type='checkbox'][class*='PROFILE_']").click(function(){
profileGroupCheckBoxSelected($(this));
});
// Set up an Event Handler for showing/hiding mRNA threshold input
$("." + PROFILE_MRNA_EXPRESSION).click(function(){
toggleThresholdPanel($(this), PROFILE_MRNA_EXPRESSION, "#z_score_threshold");
});
// Set up an Event Handler for showing/hiding RPPA threshold input
$("." + PROFILE_RPPA).click(function(){
toggleThresholdPanel($(this), PROFILE_RPPA, "#rppa_score_threshold");
});
// Set default selections and make sure all steps are visible
console.log("cancerStudySelected ( singleCancerStudySelected() )");
singleCancerStudySelected();
console.log("cancerStudySelected ( reviewCurrentSelections() )");
reviewCurrentSelections();
// check if cancer study has a clinical_free_form data to filter,
// if there is data to filter, then enable "build custom case set" link,
// otherwise disable the button
jQuery.getJSON("ClinicalFreeForm.json",
{studyId: $("#select_single_study").val()},
function(json){
var noDataToFilter = false;
if (json.freeFormData.length == 0)
{
noDataToFilter = true;
}
else
{
noDataToFilter = true;
var categorySet = json.categoryMap;
// check if there is at least one category to filter
for (var category in categorySet)
{
// continue if the category is qualified as a filter parameter
if (isEligibleForFiltering(categorySet[category]))
{
noDataToFilter = false;
break;
}
}
}
if (noDataToFilter)
{
// no clinical_free_form data to filter for the current
// cancer study, so disable the button
$("#build_custom_case_set").hide();
}
else
{
$("#build_custom_case_set").tipTip({defaultPosition: "right",
delay:"100",
edgeOffset: 10,
maxWidth: 100});
$("#build_custom_case_set").hide();//.show(); temporarily disabled build case list
}
});
}
// Triggered when a cancer study has been selected, either by the user
// or programatically.
function cancerStudySelected() {
// make sure submit button is enabled unless determined otherwise by lack of data
$("#main_submit").attr("disabled",false);
var cancerStudyId = $("#select_single_study").val() || "all";
if (window.metaDataJson.cancer_studies[cancerStudyId].partial==="true") {
console.log("cancerStudySelected( loadStudyMetaData )");
loadStudyMetaData(cancerStudyId);
} else {
updateCancerStudyInformation();
}
}
// Triggered when a case set has been selected, either by the user
// or programatically.
function caseSetSelected() {
var caseSetId = $("#select_case_set").val();
// If user has selected the user-defined option, show the case list div
// Otherwise, make sure to hide it.
if (caseSetId == "-1") {
$("#custom_case_list_section").show();
// if custom case list was selected, post to avoid long url problem.
$("#main_form").attr("method","post");
} else {
$("#custom_case_list_section").hide();
$("#main_form").attr("method","get");
}
}
// Triggered when a gene set has been selected, either by the user
// or programatically.
function geneSetSelected() {
// Get the selected ID from the pull-down menu
var geneSetId = $("#select_gene_set").val();
if (window.metaDataJson.gene_sets[geneSetId].gene_list == "") {
loadGeneList(geneSetId);
} else {
// Get the gene set meta data from global JSON variable
var gene_set = window.metaDataJson.gene_sets[geneSetId];
// Set the gene list text area
$("#gene_list").val(gene_set.gene_list);
}
}
// Adds Meta Data to the Page.
// Tiggered at the end of successful AJAX/JSON request.
function addMetaDataToPage() {
console.log("Adding Meta Data to Query Form");
json = window.metaDataJson;
// Construct oncotree
var oncotree = {'tissue':{code:'tissue', studies:[], children:[], parent: false, desc_studies_count:0, tissue:''}};
var parents = json.parent_type_of_cancers;
// First add everything to the tree
for (var tumortype in parents) {
if (parents.hasOwnProperty(tumortype)) {
oncotree[tumortype] = {code:tumortype, studies:[], children:[], parent: false, desc_studies_count: 0, tissue: false};
}
}
// Link parents and insert initial tissue info
for (var tumortype in oncotree) {
if (oncotree.hasOwnProperty(tumortype) && tumortype !== 'tissue') {
oncotree[tumortype].parent = oncotree[parents[tumortype]];
oncotree[tumortype].parent.children.push(oncotree[tumortype]);
if (parents[tumortype] === "tissue") {
oncotree[tumortype].tissue = tumortype;
}
}
}
// Insert tissue information in a "union-find" type way
for (var elt in oncotree) {
if (oncotree.hasOwnProperty(elt) && elt !== 'tissue') {
var to_modify = [];
var currelt = oncotree[elt];
while (!currelt.tissue && currelt.code !== 'tissue') {
to_modify.push(currelt);
currelt = currelt.parent;
}
for (var i=0; i<to_modify.length; i++) {
to_modify[i].tissue = currelt.tissue;
}
}
}
// Add studies to tree, and climb up adding one to each level's descendant studies
// DMP hack
var dmp_studies = [];
for (var study in json.cancer_studies) {
if (study.indexOf("mskimpact") !== -1) {
// DMP hack
dmp_studies.push(study);
} else if (json.cancer_studies.hasOwnProperty(study) && study !== 'all') { // don't re-add 'all'
try {
var code = json.cancer_studies[study].type_of_cancer.toLowerCase();
var lineage = [];
var currCode = code;
while (currCode !== 'tissue') {
lineage.push(currCode);
currCode = oncotree[currCode].parent.code;
}
oncotree[code].studies.push({id:study, lineage:lineage});
var node = oncotree[code];
while (node) {
node.desc_studies_count += 1;
node = node.parent;
}
} catch (err) {
console.log("Unable to add study");
console.log(json.cancer_studies[study]);
}
}
}
// Sort dmp by number if there is one in the name
dmp_studies.sort(function(a,b) {
var matchA = a.match(/\d+/);
var matchB = b.match(/\d+/);
var numberA = (matchA === null ? NaN : parseInt(a.match(/\d+/)[0], 10));
var numberB = (matchB === null ? NaN : parseInt(b.match(/\d+/)[0], 10));
if (isNaN(numberA) && isNaN(numberB)) {
return a.localeCompare(b);
} else if (isNaN(numberA)) {
return -1;
} else if (isNaN(numberB)) {
return 1;
} else {
return numberA-numberB;
}
});
dmp_studies.reverse();
// Sort all the children alphabetically
for (var node in oncotree) {
if (oncotree.hasOwnProperty(node)) {
oncotree[node].children.sort(function(a,b) {
try {
return json.type_of_cancers[a.code].localeCompare(json.type_of_cancers[b.code]);
} catch(err) {
return a.code.localeCompare(b.code);
}
});
oncotree[node].studies.sort(function(a,b) {
return a.id.localeCompare(b.id);
});
}
}
var splitAndCapitalize = function(s) {
return s.split("_").map(function(x) { return (x.length > 0 ? x[0].toUpperCase()+x.slice(1) : x);}).join(" ");
};
var truncateStudyName = function(n) {
var maxLength = 80;
if (n.length < maxLength) {
return n;
} else {
var suffix = '';
var suffixStart = n.indexOf('(');
if (suffixStart !== -1) {
suffix = n.slice(suffixStart);
}
var ellipsis = '... ';
return n.slice(0,maxLength-suffix.length-ellipsis.length)+ellipsis+suffix;
}
};
window.jstree_root_id = 'tissue';
var jstree_data = [];
var flat_jstree_data = [];
jstree_data.push({'id':jstree_root_id, parent:'#', text:'All', state:{opened:true}, li_attr:{name:'All'}});
flat_jstree_data.push({'id':jstree_root_id, parent:'#', text:'All', state:{opened:true}, li_attr:{name:'All'}});
var node_queue = [].concat(oncotree['tissue'].children);
var currNode;
if (dmp_studies.length > 0) {
jstree_data.push({'id':'mskimpact-study-group', 'parent':jstree_root_id, 'text':'MSKCC DMP', 'li_attr':{name:'MSKCC DMP'}});
var studyName;
$.each(dmp_studies, function(ind, id) {
studyName = truncateStudyName(json.cancer_studies[id].name);
jstree_data.push({'id':id, 'parent':'mskimpact-study-group', 'text':studyName,
'li_attr':{name: studyName, description: metaDataJson.cancer_studies[id].description}});
flat_jstree_data.push({'id':id, 'parent':jstree_root_id, 'text':truncateStudyName(json.cancer_studies[id].name),
'li_attr':{name: studyName, description: metaDataJson.cancer_studies[id].description, search_terms: 'MSKCC DMP'}});
});
}
while (node_queue.length > 0) {
currNode = node_queue.shift();
if (currNode.desc_studies_count > 0) {
var name = splitAndCapitalize(metaDataJson.type_of_cancers[currNode.code] || currNode.code);
jstree_data.push({'id':currNode.code,
'parent':((currNode.parent && currNode.parent.code) || '#'),
'text':name,
'li_attr':{name:name}
});
$.each(currNode.studies, function(ind, elt) {
name = truncateStudyName(splitAndCapitalize(metaDataJson.cancer_studies[elt.id].name));
jstree_data.push({'id':elt.id,
'parent':currNode.code,
'text':name,
'li_attr':{name: name, description:metaDataJson.cancer_studies[elt.id].description}});
flat_jstree_data.push({'id':elt.id,
'parent':jstree_root_id,
'text':name,
'li_attr':{name: name, description:metaDataJson.cancer_studies[elt.id].description, search_terms: elt.lineage.join(" ")}});
});
node_queue = node_queue.concat(currNode.children);
}
}
var precomputed_search = {query: '', results: {}};
var parse_search_query = function(query) {
// First eliminate trailing whitespace and reduce every whitespace
// to a single space.
query = query.toLowerCase().trim().split(/\s+/g).join(' ');
// Now factor out quotation marks and inter-token spaces
var phrases = [];
var currInd = 0;
var nextSpace, nextQuote;
while (currInd < query.length) {
if (query[currInd] === '"') {
nextQuote = query.indexOf('"', currInd+1);
if (nextQuote === -1) {
phrases.push(query.substring(currInd + 1));
currInd = query.length;
} else {
phrases.push(query.substring(currInd + 1, nextQuote));
currInd = nextQuote + 1;
}
} else if (query[currInd] === ' ') {
currInd += 1;
} else if (query[currInd] === '-') {
phrases.push('-');
currInd += 1;
} else {
nextSpace = query.indexOf(' ', currInd);
if (nextSpace === -1) {
phrases.push(query.substring(currInd));
currInd = query.length;
} else {
phrases.push(query.substring(currInd, nextSpace));
currInd = nextSpace + 1;
}
}
}
// Now get the conjunctive clauses, and the negative clauses
var clauses = [];
currInd = 0;
var nextOr, nextDash;
while (currInd < phrases.length) {
if (phrases[currInd] === '-') {
if (currInd < phrases.length - 1) {
clauses.push({"type":"not", "data":phrases[currInd+1]});
}
currInd = currInd + 2;
} else {
nextOr = phrases.indexOf('or', currInd);
nextDash = phrases.indexOf('-', currInd);
if (nextOr === -1 && nextDash === -1) {
clauses.push({"type":"and","data":phrases.slice(currInd)});
currInd = phrases.length;
} else if (nextOr === -1 && nextDash > 0) {
clauses.push({"type":"and", "data":phrases.slice(currInd, nextDash)});
currInd = nextDash;
} else if (nextOr > 0 && nextDash === -1) {
clauses.push({"type":"and", "data":phrases.slice(currInd, nextOr)});
currInd = nextOr + 1;
} else {
if (nextOr < nextDash) {
clauses.push({"type":"and", "data":phrases.slice(currInd, nextOr)});
currInd = nextOr + 1;
} else {
clauses.push({"type":"and", "data":phrases.slice(currInd, nextDash)});
currInd = nextDash;
}
}
}
}
return clauses;
};
var matchPhrase = function(phrase, node) {
phrase = phrase.toLowerCase();
return !!((node.li_attr && node.li_attr.name && node.li_attr.name.toLowerCase().indexOf(phrase) > -1)
|| (node.li_attr && node.li_attr.description && node.li_attr.description.toLowerCase().indexOf(phrase) > -1)
|| (node.li_attr && node.li_attr.search_terms && node.li_attr.search_terms.toLowerCase().indexOf(phrase) > -1));
};
var perform_search_single = function(parsed_query, node) {
// in: a jstree node
// text to search is node.text and node.li_attr.description and node.li_attr.search_terms
// return true iff the query, considering quotation marks, 'and' and 'or' logic, matches
var match = false;
var hasPositiveClauseType = false;
var forced = false;
$.each(parsed_query, function(ind, clause) {
if (clause.type !== 'not') {
hasPositiveClauseType = true;
return 0;
}
});
if (!hasPositiveClauseType) {
// if only negative clauses, match by default
match = true;
}
$.each(parsed_query, function(ind, clause) {
if (clause.type === 'not') {
if (matchPhrase(clause.data, node)) {
match = false;
forced = true;
return 0;
}
} else if (clause.type === 'and') {
hasPositiveClauseType = true;
var clauseMatch = true;
$.each(clause.data, function(ind2, phrase) {
clauseMatch = clauseMatch && matchPhrase(phrase, node);
});
match = match || clauseMatch;
}
});
return {result:match, forced:forced};
};
var perform_search = function(query) {
// IN: query, a string
// void method
// when this ends, the object precomputed_search has been updated
// so that results[node.id] = true iff the query directly matches it
var parsed_query = parse_search_query(query);
$.each($('#jstree').jstree(true)._model.data, function(key, node) {
precomputed_search.results[node.id] = perform_search_single(parsed_query, node);
});
precomputed_search.query = query;
};
var jstree_search = function(query, node) {
if (query === "") {
return true;
}
if (precomputed_search.query !== query) {
perform_search(query);
}
if (!precomputed_search.results[node.id].result && precomputed_search.results[node.id].forced) {
return false;
}
var nodes_to_consider = [node.id].concat(node.parents.slice());
var ret = false;
$.each(nodes_to_consider, function(ind, elt) {
if (elt === jstree_root_id || elt === '#') {
return 0;
}
if (!precomputed_search.results[elt].result && precomputed_search.results[elt].forced) {
ret = false;
return 0;
}
ret = ret || precomputed_search.results[elt].result;
});
return ret;
};
var initialize_jstree = function (data) {
console.log("Initializing jstree");
$("#jstree").jstree({
"themes": {
"theme": "default",
"dots": false,
"icons": false,
"url": "../../css/jstree.style.css"
},
"plugins": ['checkbox','search'],
"search": {'show_only_matches': true,
'search_callback': jstree_search,
'search_leaves_only': true},
"checkbox": {},
'core': {'data': data, 'check_callback': true, 'dblclick_toggle': false, 'multiple': (window.tab_index !== "tab_download")}
});
$('#jstree').on('ready.jstree', function () {
$('#jstree').jstree(true).num_leaves = $('#jstree').jstree(true).get_leaves().length;
$('#jstree').jstree(true).get_matching_nodes = function (phrase) {
var ret = [];
$.each($('#jstree').jstree(true)._model.data, function (key, node) {
if (matchPhrase(phrase, node)) {
ret.push(key);
}
});
return ret;
};
$('#jstree').jstree(true).get_node(jstree_root_id, true).children('.jstree-anchor').after($jstree_flatten_btn());
$('#jstree').jstree(true).open_all();
});
$('#jstree').on('changed.jstree', function() { onJSTreeChange(); /*saveSelectedStudiesLocalStorage();*/ });
$('#jstree').jstree(true).hide_icons();
}
initialize_jstree(window.tab_index === "tab_download" ? flat_jstree_data : jstree_data);
var jstree_is_flat = false;
var $jstree_flatten_btn = (function() {
if (window.tab_index === "tab_download") {
return false;
}
var ret = $('<i class="fa fa-lg fa-code-fork jstree-external-node-decorator" style="display:none; cursor:pointer; padding-left:0.6em"></i>');
ret.mouseenter(function () {
ret.fadeTo('fast', 0.7);
});
ret.mouseleave(function () {
ret.fadeTo('fast', 1);
});
ret.click(function () {
var selected_studies = $("#jstree").jstree(true).get_selected_leaves();
$('#jstree').jstree(true).destroy();
jstree_is_flat = !jstree_is_flat;
initialize_jstree((jstree_is_flat ? flat_jstree_data : jstree_data));
$('#jstree').on('ready.jstree', function () {
$('#jstree').jstree(true).select_node(selected_studies);
if ($("#jstree_search_input").val() !== "") {
precomputed_search.query = false; // force re-search
do_jstree_search();
}
});
});
ret.qtip({
content: {text: (jstree_is_flat ? "Unflatten tree" : "Flatten tree")},
style: {classes: 'qtip-light qtip-rounded'},
position: {my: 'bottom center', at: 'top center', viewport: $(window)},
show: {delay: 600},
hide: {delay: 10, fixed: true},
});
return ret;
});
var do_jstree_search = function() {
$("#jstree").jstree(true).search($("#jstree_search_input").val());
$('#jstree').jstree(true).get_node(jstree_root_id, true).children('.jstree-anchor').after($jstree_flatten_btn());
}
var jstree_search_timeout = null;
$("#jstree_search_input").on('input', function () {
if (jstree_search_timeout) {
clearTimeout(jstree_search_timeout);
}
jstree_search_timeout = setTimeout(function () {
if ($("#jstree_search_input").val() === "") {
$("#step_header_first_line_empty_search").css("display", "none");
$("#jstree").jstree(true)._model.data['tissue'].li_attr.name = "All";
} else {
$("#step_header_first_line_empty_search").css("display", "block");
$("#jstree").jstree(true)._model.data['tissue'].li_attr.name = "All Search Results";
}
$("#jstree").fadeTo(100, 0.5, function () {
$('#jstree_search_none_found_msg').hide();
do_jstree_search();
if ($('#jstree_search_input').val() !== "" && $('#jstree').jstree(true)._data.search.res.length === 0) {
$('#jstree_search_none_found_msg').show();
}
$("#jstree").fadeTo(100, 1);
});
}, 400); // wait for a bit with no typing before searching
});
$('#step_header_first_line_empty_search').click(function() {
$("#jstree_search_input").val("");
$("#step_header_first_line_empty_search").css("display", "none");
$("#jstree").fadeTo(100, 0.5, function () {
do_jstree_search();
$("#jstree").fadeTo(100, 1);
});
});
var saveSelectedStudiesLocalStorage = function() {
if (!supportsHTML5Storage()) {
return false;
}
var selected_studies = $("#jstree").jstree(true).get_selected_leaves();
// selectedStudiesStorageKey
window.localStorage.setItem(selectedStudiesStorageKey, selected_studies.join(","));
//$.removeCookie(selectedStudiesCookieName);
//$.cookie(selectedStudiesCookieName, selected_studies.join(","), {expires:10});
return true;
};
var getSelectedStudiesLocalStorage = function() {
if (!supportsHTML5Storage()) {
return false;
}
return window.localStorage.getItem(selectedStudiesStorageKey);
}
var onJSTreeChange = function () {
$("#error_box").remove();
var select_single_study = $("#main_form").find("#select_single_study");
var select_multiple_studies = $("#main_form").find("#select_multiple_studies");
var selected_studies = $("#jstree").jstree(true).get_selected_leaves();
var selected_ct = selected_studies.length;
$('#jstree_selected_study_count').html((selected_ct === 0 ? "No" : (selected_ct === $('#jstree').jstree(true).num_leaves ? "All" : selected_ct)) + " stud" + (selected_ct === 1 ? "y" : "ies") + " selected.");
$('#jstree_deselect_all_btn')[selected_ct > 0 ? 'show' : 'hide']();
var old_select_single_study_val = select_single_study.val();
if (selected_studies.length === 1) {
select_single_study.val(selected_studies[0]);
} else {
select_single_study.val("all");
}
select_multiple_studies.val(selected_studies.join(","));
if (select_single_study.val() !== old_select_single_study_val) {
select_single_study.trigger('change');
}
select_multiple_studies.trigger('change');
};
// Add Gene Sets to Pull-down Menu
jQuery.each(json.gene_sets,function(key,gene_set){
$("#select_gene_set").append("<option value='" + key + "'>"
+ gene_set.name + "</option>");
}); // end for each gene set loop
// Set the placeholder for the autocomplete select box
$("#example_gene_set").children("span:first").children("input:first")
.attr("placeholder", $("#select_gene_set").children("option:first").text());
// Set things up, based on currently selected cancer type
// hacky; order of preference
var selected_study_map = {};
if (!window.cancer_study_list_selected || window.cancer_study_list_selected === '') {
var windowParams = window.location.search.substring(1).split("&");
$.each(windowParams, function(ind, elt) {
var pair = elt.split("=");
if (pair[0] === window.cancer_study_list_param) {
window.cancer_study_list_selected = pair[1];
return 0;
}
});
}
if (!window.cancer_study_list_selected || window.cancer_study_list_selected === '') {
var split_url_on_hash = window.location.href.split('#');
if (split_url_on_hash.length > 1) {
window.cancer_study_list_selected = split_url_on_hash[1].split("/")[4];
}
}
if (!window.cancer_study_list_selected || window.cancer_study_list_selected === '') {
var windowParams = window.location.search.substring(1).split("&");
$.each(windowParams, function(ind, elt) {
var pair = elt.split("=");
if (pair[0] === 'cancer_study_id') {
window.cancer_study_list_selected = pair[1];
return 0;
}
});
}
//var selected_study_list = decodeURIComponent(window.selected_cancer_study_list || ( getSelectedStudiesLocalStorage() || '')).split(",");
var selected_study_list = (window.tab_index !== "tab_download" ? decodeURIComponent(window.cancer_study_list_selected || '').split(",") : []);
$.each(selected_study_list, function(ind, elt) {
if (elt !== '') {
selected_study_map[elt] = false;
}
});
if (window.cancer_study_id_selected !== 'all') {
selected_study_map[window.cancer_study_id_selected] = false;
}
jQuery.each(json.cancer_studies,function(key,cancer_study){
// Set Selected Cancer Type, Based on User Parameter
if (selected_study_map.hasOwnProperty(key)) {
selected_study_map[key] = true;
}
});
$("#jstree").on('ready.jstree', function() {
// Chosenize the select boxes
var minSearchableItems = 10;
$("#select_gene_set").chosen({ width: '620px', search_contains: true});
$("#select_case_set").chosen({ width: '420px', disable_search_threshold: minSearchableItems, search_contains: true });
$.each(selected_study_map, function(key, val) {
if (val) {
$("#jstree").jstree(true).select_node(key, true);
}
});
// Set things up, based on currently selected case set id
$('#select_single_study').one('doneChanging', function() {
if (window.case_set_id_selected != null && window.case_set_id_selected != "") {
$("#select_case_set").val(window.case_set_id_selected);
$("#select_case_set").trigger('liszt:updated');
caseSetSelectionOverriddenByUser = true;
}
caseSetSelected();
if (window.case_ids_selected !== '') {
$('#custom_case_set_ids').val(window.case_ids_selected);
}
// Set things up, based on currently selected gene set id
if (window.gene_set_id_selected != null && window.gene_set_id_selected != "") {
$("#select_gene_set").val(window.gene_set_id_selected);
} else {
$("#select_gene_set").val("user-defined-list");
}
$("#select_gene_set").trigger('liszt:updated');
// Set things up, based on all currently selected genomic profiles
// To do so, we iterate through all input elements with the name = 'genetic_profile_ids*'
$("input[name^=genetic_profile_ids]").each(function (index) {
// val() is the value that or stable ID of the genetic profile ID
var currentValue = $(this).val();
// if the user has this stable ID already selected, mark it as checked
if (window.genomic_profile_id_selected[currentValue] == 1) {
console.log("Checking " + $(this).attr('id') + "... (inside addMetaDataToPage())");
$(this).prop('checked', true);
// Select the surrounding checkbox
genomicProfileRadioButtonSelected($(this));
}
}); // end for each genomic profile option
// HACK TO DEAL WITH ASYNCHRONOUS STUFF
window.metaDataAdded = true;
// determine whether any selections have already been made
// to make sure all of the fields are shown/hidden as appropriate
console.log("addMetaDataToPage ( reviewCurrentSelections() )");
reviewCurrentSelections();
});
onJSTreeChange();
});
}
// Adds the specified genomic profiles to the page.
// Code checks for three possibilities:
// 1. 0 profiles of targetType --> show nothing
// 2. 1 profile of targetType --> show as checkbox
// 3. >1 profiles of targetType --> show group checkbox plus radio buttons
function addGenomicProfiles (genomic_profiles, targetAlterationType, targetClass, targetTitle) {
var numProfiles = 0;
var profileHtml = "";
var downloadTab = false;
// Determine whether we are in the download tab
if (window.tab_index == "tab_download") {
downloadTab = true;
}
// First count how many profiles match the targetAltertion type
jQuery.each(genomic_profiles,function(key, genomic_profile) {
if (genomic_profile.alteration_type == targetAlterationType) {
if (downloadTab || genomic_profile.show_in_analysis_tab == true) {
numProfiles++;
}
}
}); // end for each genomic profile loop
if (numProfiles == 0) {
return;
} else if(numProfiles >1 && downloadTab == false) {
// enable submit button
$('#main_submit').attr('disabled', false);
// If we have more than 1 profile, output group checkbox
// assign a class to associate the checkbox with any subgroups (radio buttons)
profileHtml += "<input type='checkbox' class='" + targetClass + "'>"
+ targetTitle + " data."
+ " Select one of the profiles below:";
profileHtml += "<div class='genomic_profiles_subgroup'>";
}
// Iterate through all genomic profiles
jQuery.each(genomic_profiles,function(key, genomic_profile) {
if (genomic_profile.alteration_type == targetAlterationType) {
if (downloadTab || genomic_profile.show_in_analysis_tab == true) {
// Branch depending on number of profiles
var optionType = "checkbox";
if (downloadTab) {
optionType = "radio";
} else {
if (numProfiles == 1) {
optionType = "checkbox";
} else if (numProfiles > 1) {
optionType = "radio";
}
}
profileHtml += outputGenomicProfileOption (downloadTab, optionType,
targetClass, genomic_profile.id, genomic_profile.name, genomic_profile.description);
}
}
}); // end for each genomic profile loop
if(numProfiles >1) {
// If we have more than 1 profile, output the end div tag
profileHtml += "</div>";
}
if(targetClass == PROFILE_MRNA_EXPRESSION && downloadTab == false){
var inputName = 'Z_SCORE_THRESHOLD';
profileHtml += "<div id='z_score_threshold' class='score_threshold'>Enter a z-score threshold ±: "
+ "<input type='text' name='" + inputName + "' size='6' value='"
+ window.zscore_threshold + "'>"
+ "</div>";
}
if(targetClass == PROFILE_RPPA && downloadTab == false){
var inputName = 'RPPA_SCORE_THRESHOLD';
profileHtml += "<div id='rppa_score_threshold' class='score_threshold'>Enter a RPPA z-score threshold ±: "
+ "<input type='text' name='" + inputName + "' size='6' value='"
+ window.rppa_score_threshold + "'>"
+ "</div>";
}
$("#genomic_profiles").append(profileHtml);
}
// Outputs a Single Genomic Profile Options
function outputGenomicProfileOption (downloadTab, optionType, targetClass, id, name,
description) {
// This following if/else requires some explanation.
// If we are in the download tab, all the input fields must use the same name.
// This enforces all inputs to work as a single group of radio buttons.
// If we are in the query tab, the input fields must be specified by alteration type.
// This enforces all the inputs of the same alteration type to work as a single group of radio
// buttons.
var paramName;
if (downloadTab) {
paramName = "genetic_profile_ids";
} else {
paramName = "genetic_profile_ids_" + targetClass;
}
var html = "<input type='" + optionType + "' "
+ "id='" + id + "'"
+ " name='" + paramName + "'"
+ " class='" + targetClass + "'"
+ " value='" + id +"'>" + ' ' + name + "</input>"
+ " <img class='profile_help' src='images/help.png' title='"
+ description + "'><br/>";
return html;
}
| remove protein level for quer
| portal/src/main/webapp/js/src/dynamicQuery.js | remove protein level for quer | <ide><path>ortal/src/main/webapp/js/src/dynamicQuery.js
<ide> addGenomicProfiles(cancer_study.genomic_profiles, "MUTATION", PROFILE_MUTATION, "Mutation");
<ide> addGenomicProfiles(cancer_study.genomic_profiles, "MUTATION_EXTENDED", PROFILE_MUTATION_EXTENDED, "Mutation");
<ide> addGenomicProfiles(cancer_study.genomic_profiles, "COPY_NUMBER_ALTERATION", PROFILE_COPY_NUMBER_ALTERATION, "Copy Number");
<del> addGenomicProfiles(cancer_study.genomic_profiles, "PROTEIN_LEVEL", PROFILE_PROTEIN, "Protein Level");
<ide> addGenomicProfiles(cancer_study.genomic_profiles, "MRNA_EXPRESSION", PROFILE_MRNA_EXPRESSION, "mRNA Expression");
<ide> addGenomicProfiles(cancer_study.genomic_profiles, "METHYLATION", PROFILE_METHYLATION, "DNA Methylation");
<ide> addGenomicProfiles(cancer_study.genomic_profiles, "METHYLATION_BINARY", PROFILE_METHYLATION, "DNA Methylation");
<add> //addGenomicProfiles(cancer_study.genomic_profiles, "PROTEIN_LEVEL", PROFILE_PROTEIN, "Protein Level");
<ide> addGenomicProfiles(cancer_study.genomic_profiles, "PROTEIN_ARRAY_PROTEIN_LEVEL", PROFILE_RPPA, "Protein/phosphoprotein level (by RPPA)");
<ide>
<ide> |
|
Java | apache-2.0 | 319c71f69ff78e2d32d5f786ed5d72740b98fe4e | 0 | imay/palo,imay/palo,imay/palo,imay/palo,imay/palo,imay/palo | // 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.doris.task;
import org.apache.doris.catalog.Catalog;
import org.apache.doris.catalog.Database;
import org.apache.doris.common.util.DebugUtil;
import org.apache.doris.load.EtlSubmitResult;
import org.apache.doris.load.FailMsg.CancelType;
import org.apache.doris.load.Load;
import org.apache.doris.load.LoadChecker;
import org.apache.doris.load.LoadJob;
import org.apache.doris.load.LoadJob.JobState;
import org.apache.doris.service.FrontendOptions;
import org.apache.doris.thrift.TStatusCode;
import org.apache.doris.transaction.TransactionState.LoadJobSourceType;
import com.google.common.base.Joiner;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.List;
import java.util.UUID;
public abstract class LoadPendingTask extends MasterTask {
private static final Logger LOG = LogManager.getLogger(LoadPendingTask.class);
private static final int RETRY_NUM = 5;
protected final LoadJob job;
protected final Load load;
protected Database db;
public LoadPendingTask(LoadJob job) {
this.job = job;
this.signature = job.getId();
this.load = Catalog.getInstance().getLoadInstance();
}
@Override
protected void exec() {
// check job state
if (job.getState() != JobState.PENDING) {
return;
}
// check timeout
if (LoadChecker.checkTimeout(job)) {
load.cancelLoadJob(job, CancelType.TIMEOUT, "pending timeout to cancel");
return;
}
// get db
long dbId = job.getDbId();
db = Catalog.getInstance().getDb(dbId);
if (db == null) {
load.cancelLoadJob(job, CancelType.ETL_SUBMIT_FAIL, "db does not exist. id: " + dbId);
return;
}
try {
// yiguolei: get transactionid here, because create etl request will get schema and partition info
// create etl request and make some guarantee for schema change and rollup
if (job.getTransactionId() < 0) {
long transactionId = Catalog.getCurrentGlobalTransactionMgr()
.beginTransaction(dbId, DebugUtil.printId(UUID.randomUUID()),
"FE: " + FrontendOptions.getLocalHostAddress(), LoadJobSourceType.FRONTEND,
job.getTimeoutSecond());
job.setTransactionId(transactionId);
}
createEtlRequest();
} catch (Exception e) {
LOG.info("create etl request failed.", e);
load.cancelLoadJob(job, CancelType.ETL_SUBMIT_FAIL, "create job request fail. " + e.getMessage());
return;
}
// submit etl job and retry 5 times if error
EtlSubmitResult result = null;
int retry = 0;
while (retry < RETRY_NUM) {
result = submitEtlJob(retry);
if (result != null) {
if (result.getStatus().getStatus_code() == TStatusCode.OK) {
if (load.updateLoadJobState(job, JobState.ETL)) {
LOG.info("submit etl job success. job: {}", job);
return;
}
}
}
++retry;
}
String failMsg = "submit etl job fail";
if (result != null) {
List<String> failMsgs = result.getStatus().getError_msgs();
failMsg = Joiner.on(";").join(failMsgs);
}
load.cancelLoadJob(job, CancelType.ETL_SUBMIT_FAIL, failMsg);
LOG.warn("submit etl job fail. job: {}", job);
}
protected abstract void createEtlRequest() throws Exception;
protected abstract EtlSubmitResult submitEtlJob(int retry);
}
| fe/src/main/java/org/apache/doris/task/LoadPendingTask.java | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package org.apache.doris.task;
import org.apache.doris.catalog.Catalog;
import org.apache.doris.catalog.Database;
import org.apache.doris.common.util.DebugUtil;
import org.apache.doris.load.EtlSubmitResult;
import org.apache.doris.load.FailMsg.CancelType;
import org.apache.doris.load.Load;
import org.apache.doris.load.LoadChecker;
import org.apache.doris.load.LoadJob;
import org.apache.doris.load.LoadJob.JobState;
import org.apache.doris.service.FrontendOptions;
import org.apache.doris.thrift.TStatusCode;
import org.apache.doris.transaction.TransactionState.LoadJobSourceType;
import com.google.common.base.Joiner;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.List;
import java.util.UUID;
import sun.security.ssl.Debug;
public abstract class LoadPendingTask extends MasterTask {
private static final Logger LOG = LogManager.getLogger(LoadPendingTask.class);
private static final int RETRY_NUM = 5;
protected final LoadJob job;
protected final Load load;
protected Database db;
public LoadPendingTask(LoadJob job) {
this.job = job;
this.signature = job.getId();
this.load = Catalog.getInstance().getLoadInstance();
}
@Override
protected void exec() {
// check job state
if (job.getState() != JobState.PENDING) {
return;
}
// check timeout
if (LoadChecker.checkTimeout(job)) {
load.cancelLoadJob(job, CancelType.TIMEOUT, "pending timeout to cancel");
return;
}
// get db
long dbId = job.getDbId();
db = Catalog.getInstance().getDb(dbId);
if (db == null) {
load.cancelLoadJob(job, CancelType.ETL_SUBMIT_FAIL, "db does not exist. id: " + dbId);
return;
}
try {
// yiguolei: get transactionid here, because create etl request will get schema and partition info
// create etl request and make some guarantee for schema change and rollup
if (job.getTransactionId() < 0) {
long transactionId = Catalog.getCurrentGlobalTransactionMgr()
.beginTransaction(dbId, DebugUtil.printId(UUID.randomUUID()),
"FE: " + FrontendOptions.getLocalHostAddress(), LoadJobSourceType.FRONTEND,
job.getTimeoutSecond());
job.setTransactionId(transactionId);
}
createEtlRequest();
} catch (Exception e) {
LOG.info("create etl request failed.", e);
load.cancelLoadJob(job, CancelType.ETL_SUBMIT_FAIL, "create job request fail. " + e.getMessage());
return;
}
// submit etl job and retry 5 times if error
EtlSubmitResult result = null;
int retry = 0;
while (retry < RETRY_NUM) {
result = submitEtlJob(retry);
if (result != null) {
if (result.getStatus().getStatus_code() == TStatusCode.OK) {
if (load.updateLoadJobState(job, JobState.ETL)) {
LOG.info("submit etl job success. job: {}", job);
return;
}
}
}
++retry;
}
String failMsg = "submit etl job fail";
if (result != null) {
List<String> failMsgs = result.getStatus().getError_msgs();
failMsg = Joiner.on(";").join(failMsgs);
}
load.cancelLoadJob(job, CancelType.ETL_SUBMIT_FAIL, failMsg);
LOG.warn("submit etl job fail. job: {}", job);
}
protected abstract void createEtlRequest() throws Exception;
protected abstract EtlSubmitResult submitEtlJob(int retry);
}
| Remove unnecessary import sun.security.ssl.Debug (#1215)
| fe/src/main/java/org/apache/doris/task/LoadPendingTask.java | Remove unnecessary import sun.security.ssl.Debug (#1215) | <ide><path>e/src/main/java/org/apache/doris/task/LoadPendingTask.java
<ide>
<ide> import java.util.List;
<ide> import java.util.UUID;
<del>
<del>import sun.security.ssl.Debug;
<ide>
<ide> public abstract class LoadPendingTask extends MasterTask {
<ide> private static final Logger LOG = LogManager.getLogger(LoadPendingTask.class); |
|
Java | apache-2.0 | 09dad0b96a67f169fba1b6a10daa083a6689771d | 0 | kalyanreddyemani/opencga,opencb/opencga,roalva1/opencga,kalyanreddyemani/opencga,opencb/opencga,j-coll/opencga,javild/opencga,opencb/opencga,roalva1/opencga,kalyanreddyemani/opencga,roalva1/opencga,j-coll/opencga,opencb/opencga,j-coll/opencga,kalyanreddyemani/opencga,roalva1/opencga,opencb/opencga,j-coll/opencga,javild/opencga,roalva1/opencga,j-coll/opencga,roalva1/opencga,roalva1/opencga,roalva1/opencga,kalyanreddyemani/opencga,j-coll/opencga,javild/opencga,kalyanreddyemani/opencga,javild/opencga,javild/opencga,opencb/opencga,javild/opencga,roalva1/opencga | package org.opencb.opencga.analysis.storage.variant;
import org.opencb.biodata.models.feature.Region;
import org.opencb.biodata.models.variant.Variant;
import org.opencb.biodata.models.variant.annotation.VariantAnnotation;
import org.opencb.commons.io.DataWriter;
import org.opencb.datastore.core.ObjectMap;
import org.opencb.datastore.core.QueryOptions;
import org.opencb.datastore.core.QueryResult;
import org.opencb.opencga.catalog.CatalogException;
import org.opencb.opencga.catalog.CatalogManager;
import org.opencb.opencga.catalog.beans.File;
import org.opencb.opencga.catalog.beans.Study;
import org.opencb.opencga.storage.core.StorageManagerException;
import org.opencb.opencga.storage.core.StorageManagerFactory;
import org.opencb.opencga.storage.core.variant.adaptors.VariantDBAdaptor;
import org.opencb.opencga.storage.core.variant.adaptors.VariantDBIterator;
import org.opencb.opencga.storage.core.variant.adaptors.VariantSourceDBAdaptor;
import org.opencb.opencga.storage.core.variant.stats.VariantStatsWrapper;
import java.util.*;
/**
* Created by hpccoll1 on 13/02/15.
*/
//public class CatalogVariantDBAdaptor {}
public class CatalogVariantDBAdaptor implements VariantDBAdaptor {
private final CatalogManager catalogManager;
private final VariantDBAdaptor dbAdaptor;
public CatalogVariantDBAdaptor(CatalogManager catalogManager, VariantDBAdaptor dbAdaptor) {
this.catalogManager = catalogManager;
this.dbAdaptor = dbAdaptor;
}
public CatalogVariantDBAdaptor(CatalogManager catalogManager, String fileId, String sessionId) throws CatalogException, IllegalAccessException, InstantiationException, ClassNotFoundException, StorageManagerException {
this.catalogManager = catalogManager;
this.dbAdaptor = buildBAdaptor(catalogManager, fileId, sessionId);
}
private static VariantDBAdaptor buildBAdaptor(CatalogManager catalogManager, String fileId, String sessionId) throws CatalogException, ClassNotFoundException, IllegalAccessException, InstantiationException, StorageManagerException {
int id = catalogManager.getFileId(fileId);
File file = catalogManager.getFile(id, sessionId).getResult().get(0);
String dbName = file.getAttributes().get("dbName").toString();
String storageEngine = file.getAttributes().get("storageEngine").toString();
return StorageManagerFactory.getVariantStorageManager(storageEngine).getDBAdaptor(dbName, new ObjectMap());
}
@Override
public void setDataWriter(DataWriter dataWriter) {
dbAdaptor.setDataWriter(dataWriter);
}
@Override
public QueryResult<Variant> getAllVariants(QueryOptions options) {
try {
checkQueryOptions(options);
} catch (Exception e) {
return queryError("getAllVariants", e);
}
return dbAdaptor.getAllVariants(options);
}
private void checkQueryOptions(QueryOptions options) throws CatalogException {
Map<Integer, Study> studiesMap = getStudiesMap(options);
Map<Integer, File> filesMap = getFilesMap(options);
checkFiles(filesMap.values());
}
@Override
public QueryResult<Variant> getVariantById(String id, QueryOptions options) {
try {
checkQueryOptions(options);
} catch (Exception e) {
return queryError("getAllVariants", e);
}
return dbAdaptor.getVariantById(id, options);
}
@Override
public List<QueryResult<Variant>> getAllVariantsByIdList(List<String> idList, QueryOptions options) {
try {
checkQueryOptions(options);
} catch (Exception e) {
return Collections.singletonList(this.<Variant>queryError("getAllVariants", e));
}
return dbAdaptor.getAllVariantsByIdList(idList, options);
}
@Override
public QueryResult<Variant> getAllVariantsByRegion(Region region, QueryOptions options) {
try {
checkQueryOptions(options);
} catch (Exception e) {
return queryError("getAllVariants", e);
}
return dbAdaptor.getAllVariantsByRegion(region, options);
}
@Override
public List<QueryResult<Variant>> getAllVariantsByRegionList(List<Region> regionList, QueryOptions options) {
try {
checkQueryOptions(options);
} catch (Exception e) {
e.printStackTrace();
return Collections.singletonList(this.<Variant>queryError("getAllVariants", e));
}
return dbAdaptor.getAllVariantsByRegionList(regionList, options);
}
@Override
public QueryResult getVariantFrequencyByRegion(Region region, QueryOptions options) {
try {
checkQueryOptions(options);
} catch (Exception e) {
return this.<Variant>queryError("getAllVariants", e);
}
return dbAdaptor.getVariantFrequencyByRegion(region, options);
}
@Override
public QueryResult groupBy(String field, QueryOptions options) {
return null;
}
@Override
public QueryResult getAllVariantsByGene(String geneName, QueryOptions options) {
return null;
}
@Deprecated
@Override
public QueryResult getMostAffectedGenes(int numGenes, QueryOptions options) {
return null;
}
@Override
public VariantSourceDBAdaptor getVariantSourceDBAdaptor() {
return null;
}
@Override
public VariantDBIterator iterator() {
return null;
}
@Override
public VariantDBIterator iterator(QueryOptions options) {
return null;
}
@Override
public QueryResult updateAnnotations(List<VariantAnnotation> variantAnnotations, QueryOptions queryOptions) {
return null;
}
@Override
public QueryResult updateStats(List<VariantStatsWrapper> variantStatsWrappers, QueryOptions queryOptions) {
return null;
}
@Override
public boolean close() {
return false;
}
//AuxMethods
private Map<Integer, File> getFilesMap(QueryOptions options) throws CatalogException {
String sessionId = options.getString("sessionId");
Object files = options.get(VariantDBAdaptor.FILES);
List<Integer> fileIds = getIntegerList(files);
return getFilesMap(fileIds, sessionId);
}
private Map<Integer, Study> getStudiesMap(QueryOptions options) throws CatalogException {
String sessionId = options.getString("sessionId");
Object files = options.get(VariantDBAdaptor.STUDIES);
List<Integer> fileIds = getIntegerList(files);
return getStudiesMap(fileIds, sessionId);
}
private List<Integer> getIntegerList(Object objedt) {
List<Integer> list = new LinkedList<>();
if (objedt == null) {
return Collections.emptyList();
} else if (objedt instanceof List) {
for (Object o : ((List) objedt)) {
list.add(Integer.parseInt("" + o));
}
} else {
for (String s : objedt.toString().split(",")) {
list.add(Integer.parseInt(s));
}
}
return list;
}
private Map<Integer, File> getFilesMap(List<Integer> files, String sessionId) throws CatalogException {
Map<Integer, File> fileMap;
fileMap = new HashMap<>();
for (Integer fileId : files) {
QueryResult<File> fileQueryResult = catalogManager.getFile(fileId, sessionId);
File file = fileQueryResult.getResult().get(0);
fileMap.put(fileId, file);
}
return fileMap;
}
private Map<Integer, Study> getStudiesMap(List<Integer> studies, String sessionId) throws CatalogException {
Map<Integer, Study> studyMap;
QueryOptions options = new QueryOptions("include", Collections.singletonList("projects.studies.id"));
studyMap = new HashMap<>();
for (Integer studyId : studies) {
QueryResult<Study> fileQueryResult = catalogManager.getStudy(studyId, sessionId, options);
Study s = fileQueryResult.getResult().get(0);
studyMap.put(studyId, s);
}
return studyMap;
}
private void checkFiles(Collection<File> values) throws CatalogException {
for (File file : values) {
if (!file.getType().equals(File.Type.INDEX)) {
throw new CatalogException("Expected file type = INDEX");
} else if (!file.getBioformat().equals(File.Bioformat.VARIANT)) {
throw new CatalogException("Expected file bioformat = VARIANT");
}
}
}
private <T> QueryResult<T> queryError(String id, Exception e) {
return new QueryResult<T>(id, 0, 0, 0, "", e.getMessage(), Collections.<T>emptyList());
}
// private QueryResult queryError(String id, Exception e) {
// return new QueryResult(id, 0, 0, 0, "", e.getMessage(), Collections.emptyList());
// }
// DEPRECATED METHODS
@Deprecated
@Override
public QueryResult getAllVariantsByRegionAndStudies(Region region, List<String> studyIds, QueryOptions options) {
throw new UnsupportedOperationException("Deprecated method");
}
@Deprecated
@Override
public QueryResult getLeastAffectedGenes(int numGenes, QueryOptions options) {
throw new UnsupportedOperationException("Deprecated method");
}
@Deprecated
@Override
public QueryResult getTopConsequenceTypes(int numConsequenceTypes, QueryOptions options) {
throw new UnsupportedOperationException("Deprecated method");
}
@Deprecated
@Override
public QueryResult getBottomConsequenceTypes(int numConsequenceTypes, QueryOptions options) {
throw new UnsupportedOperationException("Deprecated method");
}
}
| opencga-analysis/src/main/java/org/opencb/opencga/analysis/storage/variant/CatalogVariantDBAdaptor.java | package org.opencb.opencga.analysis.storage.variant;
import org.opencb.biodata.models.feature.Region;
import org.opencb.biodata.models.variant.Variant;
import org.opencb.biodata.models.variant.annotation.VariantAnnotation;
import org.opencb.commons.io.DataWriter;
import org.opencb.datastore.core.ObjectMap;
import org.opencb.datastore.core.QueryOptions;
import org.opencb.datastore.core.QueryResult;
import org.opencb.opencga.catalog.CatalogException;
import org.opencb.opencga.catalog.CatalogManager;
import org.opencb.opencga.catalog.beans.File;
import org.opencb.opencga.catalog.beans.Study;
import org.opencb.opencga.storage.core.StorageManagerFactory;
import org.opencb.opencga.storage.core.variant.adaptors.VariantDBAdaptor;
import org.opencb.opencga.storage.core.variant.adaptors.VariantDBIterator;
import org.opencb.opencga.storage.core.variant.adaptors.VariantSourceDBAdaptor;
import java.util.*;
/**
* Created by hpccoll1 on 13/02/15.
*/
//public class CatalogVariantDBAdaptor {}
public class CatalogVariantDBAdaptor implements VariantDBAdaptor {
private final CatalogManager catalogManager;
private final VariantDBAdaptor dbAdaptor;
public CatalogVariantDBAdaptor(CatalogManager catalogManager, VariantDBAdaptor dbAdaptor) {
this.catalogManager = catalogManager;
this.dbAdaptor = dbAdaptor;
}
public CatalogVariantDBAdaptor(CatalogManager catalogManager, String fileId, String sessionId) throws CatalogException, IllegalAccessException, InstantiationException, ClassNotFoundException {
this.catalogManager = catalogManager;
this.dbAdaptor = buildBAdaptor(catalogManager, fileId, sessionId);
}
private static VariantDBAdaptor buildBAdaptor(CatalogManager catalogManager, String fileId, String sessionId) throws CatalogException, ClassNotFoundException, IllegalAccessException, InstantiationException {
int id = catalogManager.getFileId(fileId);
File file = catalogManager.getFile(id, sessionId).getResult().get(0);
String dbName = file.getAttributes().get("dbName").toString();
String storageEngine = file.getAttributes().get("storageEngine").toString();
return StorageManagerFactory.getVariantStorageManager(storageEngine).getDBAdaptor(dbName, new ObjectMap());
}
@Override
public void setDataWriter(DataWriter dataWriter) {
dbAdaptor.setDataWriter(dataWriter);
}
@Override
public QueryResult<Variant> getAllVariants(QueryOptions options) {
try {
checkQueryOptions(options);
} catch (Exception e) {
return queryError("getAllVariants", e);
}
return dbAdaptor.getAllVariants(options);
}
private void checkQueryOptions(QueryOptions options) throws CatalogException {
Map<Integer, Study> studiesMap = getStudiesMap(options);
Map<Integer, File> filesMap = getFilesMap(options);
checkFiles(filesMap.values());
}
@Override
public QueryResult<Variant> getVariantById(String id, QueryOptions options) {
try {
checkQueryOptions(options);
} catch (Exception e) {
return queryError("getAllVariants", e);
}
return dbAdaptor.getVariantById(id, options);
}
@Override
public List<QueryResult<Variant>> getAllVariantsByIdList(List<String> idList, QueryOptions options) {
try {
checkQueryOptions(options);
} catch (Exception e) {
return Collections.singletonList(this.<Variant>queryError("getAllVariants", e));
}
return dbAdaptor.getAllVariantsByIdList(idList, options);
}
@Override
public QueryResult<Variant> getAllVariantsByRegion(Region region, QueryOptions options) {
try {
checkQueryOptions(options);
} catch (Exception e) {
return queryError("getAllVariants", e);
}
return dbAdaptor.getAllVariantsByRegion(region, options);
}
@Override
public List<QueryResult<Variant>> getAllVariantsByRegionList(List<Region> regionList, QueryOptions options) {
try {
checkQueryOptions(options);
} catch (Exception e) {
e.printStackTrace();
return Collections.singletonList(this.<Variant>queryError("getAllVariants", e));
}
return dbAdaptor.getAllVariantsByRegionList(regionList, options);
}
@Override
public QueryResult getVariantFrequencyByRegion(Region region, QueryOptions options) {
try {
checkQueryOptions(options);
} catch (Exception e) {
return this.<Variant>queryError("getAllVariants", e);
}
return dbAdaptor.getVariantFrequencyByRegion(region, options);
}
@Override
public QueryResult groupBy(String field, QueryOptions options) {
return null;
}
@Override
public QueryResult getAllVariantsByGene(String geneName, QueryOptions options) {
return null;
}
@Deprecated
@Override
public QueryResult getMostAffectedGenes(int numGenes, QueryOptions options) {
return null;
}
@Override
public VariantSourceDBAdaptor getVariantSourceDBAdaptor() {
return null;
}
@Override
public VariantDBIterator iterator() {
return null;
}
@Override
public VariantDBIterator iterator(QueryOptions options) {
return null;
}
@Override
public QueryResult updateAnnotations(List<VariantAnnotation> variantAnnotations, QueryOptions queryOptions) {
return null;
}
@Override
public boolean close() {
return false;
}
//AuxMethods
private Map<Integer, File> getFilesMap(QueryOptions options) throws CatalogException {
String sessionId = options.getString("sessionId");
Object files = options.get(VariantDBAdaptor.FILES);
List<Integer> fileIds = getIntegerList(files);
return getFilesMap(fileIds, sessionId);
}
private Map<Integer, Study> getStudiesMap(QueryOptions options) throws CatalogException {
String sessionId = options.getString("sessionId");
Object files = options.get(VariantDBAdaptor.STUDIES);
List<Integer> fileIds = getIntegerList(files);
return getStudiesMap(fileIds, sessionId);
}
private List<Integer> getIntegerList(Object objedt) {
List<Integer> list = new LinkedList<>();
if (objedt == null) {
return Collections.emptyList();
} else if (objedt instanceof List) {
for (Object o : ((List) objedt)) {
list.add(Integer.parseInt("" + o));
}
} else {
for (String s : objedt.toString().split(",")) {
list.add(Integer.parseInt(s));
}
}
return list;
}
private Map<Integer, File> getFilesMap(List<Integer> files, String sessionId) throws CatalogException {
Map<Integer, File> fileMap;
fileMap = new HashMap<>();
for (Integer fileId : files) {
QueryResult<File> fileQueryResult = catalogManager.getFile(fileId, sessionId);
File file = fileQueryResult.getResult().get(0);
fileMap.put(fileId, file);
}
return fileMap;
}
private Map<Integer, Study> getStudiesMap(List<Integer> studies, String sessionId) throws CatalogException {
Map<Integer, Study> studyMap;
QueryOptions options = new QueryOptions("include", Collections.singletonList("projects.studies.id"));
studyMap = new HashMap<>();
for (Integer studyId : studies) {
QueryResult<Study> fileQueryResult = catalogManager.getStudy(studyId, sessionId, options);
Study s = fileQueryResult.getResult().get(0);
studyMap.put(studyId, s);
}
return studyMap;
}
private void checkFiles(Collection<File> values) throws CatalogException {
for (File file : values) {
if (!file.getType().equals(File.Type.INDEX)) {
throw new CatalogException("Expected file type = INDEX");
} else if (!file.getBioformat().equals(File.Bioformat.VARIANT)) {
throw new CatalogException("Expected file bioformat = VARIANT");
}
}
}
private <T> QueryResult<T> queryError(String id, Exception e) {
return new QueryResult<T>(id, 0, 0, 0, "", e.getMessage(), Collections.<T>emptyList());
}
// private QueryResult queryError(String id, Exception e) {
// return new QueryResult(id, 0, 0, 0, "", e.getMessage(), Collections.emptyList());
// }
// DEPRECATED METHODS
@Deprecated
@Override
public QueryResult getAllVariantsByRegionAndStudies(Region region, List<String> studyIds, QueryOptions options) {
throw new UnsupportedOperationException("Deprecated method");
}
@Deprecated
@Override
public QueryResult getLeastAffectedGenes(int numGenes, QueryOptions options) {
throw new UnsupportedOperationException("Deprecated method");
}
@Deprecated
@Override
public QueryResult getTopConsequenceTypes(int numConsequenceTypes, QueryOptions options) {
throw new UnsupportedOperationException("Deprecated method");
}
@Deprecated
@Override
public QueryResult getBottomConsequenceTypes(int numConsequenceTypes, QueryOptions options) {
throw new UnsupportedOperationException("Deprecated method");
}
}
| storage-catalog: minnor changes
| opencga-analysis/src/main/java/org/opencb/opencga/analysis/storage/variant/CatalogVariantDBAdaptor.java | storage-catalog: minnor changes | <ide><path>pencga-analysis/src/main/java/org/opencb/opencga/analysis/storage/variant/CatalogVariantDBAdaptor.java
<ide> import org.opencb.opencga.catalog.CatalogManager;
<ide> import org.opencb.opencga.catalog.beans.File;
<ide> import org.opencb.opencga.catalog.beans.Study;
<add>import org.opencb.opencga.storage.core.StorageManagerException;
<ide> import org.opencb.opencga.storage.core.StorageManagerFactory;
<ide> import org.opencb.opencga.storage.core.variant.adaptors.VariantDBAdaptor;
<ide> import org.opencb.opencga.storage.core.variant.adaptors.VariantDBIterator;
<ide> import org.opencb.opencga.storage.core.variant.adaptors.VariantSourceDBAdaptor;
<add>import org.opencb.opencga.storage.core.variant.stats.VariantStatsWrapper;
<ide>
<ide> import java.util.*;
<ide>
<ide> this.dbAdaptor = dbAdaptor;
<ide> }
<ide>
<del> public CatalogVariantDBAdaptor(CatalogManager catalogManager, String fileId, String sessionId) throws CatalogException, IllegalAccessException, InstantiationException, ClassNotFoundException {
<add> public CatalogVariantDBAdaptor(CatalogManager catalogManager, String fileId, String sessionId) throws CatalogException, IllegalAccessException, InstantiationException, ClassNotFoundException, StorageManagerException {
<ide> this.catalogManager = catalogManager;
<ide> this.dbAdaptor = buildBAdaptor(catalogManager, fileId, sessionId);
<ide> }
<ide>
<del> private static VariantDBAdaptor buildBAdaptor(CatalogManager catalogManager, String fileId, String sessionId) throws CatalogException, ClassNotFoundException, IllegalAccessException, InstantiationException {
<add> private static VariantDBAdaptor buildBAdaptor(CatalogManager catalogManager, String fileId, String sessionId) throws CatalogException, ClassNotFoundException, IllegalAccessException, InstantiationException, StorageManagerException {
<ide> int id = catalogManager.getFileId(fileId);
<ide> File file = catalogManager.getFile(id, sessionId).getResult().get(0);
<ide> String dbName = file.getAttributes().get("dbName").toString();
<ide>
<ide> @Override
<ide> public QueryResult updateAnnotations(List<VariantAnnotation> variantAnnotations, QueryOptions queryOptions) {
<add> return null;
<add> }
<add>
<add> @Override
<add> public QueryResult updateStats(List<VariantStatsWrapper> variantStatsWrappers, QueryOptions queryOptions) {
<ide> return null;
<ide> }
<ide> |
|
Java | apache-2.0 | 8ff1ac59e0bb49a40c07cf785c6505e55ff41386 | 0 | spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework | /*
* Copyright 2002-2020 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.util;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* Miscellaneous methods for calculating digests.
*
* <p>Mainly for internal use within the framework; consider
* <a href="https://commons.apache.org/codec/">Apache Commons Codec</a>
* for a more comprehensive suite of digest utilities.
*
* @author Arjen Poutsma
* @author Juergen Hoeller
* @author Craig Andrews
* @since 3.0
*/
public abstract class DigestUtils {
private static final String MD5_ALGORITHM_NAME = "MD5";
private static final char[] HEX_CHARS =
{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
/**
* Calculate the MD5 digest of the given bytes.
* @param bytes the bytes to calculate the digest over
* @return the digest
*/
public static byte[] md5Digest(byte[] bytes) {
return digest(MD5_ALGORITHM_NAME, bytes);
}
/**
* Calculate the MD5 digest of the given stream.
* <p>This method does <strong>not</strong> close the input stream.
* @param inputStream the InputStream to calculate the digest over
* @return the digest
* @since 4.2
*/
public static byte[] md5Digest(InputStream inputStream) throws IOException {
return digest(MD5_ALGORITHM_NAME, inputStream);
}
/**
* Return a hexadecimal string representation of the MD5 digest of the given bytes.
* @param bytes the bytes to calculate the digest over
* @return a hexadecimal digest string
*/
public static String md5DigestAsHex(byte[] bytes) {
return digestAsHexString(MD5_ALGORITHM_NAME, bytes);
}
/**
* Return a hexadecimal string representation of the MD5 digest of the given stream.
* <p>This method does <strong>not</strong> close the input stream.
* @param inputStream the InputStream to calculate the digest over
* @return a hexadecimal digest string
* @since 4.2
*/
public static String md5DigestAsHex(InputStream inputStream) throws IOException {
return digestAsHexString(MD5_ALGORITHM_NAME, inputStream);
}
/**
* Append a hexadecimal string representation of the MD5 digest of the given
* bytes to the given {@link StringBuilder}.
* @param bytes the bytes to calculate the digest over
* @param builder the string builder to append the digest to
* @return the given string builder
*/
public static StringBuilder appendMd5DigestAsHex(byte[] bytes, StringBuilder builder) {
return appendDigestAsHex(MD5_ALGORITHM_NAME, bytes, builder);
}
/**
* Append a hexadecimal string representation of the MD5 digest of the given
* inputStream to the given {@link StringBuilder}.
* <p>This method does <strong>not</strong> close the input stream.
* @param inputStream the inputStream to calculate the digest over
* @param builder the string builder to append the digest to
* @return the given string builder
* @since 4.2
*/
public static StringBuilder appendMd5DigestAsHex(InputStream inputStream, StringBuilder builder) throws IOException {
return appendDigestAsHex(MD5_ALGORITHM_NAME, inputStream, builder);
}
/**
* Create a new {@link MessageDigest} with the given algorithm.
* <p>Necessary because {@code MessageDigest} is not thread-safe.
*/
private static MessageDigest getDigest(String algorithm) {
try {
return MessageDigest.getInstance(algorithm);
}
catch (NoSuchAlgorithmException ex) {
throw new IllegalStateException("Could not find MessageDigest with algorithm \"" + algorithm + "\"", ex);
}
}
private static byte[] digest(String algorithm, byte[] bytes) {
return getDigest(algorithm).digest(bytes);
}
private static byte[] digest(String algorithm, InputStream inputStream) throws IOException {
MessageDigest messageDigest = getDigest(algorithm);
if (inputStream instanceof UpdateMessageDigestInputStream){
((UpdateMessageDigestInputStream) inputStream).updateMessageDigest(messageDigest);
return messageDigest.digest();
}
else {
final byte[] buffer = new byte[StreamUtils.BUFFER_SIZE];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
messageDigest.update(buffer, 0, bytesRead);
}
return messageDigest.digest();
}
}
private static String digestAsHexString(String algorithm, byte[] bytes) {
char[] hexDigest = digestAsHexChars(algorithm, bytes);
return new String(hexDigest);
}
private static String digestAsHexString(String algorithm, InputStream inputStream) throws IOException {
char[] hexDigest = digestAsHexChars(algorithm, inputStream);
return new String(hexDigest);
}
private static StringBuilder appendDigestAsHex(String algorithm, byte[] bytes, StringBuilder builder) {
char[] hexDigest = digestAsHexChars(algorithm, bytes);
return builder.append(hexDigest);
}
private static StringBuilder appendDigestAsHex(String algorithm, InputStream inputStream, StringBuilder builder)
throws IOException {
char[] hexDigest = digestAsHexChars(algorithm, inputStream);
return builder.append(hexDigest);
}
private static char[] digestAsHexChars(String algorithm, byte[] bytes) {
byte[] digest = digest(algorithm, bytes);
return encodeHex(digest);
}
private static char[] digestAsHexChars(String algorithm, InputStream inputStream) throws IOException {
byte[] digest = digest(algorithm, inputStream);
return encodeHex(digest);
}
private static char[] encodeHex(byte[] bytes) {
char[] chars = new char[32];
for (int i = 0; i < chars.length; i = i + 2) {
byte b = bytes[i / 2];
chars[i] = HEX_CHARS[(b >>> 0x4) & 0xf];
chars[i + 1] = HEX_CHARS[b & 0xf];
}
return chars;
}
}
| spring-core/src/main/java/org/springframework/util/DigestUtils.java | /*
* Copyright 2002-2020 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.util;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* Miscellaneous methods for calculating digests.
*
* <p>Mainly for internal use within the framework; consider
* <a href="https://commons.apache.org/codec/">Apache Commons Codec</a>
* for a more comprehensive suite of digest utilities.
*
* @author Arjen Poutsma
* @author Juergen Hoeller
* @author Craig Andrews
* @since 3.0
*/
public abstract class DigestUtils {
private static final String MD5_ALGORITHM_NAME = "MD5";
private static final char[] HEX_CHARS =
{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
/**
* Calculate the MD5 digest of the given bytes.
* @param bytes the bytes to calculate the digest over
* @return the digest
*/
public static byte[] md5Digest(byte[] bytes) {
return digest(MD5_ALGORITHM_NAME, bytes);
}
/**
* Calculate the MD5 digest of the given stream. This method does
* <strong>not</strong> close the input stream.
* @param inputStream the InputStream to calculate the digest over
* @return the digest
* @since 4.2
*/
public static byte[] md5Digest(InputStream inputStream) throws IOException {
return digest(MD5_ALGORITHM_NAME, inputStream);
}
/**
* Return a hexadecimal string representation of the MD5 digest of the given bytes.
* @param bytes the bytes to calculate the digest over
* @return a hexadecimal digest string
*/
public static String md5DigestAsHex(byte[] bytes) {
return digestAsHexString(MD5_ALGORITHM_NAME, bytes);
}
/**
* Return a hexadecimal string representation of the MD5 digest of the given stream.
* This method does <strong>not</strong> close the input stream.
* @param inputStream the InputStream to calculate the digest over
* @return a hexadecimal digest string
* @since 4.2
*/
public static String md5DigestAsHex(InputStream inputStream) throws IOException {
return digestAsHexString(MD5_ALGORITHM_NAME, inputStream);
}
/**
* Append a hexadecimal string representation of the MD5 digest of the given
* bytes to the given {@link StringBuilder}.
* @param bytes the bytes to calculate the digest over
* @param builder the string builder to append the digest to
* @return the given string builder
*/
public static StringBuilder appendMd5DigestAsHex(byte[] bytes, StringBuilder builder) {
return appendDigestAsHex(MD5_ALGORITHM_NAME, bytes, builder);
}
/**
* Append a hexadecimal string representation of the MD5 digest of the given
* inputStream to the given {@link StringBuilder}. This method does
* <strong>not</strong> close the input stream.
* @param inputStream the inputStream to calculate the digest over
* @param builder the string builder to append the digest to
* @return the given string builder
* @since 4.2
*/
public static StringBuilder appendMd5DigestAsHex(InputStream inputStream, StringBuilder builder) throws IOException {
return appendDigestAsHex(MD5_ALGORITHM_NAME, inputStream, builder);
}
/**
* Create a new {@link MessageDigest} with the given algorithm.
* Necessary because {@code MessageDigest} is not thread-safe.
*/
private static MessageDigest getDigest(String algorithm) {
try {
return MessageDigest.getInstance(algorithm);
}
catch (NoSuchAlgorithmException ex) {
throw new IllegalStateException("Could not find MessageDigest with algorithm \"" + algorithm + "\"", ex);
}
}
private static byte[] digest(String algorithm, byte[] bytes) {
return getDigest(algorithm).digest(bytes);
}
private static byte[] digest(String algorithm, InputStream inputStream) throws IOException {
MessageDigest messageDigest = getDigest(algorithm);
if (inputStream instanceof UpdateMessageDigestInputStream){
((UpdateMessageDigestInputStream) inputStream).updateMessageDigest(messageDigest);
return messageDigest.digest();
}
else {
final byte[] buffer = new byte[StreamUtils.BUFFER_SIZE];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
messageDigest.update(buffer, 0, bytesRead);
}
return messageDigest.digest();
}
}
private static String digestAsHexString(String algorithm, byte[] bytes) {
char[] hexDigest = digestAsHexChars(algorithm, bytes);
return new String(hexDigest);
}
private static String digestAsHexString(String algorithm, InputStream inputStream) throws IOException {
char[] hexDigest = digestAsHexChars(algorithm, inputStream);
return new String(hexDigest);
}
private static StringBuilder appendDigestAsHex(String algorithm, byte[] bytes, StringBuilder builder) {
char[] hexDigest = digestAsHexChars(algorithm, bytes);
return builder.append(hexDigest);
}
private static StringBuilder appendDigestAsHex(String algorithm, InputStream inputStream, StringBuilder builder)
throws IOException {
char[] hexDigest = digestAsHexChars(algorithm, inputStream);
return builder.append(hexDigest);
}
private static char[] digestAsHexChars(String algorithm, byte[] bytes) {
byte[] digest = digest(algorithm, bytes);
return encodeHex(digest);
}
private static char[] digestAsHexChars(String algorithm, InputStream inputStream) throws IOException {
byte[] digest = digest(algorithm, inputStream);
return encodeHex(digest);
}
private static char[] encodeHex(byte[] bytes) {
char[] chars = new char[32];
for (int i = 0; i < chars.length; i = i + 2) {
byte b = bytes[i / 2];
chars[i] = HEX_CHARS[(b >>> 0x4) & 0xf];
chars[i + 1] = HEX_CHARS[b & 0xf];
}
return chars;
}
}
| Polishing
| spring-core/src/main/java/org/springframework/util/DigestUtils.java | Polishing | <ide><path>pring-core/src/main/java/org/springframework/util/DigestUtils.java
<ide> }
<ide>
<ide> /**
<del> * Calculate the MD5 digest of the given stream. This method does
<del> * <strong>not</strong> close the input stream.
<add> * Calculate the MD5 digest of the given stream.
<add> * <p>This method does <strong>not</strong> close the input stream.
<ide> * @param inputStream the InputStream to calculate the digest over
<ide> * @return the digest
<ide> * @since 4.2
<ide>
<ide> /**
<ide> * Return a hexadecimal string representation of the MD5 digest of the given stream.
<del> * This method does <strong>not</strong> close the input stream.
<add> * <p>This method does <strong>not</strong> close the input stream.
<ide> * @param inputStream the InputStream to calculate the digest over
<ide> * @return a hexadecimal digest string
<ide> * @since 4.2
<ide>
<ide> /**
<ide> * Append a hexadecimal string representation of the MD5 digest of the given
<del> * inputStream to the given {@link StringBuilder}. This method does
<del> * <strong>not</strong> close the input stream.
<add> * inputStream to the given {@link StringBuilder}.
<add> * <p>This method does <strong>not</strong> close the input stream.
<ide> * @param inputStream the inputStream to calculate the digest over
<ide> * @param builder the string builder to append the digest to
<ide> * @return the given string builder
<ide>
<ide> /**
<ide> * Create a new {@link MessageDigest} with the given algorithm.
<del> * Necessary because {@code MessageDigest} is not thread-safe.
<add> * <p>Necessary because {@code MessageDigest} is not thread-safe.
<ide> */
<ide> private static MessageDigest getDigest(String algorithm) {
<ide> try { |
|
Java | apache-2.0 | dee9471b09d6933580fa746e1d57101a08ed4232 | 0 | apache/geronimo,apache/geronimo,apache/geronimo,apache/geronimo | /**
*
* 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.geronimo.openejb;
import java.util.Set;
import java.util.ArrayList;
import java.lang.reflect.Method;
import javax.ejb.EJBHome;
import javax.ejb.EJBLocalHome;
import javax.ejb.EJBObject;
import javax.naming.Context;
import javax.security.auth.Subject;
import org.apache.geronimo.connector.outbound.connectiontracking.TrackedConnectionAssociator;
import org.apache.geronimo.management.EJB;
import org.apache.geronimo.security.ContextManager;
import org.apache.openejb.BeanType;
import org.apache.openejb.Container;
import org.apache.openejb.InterfaceType;
import org.apache.openejb.core.CoreDeploymentInfo;
import org.apache.openejb.core.ivm.EjbObjectProxyHandler;
public class EjbDeployment implements EJB {
private final String objectName;
private final String deploymentId;
private final String ejbName;
private final String homeInterfaceName;
private final String remoteInterfaceName;
private final String localHomeInterfaceName;
private final String localInterfaceName;
private final String serviceEndpointInterfaceName;
private final String beanClassName;
private final ClassLoader classLoader;
private final boolean securityEnabled;
private final Subject defaultSubject;
private final Subject runAs;
private final Context componentContext;
// connector stuff
private final Set unshareableResources;
private final Set applicationManagedSecurityResources;
private final TrackedConnectionAssociator trackedConnectionAssociator;
private final OpenEjbSystem openEjbSystem;
private CoreDeploymentInfo deploymentInfo;
private Context javaCompSubContext;
public EjbDeployment() {
this(null, null, null, null, null, null, null, null, null, null,
false, null, null, null, null, null, null, null);
}
public EjbDeployment(String objectName,
String deploymentId,
String ejbName,
String homeInterfaceName,
String remoteInterfaceName,
String localHomeInterfaceName,
String localInterfaceName,
String serviceEndpointInterfaceName,
String beanClassName,
ClassLoader classLoader,
boolean securityEnabled,
Subject defaultSubject,
Subject runAs,
Context componentContext,
Set unshareableResources,
Set applicationManagedSecurityResources,
TrackedConnectionAssociator trackedConnectionAssociator,
OpenEjbSystem openEjbSystem) {
this.objectName = objectName;
this.deploymentId = deploymentId;
this.ejbName = ejbName;
this.homeInterfaceName = homeInterfaceName;
this.remoteInterfaceName = remoteInterfaceName;
this.localHomeInterfaceName = localHomeInterfaceName;
this.localInterfaceName = localInterfaceName;
this.serviceEndpointInterfaceName = serviceEndpointInterfaceName;
this.beanClassName = beanClassName;
this.classLoader = classLoader;
this.securityEnabled = securityEnabled;
this.defaultSubject = defaultSubject;
this.runAs = runAs;
this.componentContext = componentContext;
this.unshareableResources = unshareableResources;
this.applicationManagedSecurityResources = applicationManagedSecurityResources;
this.trackedConnectionAssociator = trackedConnectionAssociator;
this.openEjbSystem = openEjbSystem;
}
public CoreDeploymentInfo getDeploymentInfo() {
return deploymentInfo;
}
public String getDeploymentId() {
return deploymentId;
}
public String getEjbName() {
return ejbName;
}
public String getHomeInterfaceName() {
return homeInterfaceName;
}
public String getRemoteInterfaceName() {
return remoteInterfaceName;
}
public String getLocalHomeInterfaceName() {
return localHomeInterfaceName;
}
public String getLocalInterfaceName() {
return localInterfaceName;
}
public String getServiceEndpointInterfaceName() {
return serviceEndpointInterfaceName;
}
public String getBeanClassName() {
return beanClassName;
}
public ClassLoader getClassLoader() {
return classLoader;
}
public boolean isSecurityEnabled() {
return securityEnabled;
}
public Subject getDefaultSubject() {
return defaultSubject;
}
public Subject getRunAs() {
return runAs;
}
public Context getComponentContext() {
return javaCompSubContext;
}
public Set getUnshareableResources() {
return unshareableResources;
}
public Set getApplicationManagedSecurityResources() {
return applicationManagedSecurityResources;
}
public TrackedConnectionAssociator getTrackedConnectionAssociator() {
return trackedConnectionAssociator;
}
public EJBHome getEJBHome() {
return deploymentInfo.getEJBHome();
}
public EJBLocalHome getEJBLocalHome() {
return deploymentInfo.getEJBLocalHome();
}
public Object getBusinessLocalHome() {
return deploymentInfo.getBusinessLocalHome();
}
public Object getBusinessRemoteHome() {
return deploymentInfo.getBusinessRemoteHome();
}
public EJBObject getEjbObject(Object primaryKey) {
return (EJBObject) EjbObjectProxyHandler.createProxy(deploymentInfo, primaryKey, InterfaceType.EJB_HOME);
}
public Class getHomeInterface() {
return deploymentInfo.getHomeInterface();
}
public Class getRemoteInterface() {
return deploymentInfo.getRemoteInterface();
}
public Class getLocalHomeInterface() {
return deploymentInfo.getLocalHomeInterface();
}
public Class getLocalInterface() {
return deploymentInfo.getLocalInterface();
}
public Class getBeanClass() {
return deploymentInfo.getBeanClass();
}
public Class getBusinessLocalInterface() {
return deploymentInfo.getBusinessLocalInterface();
}
public Class getBusinessRemoteInterface() {
return deploymentInfo.getBusinessRemoteInterface();
}
public Class getMdbInterface() {
return deploymentInfo.getMdbInterface();
}
public Class getServiceEndpointInterface() {
return deploymentInfo.getServiceEndpointInterface();
}
public BeanType getComponentType() {
return deploymentInfo.getComponentType();
}
public Container getContainer() {
return deploymentInfo.getContainer();
}
public boolean isBeanManagedTransaction() {
return deploymentInfo.isBeanManagedTransaction();
}
public byte getTransactionAttribute(Method method) {
return deploymentInfo.getTransactionAttribute(method);
}
public String getObjectName() {
return objectName;
}
public boolean isStateManageable() {
return true;
}
public boolean isStatisticsProvider() {
return false;
}
public boolean isEventProvider() {
return true;
}
protected void start() throws Exception {
deploymentInfo = (CoreDeploymentInfo) openEjbSystem.getDeploymentInfo(deploymentId);
if (deploymentInfo == null) {
throw new IllegalStateException("Ejb does not exist " + deploymentId);
}
if (defaultSubject != null) {
ContextManager.registerSubject(defaultSubject);
}
if (runAs != null) {
ContextManager.registerSubject(runAs);
}
javaCompSubContext = (Context) deploymentInfo.getJndiEnc().lookup("java:comp");
if (componentContext != null) {
javaCompSubContext.bind("geronimo", componentContext);
}
deploymentInfo.set(EjbDeployment.class, this);
}
protected void stop() {
if (deploymentInfo != null) {
deploymentInfo.set(EjbDeployment.class, null);
deploymentInfo = null;
}
if (defaultSubject != null) {
ContextManager.unregisterSubject(defaultSubject);
}
if (runAs != null) {
ContextManager.unregisterSubject(runAs);
}
}
}
| modules/geronimo-openejb/src/main/java/org/apache/geronimo/openejb/EjbDeployment.java | /**
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.openejb;
import java.util.Set;
import java.util.ArrayList;
import java.lang.reflect.Method;
import javax.ejb.EJBHome;
import javax.ejb.EJBLocalHome;
import javax.ejb.EJBObject;
import javax.naming.Context;
import javax.security.auth.Subject;
import org.apache.geronimo.connector.outbound.connectiontracking.TrackedConnectionAssociator;
import org.apache.geronimo.management.EJB;
import org.apache.geronimo.security.ContextManager;
import org.apache.openejb.BeanType;
import org.apache.openejb.Container;
import org.apache.openejb.ProxyInfo;
import org.apache.openejb.RpcContainer;
import org.apache.openejb.InterfaceType;
import org.apache.openejb.core.CoreDeploymentInfo;
import org.apache.openejb.core.ivm.EjbHomeProxyHandler;
import org.apache.openejb.core.ivm.EjbObjectProxyHandler;
import org.apache.openejb.util.proxy.ProxyManager;
public class EjbDeployment implements EJB {
private final String objectName;
private final String deploymentId;
private final String ejbName;
private final String homeInterfaceName;
private final String remoteInterfaceName;
private final String localHomeInterfaceName;
private final String localInterfaceName;
private final String serviceEndpointInterfaceName;
private final String beanClassName;
private final ClassLoader classLoader;
private final boolean securityEnabled;
private final Subject defaultSubject;
private final Subject runAs;
private final Context componentContext;
// connector stuff
private final Set unshareableResources;
private final Set applicationManagedSecurityResources;
private final TrackedConnectionAssociator trackedConnectionAssociator;
private final OpenEjbSystem openEjbSystem;
private CoreDeploymentInfo deploymentInfo;
private Context javaCompSubContext;
public EjbDeployment() {
this(null, null, null, null, null, null, null, null, null, null,
false, null, null, null, null, null, null, null);
}
public EjbDeployment(String objectName,
String deploymentId,
String ejbName,
String homeInterfaceName,
String remoteInterfaceName,
String localHomeInterfaceName,
String localInterfaceName,
String serviceEndpointInterfaceName,
String beanClassName,
ClassLoader classLoader,
boolean securityEnabled,
Subject defaultSubject,
Subject runAs,
Context componentContext,
Set unshareableResources,
Set applicationManagedSecurityResources,
TrackedConnectionAssociator trackedConnectionAssociator,
OpenEjbSystem openEjbSystem) {
this.objectName = objectName;
this.deploymentId = deploymentId;
this.ejbName = ejbName;
this.homeInterfaceName = homeInterfaceName;
this.remoteInterfaceName = remoteInterfaceName;
this.localHomeInterfaceName = localHomeInterfaceName;
this.localInterfaceName = localInterfaceName;
this.serviceEndpointInterfaceName = serviceEndpointInterfaceName;
this.beanClassName = beanClassName;
this.classLoader = classLoader;
this.securityEnabled = securityEnabled;
this.defaultSubject = defaultSubject;
this.runAs = runAs;
this.componentContext = componentContext;
this.unshareableResources = unshareableResources;
this.applicationManagedSecurityResources = applicationManagedSecurityResources;
this.trackedConnectionAssociator = trackedConnectionAssociator;
this.openEjbSystem = openEjbSystem;
}
public CoreDeploymentInfo getDeploymentInfo() {
return deploymentInfo;
}
public String getDeploymentId() {
return deploymentId;
}
public String getEjbName() {
return ejbName;
}
public String getHomeInterfaceName() {
return homeInterfaceName;
}
public String getRemoteInterfaceName() {
return remoteInterfaceName;
}
public String getLocalHomeInterfaceName() {
return localHomeInterfaceName;
}
public String getLocalInterfaceName() {
return localInterfaceName;
}
public String getServiceEndpointInterfaceName() {
return serviceEndpointInterfaceName;
}
public String getBeanClassName() {
return beanClassName;
}
public ClassLoader getClassLoader() {
return classLoader;
}
public boolean isSecurityEnabled() {
return securityEnabled;
}
public Subject getDefaultSubject() {
return defaultSubject;
}
public Subject getRunAs() {
return runAs;
}
public Context getComponentContext() {
return javaCompSubContext;
}
public Set getUnshareableResources() {
return unshareableResources;
}
public Set getApplicationManagedSecurityResources() {
return applicationManagedSecurityResources;
}
public TrackedConnectionAssociator getTrackedConnectionAssociator() {
return trackedConnectionAssociator;
}
public EJBHome getEJBHome() {
return deploymentInfo.getEJBHome();
}
public EJBLocalHome getEJBLocalHome() {
return deploymentInfo.getEJBLocalHome();
}
public Object getBusinessLocalHome() {
return deploymentInfo.getBusinessLocalHome();
}
public Object getBusinessRemoteHome() {
return deploymentInfo.getBusinessRemoteHome();
}
public EJBObject getEjbObject(Object primaryKey) {
return (EJBObject) EjbObjectProxyHandler.createProxy(deploymentInfo, primaryKey, InterfaceType.EJB_HOME, new ArrayList<Class>());
}
public Class getHomeInterface() {
return deploymentInfo.getHomeInterface();
}
public Class getRemoteInterface() {
return deploymentInfo.getRemoteInterface();
}
public Class getLocalHomeInterface() {
return deploymentInfo.getLocalHomeInterface();
}
public Class getLocalInterface() {
return deploymentInfo.getLocalInterface();
}
public Class getBeanClass() {
return deploymentInfo.getBeanClass();
}
public Class getBusinessLocalInterface() {
return deploymentInfo.getBusinessLocalInterface();
}
public Class getBusinessRemoteInterface() {
return deploymentInfo.getBusinessRemoteInterface();
}
public Class getMdbInterface() {
return deploymentInfo.getMdbInterface();
}
public Class getServiceEndpointInterface() {
return deploymentInfo.getServiceEndpointInterface();
}
public BeanType getComponentType() {
return deploymentInfo.getComponentType();
}
public Container getContainer() {
return deploymentInfo.getContainer();
}
public boolean isBeanManagedTransaction() {
return deploymentInfo.isBeanManagedTransaction();
}
public byte getTransactionAttribute(Method method) {
return deploymentInfo.getTransactionAttribute(method);
}
public String getObjectName() {
return objectName;
}
public boolean isStateManageable() {
return true;
}
public boolean isStatisticsProvider() {
return false;
}
public boolean isEventProvider() {
return true;
}
protected void start() throws Exception {
deploymentInfo = (CoreDeploymentInfo) openEjbSystem.getDeploymentInfo(deploymentId);
if (deploymentInfo == null) {
throw new IllegalStateException("Ejb does not exist " + deploymentId);
}
if (defaultSubject != null) {
ContextManager.registerSubject(defaultSubject);
}
if (runAs != null) {
ContextManager.registerSubject(runAs);
}
javaCompSubContext = (Context) deploymentInfo.getJndiEnc().lookup("java:comp");
if (componentContext != null) {
javaCompSubContext.bind("geronimo", componentContext);
}
deploymentInfo.set(EjbDeployment.class, this);
}
protected void stop() {
if (deploymentInfo != null) {
deploymentInfo.set(EjbDeployment.class, null);
deploymentInfo = null;
}
if (defaultSubject != null) {
ContextManager.unregisterSubject(defaultSubject);
}
if (runAs != null) {
ContextManager.unregisterSubject(runAs);
}
}
}
| Forgot to check this in last night.
git-svn-id: 0d16bf2c240b8111500ec482b35765e5042f5526@529731 13f79535-47bb-0310-9956-ffa450edef68
| modules/geronimo-openejb/src/main/java/org/apache/geronimo/openejb/EjbDeployment.java | Forgot to check this in last night. | <ide><path>odules/geronimo-openejb/src/main/java/org/apache/geronimo/openejb/EjbDeployment.java
<ide> import org.apache.geronimo.security.ContextManager;
<ide> import org.apache.openejb.BeanType;
<ide> import org.apache.openejb.Container;
<del>import org.apache.openejb.ProxyInfo;
<del>import org.apache.openejb.RpcContainer;
<ide> import org.apache.openejb.InterfaceType;
<ide> import org.apache.openejb.core.CoreDeploymentInfo;
<del>import org.apache.openejb.core.ivm.EjbHomeProxyHandler;
<ide> import org.apache.openejb.core.ivm.EjbObjectProxyHandler;
<del>import org.apache.openejb.util.proxy.ProxyManager;
<ide>
<ide> public class EjbDeployment implements EJB {
<ide> private final String objectName;
<ide> private Context javaCompSubContext;
<ide>
<ide> public EjbDeployment() {
<del> this(null, null, null, null, null, null, null, null, null, null,
<add> this(null, null, null, null, null, null, null, null, null, null,
<ide> false, null, null, null, null, null, null, null);
<ide> }
<ide>
<ide> }
<ide>
<ide> public EJBObject getEjbObject(Object primaryKey) {
<del> return (EJBObject) EjbObjectProxyHandler.createProxy(deploymentInfo, primaryKey, InterfaceType.EJB_HOME, new ArrayList<Class>());
<add> return (EJBObject) EjbObjectProxyHandler.createProxy(deploymentInfo, primaryKey, InterfaceType.EJB_HOME);
<ide> }
<ide>
<ide> public Class getHomeInterface() { |
|
Java | apache-2.0 | c3ac60661d3bdb4f72e0c10c62e4b6b60ff8072b | 0 | soulgalore/image-resize-servlet | /******************************************************
* Imagemagick resize servlet
*
*
* Copyright (C) 2012 by Peter Hedenskog (http://peterhedenskog.com)
*
******************************************************
*
* 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.soulgalore.servlet.thumbnail;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
/**
* Image magick backend for creating thumbnails.
*
*/
public class ImageMagickThumbnailCreator implements
Callable<File> {
private final Thumbnail thumbnail;
public ImageMagickThumbnailCreator(Thumbnail thumb) {
thumbnail = thumb;
}
@Override
public File call() throws Exception {
final ProcessBuilder pb = new ProcessBuilder("convert", "-thumbnail",
thumbnail.getImageDimensions(), thumbnail.getOriginalBaseDir()
+ File.separator
+ thumbnail.getOriginalImageNameWithExtension(),
thumbnail.getDestinationDir() + File.separator
+ thumbnail.getImageFileName());
pb.directory(new File(thumbnail.getOriginalBaseDir()));
try {
final Process p = pb.start();
// wait until it's created
p.waitFor();
} catch (IOException e) {
throw e;
}
return new File(thumbnail.getDestinationDir() + File.separator
+ thumbnail.getImageFileName());
}
}
| src/main/java/com/soulgalore/servlet/thumbnail/ImageMagickThumbnailCreator.java | /******************************************************
* Imagemagick resize servlet
*
*
* Copyright (C) 2012 by Peter Hedenskog (http://peterhedenskog.com)
*
******************************************************
*
* 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.soulgalore.servlet.thumbnail;
import java.io.File;
import java.io.IOException;
/**
* Image magick backend for creating thumbnails.
*
*/
public class ImageMagickThumbnailCreator implements ThumbnailCreator {
public ImageMagickThumbnailCreator() {
}
/*
* (non-Javadoc)
*
* @see
* com.soulgalore.servlet.thumbnail.ThumbnailCreator#createThumbnail(com
* .soulgalore.servlet.thumbnail.Thumbnail, java.lang.String,
* java.lang.String)
*/
@Override
public File createThumbnail(Thumbnail thumbnail)
throws InterruptedException, IOException {
final ProcessBuilder pb = new ProcessBuilder("convert", "-thumbnail",
thumbnail.getImageDimensions(), thumbnail.getOriginalBaseDir()
+ File.separator
+ thumbnail.getOriginalImageNameWithExtension(),
thumbnail.getDestinationDir() + File.separator
+ thumbnail.getImageFileName());
pb.directory(new File(thumbnail.getOriginalBaseDir()));
try {
final Process p = pb.start();
// wait until it's created
p.waitFor();
return new File(thumbnail.getDestinationDir() + File.separator
+ thumbnail.getImageFileName());
} catch (IOException e1) {
throw e1;
}
}
}
| now callable | src/main/java/com/soulgalore/servlet/thumbnail/ImageMagickThumbnailCreator.java | now callable | <ide><path>rc/main/java/com/soulgalore/servlet/thumbnail/ImageMagickThumbnailCreator.java
<ide>
<ide> import java.io.File;
<ide> import java.io.IOException;
<add>import java.util.concurrent.Callable;
<add>import java.util.concurrent.ExecutionException;
<ide>
<ide> /**
<ide> * Image magick backend for creating thumbnails.
<ide> *
<ide> */
<del>public class ImageMagickThumbnailCreator implements ThumbnailCreator {
<add>public class ImageMagickThumbnailCreator implements
<add> Callable<File> {
<ide>
<del> public ImageMagickThumbnailCreator() {
<del>
<add> private final Thumbnail thumbnail;
<add>
<add> public ImageMagickThumbnailCreator(Thumbnail thumb) {
<add> thumbnail = thumb;
<ide> }
<ide>
<del> /*
<del> * (non-Javadoc)
<del> *
<del> * @see
<del> * com.soulgalore.servlet.thumbnail.ThumbnailCreator#createThumbnail(com
<del> * .soulgalore.servlet.thumbnail.Thumbnail, java.lang.String,
<del> * java.lang.String)
<del> */
<add>
<ide> @Override
<del> public File createThumbnail(Thumbnail thumbnail)
<del> throws InterruptedException, IOException {
<del>
<add> public File call() throws Exception {
<ide> final ProcessBuilder pb = new ProcessBuilder("convert", "-thumbnail",
<ide> thumbnail.getImageDimensions(), thumbnail.getOriginalBaseDir()
<ide> + File.separator
<ide> final Process p = pb.start();
<ide> // wait until it's created
<ide> p.waitFor();
<del> return new File(thumbnail.getDestinationDir() + File.separator
<del> + thumbnail.getImageFileName());
<ide>
<del> } catch (IOException e1) {
<del> throw e1;
<add> } catch (IOException e) {
<add> throw e;
<ide> }
<add>
<add> return new File(thumbnail.getDestinationDir() + File.separator
<add> + thumbnail.getImageFileName());
<ide> }
<ide> } |
|
Java | apache-2.0 | b75ab9e61227e580a7688ce4d4b04047e26cf4e1 | 0 | marverenic/Jockey,marverenic/Jockey | package com.marverenic.music.data.store;
import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v4.util.ArrayMap;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.marverenic.music.R;
import com.marverenic.music.model.AutoPlaylist;
import com.marverenic.music.model.Playlist;
import com.marverenic.music.model.Song;
import com.marverenic.music.model.playlistrules.AutoPlaylistRule;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subjects.BehaviorSubject;
import timber.log.Timber;
public class LocalPlaylistStore implements PlaylistStore {
private static final String AUTO_PLAYLIST_EXTENSION = ".jpl";
// Used to generate Auto Playlist contents
private MusicStore mMusicStore;
private PlayCountStore mPlayCountStore;
private Context mContext;
private BehaviorSubject<List<Playlist>> mPlaylists;
private Map<Playlist, BehaviorSubject<List<Song>>> mPlaylistContents;
private BehaviorSubject<Boolean> mLoadingState;
public LocalPlaylistStore(Context context, MusicStore musicStore,
PlayCountStore playCountStore) {
mContext = context;
mMusicStore = musicStore;
mPlayCountStore = playCountStore;
mPlaylistContents = new ArrayMap<>();
mLoadingState = BehaviorSubject.create(false);
}
@Override
public void loadPlaylists() {
getPlaylists().take(1).subscribe();
}
@Override
public Observable<Boolean> refresh() {
if (mPlaylists == null) {
return Observable.just(true);
}
mLoadingState.onNext(true);
return MediaStoreUtil.promptPermission(mContext)
.observeOn(Schedulers.io())
.map(granted -> {
if (granted && mPlaylists != null) {
mPlaylists.onNext(getAllPlaylists());
mPlaylistContents.clear();
}
mLoadingState.onNext(false);
return granted;
})
.observeOn(AndroidSchedulers.mainThread());
}
@Override
public Observable<Boolean> isLoading() {
return mLoadingState.asObservable().observeOn(AndroidSchedulers.mainThread());
}
@Override
public Observable<List<Playlist>> getPlaylists() {
if (mPlaylists == null) {
mPlaylists = BehaviorSubject.create();
mLoadingState.onNext(true);
MediaStoreUtil.getPermission(mContext)
.observeOn(Schedulers.io())
.subscribe(granted -> {
if (granted) {
mPlaylists.onNext(getAllPlaylists());
} else {
mPlaylists.onNext(Collections.emptyList());
}
mLoadingState.onNext(false);
}, throwable -> {
Timber.e(throwable, "Failed to query MediaStore for playlists");
});
}
return mPlaylists.asObservable().observeOn(AndroidSchedulers.mainThread());
}
private List<Playlist> getAllPlaylists() {
return MediaStoreUtil.getAllPlaylists(mContext);
}
@Override
public Observable<List<Song>> getSongs(Playlist playlist) {
if (playlist instanceof AutoPlaylist) {
return getAutoPlaylistSongs((AutoPlaylist) playlist);
} else {
return getPlaylistSongs(playlist);
}
}
private Observable<List<Song>> getPlaylistSongs(Playlist playlist) {
BehaviorSubject<List<Song>> subject;
if (mPlaylistContents.containsKey(playlist)) {
subject = mPlaylistContents.get(playlist);
} else {
subject = BehaviorSubject.create(MediaStoreUtil.getPlaylistSongs(mContext, playlist));
mPlaylistContents.put(playlist, subject);
}
return subject.asObservable().observeOn(AndroidSchedulers.mainThread());
}
private Observable<List<Song>> getAutoPlaylistSongs(AutoPlaylist playlist) {
BehaviorSubject<List<Song>> subject;
if (mPlaylistContents.containsKey(playlist)) {
subject = mPlaylistContents.get(playlist);
} else {
subject = BehaviorSubject.create();
mPlaylistContents.put(playlist, subject);
playlist.generatePlaylist(mMusicStore, this, mPlayCountStore)
.subscribe(subject::onNext, subject::onError);
subject.observeOn(Schedulers.io())
.subscribe(contents -> {
editPlaylist(playlist, contents);
}, throwable -> {
Timber.e(throwable, "Failed to save playlist contents");
});
}
return subject.asObservable().observeOn(AndroidSchedulers.mainThread());
}
@Override
public Observable<List<Playlist>> searchForPlaylists(String query) {
if (query == null || query.isEmpty()) {
return Observable.just(Collections.emptyList());
}
return getPlaylists().map(playlists -> {
List<Playlist> filtered = new ArrayList<>();
String lowerCaseQuery = query.toLowerCase();
for (Playlist playlist : playlists) {
if (playlist.getPlaylistName().toLowerCase().contains(lowerCaseQuery)) {
filtered.add(playlist);
}
}
return filtered;
});
}
@Override
public String verifyPlaylistName(String playlistName) {
if (playlistName == null || playlistName.trim().isEmpty()) {
return mContext.getString(R.string.error_hint_empty_playlist);
}
if (MediaStoreUtil.findPlaylistByName(mContext, playlistName) != null) {
return mContext.getString(R.string.error_hint_duplicate_playlist);
}
return null;
}
@Override
public Playlist makePlaylist(String name) {
return makePlaylist(name, null);
}
@Override
public AutoPlaylist makePlaylist(AutoPlaylist playlist) {
Playlist localReference = MediaStoreUtil.createPlaylist(mContext,
playlist.getPlaylistName(), Collections.emptyList());
AutoPlaylist created = new AutoPlaylist.Builder(playlist)
.setId(localReference.getPlaylistId())
.build();
saveAutoPlaylistConfiguration(created);
if (mPlaylists != null && mPlaylists.getValue() != null) {
List<Playlist> updatedPlaylists = new ArrayList<>(mPlaylists.getValue());
updatedPlaylists.add(created);
Collections.sort(updatedPlaylists);
mPlaylists.onNext(updatedPlaylists);
}
return created;
}
@Override
public Playlist makePlaylist(String name, @Nullable List<Song> songs) {
Playlist created = MediaStoreUtil.createPlaylist(mContext, name, songs);
if (mPlaylists != null && mPlaylists.getValue() != null) {
List<Playlist> updated = new ArrayList<>(mPlaylists.getValue());
updated.add(created);
Collections.sort(updated);
mPlaylists.onNext(updated);
}
return created;
}
@Override
public void removePlaylist(Playlist playlist) {
MediaStoreUtil.deletePlaylist(mContext, playlist);
mPlaylistContents.remove(playlist);
if (mPlaylists != null && mPlaylists.getValue() != null) {
List<Playlist> updated = new ArrayList<>(mPlaylists.getValue());
updated.remove(playlist);
mPlaylists.onNext(updated);
}
}
@Override
public void editPlaylist(Playlist playlist, List<Song> newSongs) {
MediaStoreUtil.editPlaylist(mContext, playlist, newSongs);
if (mPlaylistContents.containsKey(playlist)) {
mPlaylistContents.get(playlist).onNext(new ArrayList<>(newSongs));
}
}
@Override
public void editPlaylist(AutoPlaylist replacement) {
saveAutoPlaylistConfiguration(replacement);
if (mPlaylists != null && mPlaylists.getValue() != null) {
List<Playlist> updatedPlaylists = new ArrayList<>(mPlaylists.getValue());
int index = updatedPlaylists.indexOf(replacement);
updatedPlaylists.set(index, replacement);
mPlaylists.onNext(updatedPlaylists);
}
}
private void saveAutoPlaylistConfiguration(AutoPlaylist playlist) {
// Write an initial set of values to the MediaStore so other apps can see this playlist
playlist.generatePlaylist(mMusicStore, this, mPlayCountStore)
.take(1)
.observeOn(Schedulers.io())
.subscribe(contents -> {
editPlaylist(playlist, contents);
// Cache this result in memory
BehaviorSubject<List<Song>> contentsSubject;
if (mPlaylistContents.containsKey(playlist)) {
contentsSubject = mPlaylistContents.get(playlist);
} else {
contentsSubject = BehaviorSubject.create();
mPlaylistContents.put(playlist, contentsSubject);
}
contentsSubject.onNext(contents);
try {
writeAutoPlaylistConfiguration(playlist);
} catch (IOException e) {
Timber.e(e, "Failed to write autoPlaylist configuration");
}
}, throwable -> {
Timber.e(throwable, "makePlaylist: Failed to initialize contents");
});
}
private void writeAutoPlaylistConfiguration(AutoPlaylist playlist) throws IOException {
Gson gson = new GsonBuilder()
.setPrettyPrinting()
.registerTypeAdapter(AutoPlaylistRule.class, new AutoPlaylistRule.RuleTypeAdapter())
.create();
FileWriter writer = null;
try {
String filename = playlist.getPlaylistName() + AUTO_PLAYLIST_EXTENSION;
String fullPath = mContext.getExternalFilesDir(null) + File.separator + filename;
writer = new FileWriter(fullPath);
writer.write(gson.toJson(playlist, AutoPlaylist.class));
} finally {
if (writer != null) {
writer.close();
}
}
}
@Override
public void addToPlaylist(Playlist playlist, Song song) {
MediaStoreUtil.appendToPlaylist(mContext, playlist, song);
if (mPlaylistContents.containsKey(playlist)) {
BehaviorSubject<List<Song>> observableContents = mPlaylistContents.get(playlist);
List<Song> updatedContents = new ArrayList<>(observableContents.getValue());
updatedContents.add(song);
observableContents.onNext(updatedContents);
}
}
@Override
public void addToPlaylist(Playlist playlist, List<Song> songs) {
MediaStoreUtil.appendToPlaylist(mContext, playlist, songs);
if (mPlaylistContents.containsKey(playlist)) {
BehaviorSubject<List<Song>> observableContents = mPlaylistContents.get(playlist);
List<Song> updatedContents = new ArrayList<>(observableContents.getValue());
updatedContents.addAll(songs);
observableContents.onNext(updatedContents);
}
}
}
| app/src/main/java/com/marverenic/music/data/store/LocalPlaylistStore.java | package com.marverenic.music.data.store;
import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v4.util.ArrayMap;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.marverenic.music.R;
import com.marverenic.music.model.AutoPlaylist;
import com.marverenic.music.model.Playlist;
import com.marverenic.music.model.Song;
import com.marverenic.music.model.playlistrules.AutoPlaylistRule;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subjects.BehaviorSubject;
import timber.log.Timber;
public class LocalPlaylistStore implements PlaylistStore {
private static final String AUTO_PLAYLIST_EXTENSION = ".jpl";
// Used to generate Auto Playlist contents
private MusicStore mMusicStore;
private PlayCountStore mPlayCountStore;
private Context mContext;
private BehaviorSubject<List<Playlist>> mPlaylists;
private Map<AutoPlaylist, BehaviorSubject<List<Song>>> mAutoPlaylistSessionContents;
private BehaviorSubject<Boolean> mLoadingState;
public LocalPlaylistStore(Context context, MusicStore musicStore,
PlayCountStore playCountStore) {
mContext = context;
mMusicStore = musicStore;
mPlayCountStore = playCountStore;
mAutoPlaylistSessionContents = new ArrayMap<>();
mLoadingState = BehaviorSubject.create(false);
}
@Override
public void loadPlaylists() {
getPlaylists().take(1).subscribe();
}
@Override
public Observable<Boolean> refresh() {
if (mPlaylists == null) {
return Observable.just(true);
}
mLoadingState.onNext(true);
return MediaStoreUtil.promptPermission(mContext)
.observeOn(Schedulers.io())
.map(granted -> {
if (granted && mPlaylists != null) {
mPlaylists.onNext(getAllPlaylists());
mAutoPlaylistSessionContents.clear();
}
mLoadingState.onNext(false);
return granted;
})
.observeOn(AndroidSchedulers.mainThread());
}
@Override
public Observable<Boolean> isLoading() {
return mLoadingState.asObservable().observeOn(AndroidSchedulers.mainThread());
}
@Override
public Observable<List<Playlist>> getPlaylists() {
if (mPlaylists == null) {
mPlaylists = BehaviorSubject.create();
mLoadingState.onNext(true);
MediaStoreUtil.getPermission(mContext)
.observeOn(Schedulers.io())
.subscribe(granted -> {
if (granted) {
mPlaylists.onNext(getAllPlaylists());
} else {
mPlaylists.onNext(Collections.emptyList());
}
mLoadingState.onNext(false);
}, throwable -> {
Timber.e(throwable, "Failed to query MediaStore for playlists");
});
}
return mPlaylists.asObservable().observeOn(AndroidSchedulers.mainThread());
}
private List<Playlist> getAllPlaylists() {
return MediaStoreUtil.getAllPlaylists(mContext);
}
@Override
public Observable<List<Song>> getSongs(Playlist playlist) {
if (playlist instanceof AutoPlaylist) {
return getAutoPlaylistSongs((AutoPlaylist) playlist);
} else {
return getPlaylistSongs(playlist);
}
}
private Observable<List<Song>> getPlaylistSongs(Playlist playlist) {
return Observable.just(MediaStoreUtil.getPlaylistSongs(mContext, playlist));
}
private Observable<List<Song>> getAutoPlaylistSongs(AutoPlaylist playlist) {
BehaviorSubject<List<Song>> subject;
if (mAutoPlaylistSessionContents.containsKey(playlist)) {
subject = mAutoPlaylistSessionContents.get(playlist);
} else {
subject = BehaviorSubject.create();
mAutoPlaylistSessionContents.put(playlist, subject);
playlist.generatePlaylist(mMusicStore, this, mPlayCountStore)
.subscribe(subject::onNext, subject::onError);
subject.observeOn(Schedulers.io())
.subscribe(contents -> {
editPlaylist(playlist, contents);
}, throwable -> {
Timber.e(throwable, "Failed to save playlist contents");
});
}
return subject.asObservable().observeOn(AndroidSchedulers.mainThread());
}
@Override
public Observable<List<Playlist>> searchForPlaylists(String query) {
if (query == null || query.isEmpty()) {
return Observable.just(Collections.emptyList());
}
return getPlaylists().map(playlists -> {
List<Playlist> filtered = new ArrayList<>();
String lowerCaseQuery = query.toLowerCase();
for (Playlist playlist : playlists) {
if (playlist.getPlaylistName().toLowerCase().contains(lowerCaseQuery)) {
filtered.add(playlist);
}
}
return filtered;
});
}
@Override
public String verifyPlaylistName(String playlistName) {
if (playlistName == null || playlistName.trim().isEmpty()) {
return mContext.getString(R.string.error_hint_empty_playlist);
}
if (MediaStoreUtil.findPlaylistByName(mContext, playlistName) != null) {
return mContext.getString(R.string.error_hint_duplicate_playlist);
}
return null;
}
@Override
public Playlist makePlaylist(String name) {
return makePlaylist(name, null);
}
@Override
public AutoPlaylist makePlaylist(AutoPlaylist playlist) {
Playlist localReference = MediaStoreUtil.createPlaylist(mContext,
playlist.getPlaylistName(), Collections.emptyList());
AutoPlaylist created = new AutoPlaylist.Builder(playlist)
.setId(localReference.getPlaylistId())
.build();
saveAutoPlaylistConfiguration(created);
if (mPlaylists != null && mPlaylists.getValue() != null) {
List<Playlist> updatedPlaylists = new ArrayList<>(mPlaylists.getValue());
updatedPlaylists.add(created);
Collections.sort(updatedPlaylists);
mPlaylists.onNext(updatedPlaylists);
}
return created;
}
@Override
public Playlist makePlaylist(String name, @Nullable List<Song> songs) {
Playlist created = MediaStoreUtil.createPlaylist(mContext, name, songs);
if (mPlaylists != null && mPlaylists.getValue() != null) {
List<Playlist> updated = new ArrayList<>(mPlaylists.getValue());
updated.add(created);
Collections.sort(updated);
mPlaylists.onNext(updated);
}
return created;
}
@Override
public void removePlaylist(Playlist playlist) {
MediaStoreUtil.deletePlaylist(mContext, playlist);
if (mPlaylists != null && mPlaylists.getValue() != null) {
List<Playlist> updated = new ArrayList<>(mPlaylists.getValue());
updated.remove(playlist);
mPlaylists.onNext(updated);
}
}
@Override
public void editPlaylist(Playlist playlist, List<Song> newSongs) {
MediaStoreUtil.editPlaylist(mContext, playlist, newSongs);
}
@Override
public void editPlaylist(AutoPlaylist replacement) {
saveAutoPlaylistConfiguration(replacement);
if (mPlaylists != null && mPlaylists.getValue() != null) {
List<Playlist> updatedPlaylists = new ArrayList<>(mPlaylists.getValue());
int index = updatedPlaylists.indexOf(replacement);
updatedPlaylists.set(index, replacement);
mPlaylists.onNext(updatedPlaylists);
}
}
private void saveAutoPlaylistConfiguration(AutoPlaylist playlist) {
// Write an initial set of values to the MediaStore so other apps can see this playlist
playlist.generatePlaylist(mMusicStore, this, mPlayCountStore)
.take(1)
.observeOn(Schedulers.io())
.subscribe(contents -> {
editPlaylist(playlist, contents);
// Cache this result in memory
BehaviorSubject<List<Song>> contentsSubject;
if (mAutoPlaylistSessionContents.containsKey(playlist)) {
contentsSubject = mAutoPlaylistSessionContents.get(playlist);
} else {
contentsSubject = BehaviorSubject.create();
mAutoPlaylistSessionContents.put(playlist, contentsSubject);
}
contentsSubject.onNext(contents);
try {
writeAutoPlaylistConfiguration(playlist);
} catch (IOException e) {
Timber.e(e, "Failed to write autoPlaylist configuration");
}
}, throwable -> {
Timber.e(throwable, "makePlaylist: Failed to initialize contents");
});
}
private void writeAutoPlaylistConfiguration(AutoPlaylist playlist) throws IOException {
Gson gson = new GsonBuilder()
.setPrettyPrinting()
.registerTypeAdapter(AutoPlaylistRule.class, new AutoPlaylistRule.RuleTypeAdapter())
.create();
FileWriter writer = null;
try {
String filename = playlist.getPlaylistName() + AUTO_PLAYLIST_EXTENSION;
String fullPath = mContext.getExternalFilesDir(null) + File.separator + filename;
writer = new FileWriter(fullPath);
writer.write(gson.toJson(playlist, AutoPlaylist.class));
} finally {
if (writer != null) {
writer.close();
}
}
}
@Override
public void addToPlaylist(Playlist playlist, Song song) {
MediaStoreUtil.appendToPlaylist(mContext, playlist, song);
}
@Override
public void addToPlaylist(Playlist playlist, List<Song> songs) {
MediaStoreUtil.appendToPlaylist(mContext, playlist, songs);
}
}
| Keep playlist observables up-to-date
This fixes an issue where editing a playlist would not refresh the data
shown in playlist activities in the background until they are reopened
| app/src/main/java/com/marverenic/music/data/store/LocalPlaylistStore.java | Keep playlist observables up-to-date | <ide><path>pp/src/main/java/com/marverenic/music/data/store/LocalPlaylistStore.java
<ide>
<ide> private Context mContext;
<ide> private BehaviorSubject<List<Playlist>> mPlaylists;
<del> private Map<AutoPlaylist, BehaviorSubject<List<Song>>> mAutoPlaylistSessionContents;
<add> private Map<Playlist, BehaviorSubject<List<Song>>> mPlaylistContents;
<ide>
<ide> private BehaviorSubject<Boolean> mLoadingState;
<ide>
<ide> mContext = context;
<ide> mMusicStore = musicStore;
<ide> mPlayCountStore = playCountStore;
<del> mAutoPlaylistSessionContents = new ArrayMap<>();
<add> mPlaylistContents = new ArrayMap<>();
<ide> mLoadingState = BehaviorSubject.create(false);
<ide> }
<ide>
<ide> .map(granted -> {
<ide> if (granted && mPlaylists != null) {
<ide> mPlaylists.onNext(getAllPlaylists());
<del> mAutoPlaylistSessionContents.clear();
<add> mPlaylistContents.clear();
<ide> }
<ide> mLoadingState.onNext(false);
<ide> return granted;
<ide> }
<ide>
<ide> private Observable<List<Song>> getPlaylistSongs(Playlist playlist) {
<del> return Observable.just(MediaStoreUtil.getPlaylistSongs(mContext, playlist));
<add> BehaviorSubject<List<Song>> subject;
<add>
<add> if (mPlaylistContents.containsKey(playlist)) {
<add> subject = mPlaylistContents.get(playlist);
<add> } else {
<add> subject = BehaviorSubject.create(MediaStoreUtil.getPlaylistSongs(mContext, playlist));
<add> mPlaylistContents.put(playlist, subject);
<add> }
<add>
<add> return subject.asObservable().observeOn(AndroidSchedulers.mainThread());
<ide> }
<ide>
<ide> private Observable<List<Song>> getAutoPlaylistSongs(AutoPlaylist playlist) {
<ide> BehaviorSubject<List<Song>> subject;
<ide>
<del> if (mAutoPlaylistSessionContents.containsKey(playlist)) {
<del> subject = mAutoPlaylistSessionContents.get(playlist);
<add> if (mPlaylistContents.containsKey(playlist)) {
<add> subject = mPlaylistContents.get(playlist);
<ide> } else {
<ide> subject = BehaviorSubject.create();
<del> mAutoPlaylistSessionContents.put(playlist, subject);
<add> mPlaylistContents.put(playlist, subject);
<ide>
<ide> playlist.generatePlaylist(mMusicStore, this, mPlayCountStore)
<ide> .subscribe(subject::onNext, subject::onError);
<ide> @Override
<ide> public void removePlaylist(Playlist playlist) {
<ide> MediaStoreUtil.deletePlaylist(mContext, playlist);
<add> mPlaylistContents.remove(playlist);
<ide>
<ide> if (mPlaylists != null && mPlaylists.getValue() != null) {
<ide> List<Playlist> updated = new ArrayList<>(mPlaylists.getValue());
<ide> @Override
<ide> public void editPlaylist(Playlist playlist, List<Song> newSongs) {
<ide> MediaStoreUtil.editPlaylist(mContext, playlist, newSongs);
<add> if (mPlaylistContents.containsKey(playlist)) {
<add> mPlaylistContents.get(playlist).onNext(new ArrayList<>(newSongs));
<add> }
<ide> }
<ide>
<ide> @Override
<ide>
<ide> // Cache this result in memory
<ide> BehaviorSubject<List<Song>> contentsSubject;
<del> if (mAutoPlaylistSessionContents.containsKey(playlist)) {
<del> contentsSubject = mAutoPlaylistSessionContents.get(playlist);
<add> if (mPlaylistContents.containsKey(playlist)) {
<add> contentsSubject = mPlaylistContents.get(playlist);
<ide> } else {
<ide> contentsSubject = BehaviorSubject.create();
<del> mAutoPlaylistSessionContents.put(playlist, contentsSubject);
<add> mPlaylistContents.put(playlist, contentsSubject);
<ide> }
<ide> contentsSubject.onNext(contents);
<ide>
<ide> @Override
<ide> public void addToPlaylist(Playlist playlist, Song song) {
<ide> MediaStoreUtil.appendToPlaylist(mContext, playlist, song);
<add>
<add> if (mPlaylistContents.containsKey(playlist)) {
<add> BehaviorSubject<List<Song>> observableContents = mPlaylistContents.get(playlist);
<add> List<Song> updatedContents = new ArrayList<>(observableContents.getValue());
<add> updatedContents.add(song);
<add> observableContents.onNext(updatedContents);
<add> }
<ide> }
<ide>
<ide> @Override
<ide> public void addToPlaylist(Playlist playlist, List<Song> songs) {
<ide> MediaStoreUtil.appendToPlaylist(mContext, playlist, songs);
<add>
<add> if (mPlaylistContents.containsKey(playlist)) {
<add> BehaviorSubject<List<Song>> observableContents = mPlaylistContents.get(playlist);
<add> List<Song> updatedContents = new ArrayList<>(observableContents.getValue());
<add> updatedContents.addAll(songs);
<add> observableContents.onNext(updatedContents);
<add> }
<ide> }
<ide> } |
|
Java | apache-2.0 | 4efacb812d504455f39f3cacdc1ae58df5c42e06 | 0 | christiaandejong/AxonFramework,soulrebel/AxonFramework,BrentDouglas/AxonFramework,krosenvold/AxonFramework,bojanv55/AxonFramework,fpape/AxonFramework,Cosium/AxonFramework,oiavorskyi/AxonFramework,AxonFramework/AxonFramework,phaas/AxonFramework,adinath/AxonFramework | /*
* Copyright (c) 2010-2014. Axon Framework
*
* 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.axonframework.commandhandling.annotation;
import org.axonframework.eventsourcing.annotation.AbstractAnnotatedEntity;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Marker annotation for fields that contain a {@link java.util.Map} of Entities capable of handling Commands on behalf
* of the aggregate. When a field is annotated with <code>@CommandHandlerMemberMap</code>, it is a hint towards Command
* Handler discovery mechanisms that the entity should also be inspected for {@link
* org.axonframework.commandhandling.annotation.CommandHandler} annotated methods.
* <p/>
* Note that CommandHandler detection is done using static typing. This means that only the declared type of the field
* can be inspected. If a subclass of that type is assigned to the field, any handlers declared on that subclass will
* be ignored.
*
* @author Jeroen Bruinink
* @since 2.4
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public @interface CommandHandlingMemberMap {
/**
* The name of the property on the incoming command's payload that identifies the intended target of the command.
* This identity should correspond to the keys in the annotated map.
* <p/>
* The name of this method must correspond with the getter method using the JavaBean specification (property 'id'
* is accessed using method 'getId()'), or any other specification supported by a configured
* {@link org.axonframework.common.property.PropertyAccessStrategy}.
*/
String commandTargetProperty();
/**
* The type of entity contained in the annotated map. By default, Axon attempts to identify the type by the
* generic parameters on the field declaration.
*/
Class<? extends AbstractAnnotatedEntity> entityType() default AbstractAnnotatedEntity.class;
}
| core/src/main/java/org/axonframework/commandhandling/annotation/CommandHandlingMemberMap.java | /*
* Copyright (c) 2010-2014. Axon Framework
*
* 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.axonframework.commandhandling.annotation;
import org.axonframework.eventsourcing.annotation.AbstractAnnotatedEntity;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Marker annotation for fields that contain a {@link java.util.Map} of Entities capable of handling Commands on behalf of the aggregate. When
* a field is annotated with <code>@CommandHandlerMemberMap</code>, it is a hint towards Command Handler discovery
* mechanisms that the entity should also be inspected for {@link org.axonframework.commandhandling.annotation.CommandHandler} annotated methods.
* <p/>
* Note that CommandHandler detection is done using static typing. This means that only the declared type of the field
* can be inspected. If a subclass of that type is assigned to the field, any handlers declared on that subclass will
* be ignored.
*
* @author Jeroen Bruinink
* @since 2.4
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public @interface CommandHandlingMemberMap {
/**
* The name of the property on the incoming command's payload that identifies the intended target of the command.
* This identity should correspond to the keys in the annotated map.
* <p/>
* The name of this method must correspond with the getter method using the JavaBean specification (property 'id'
* is accessed using method 'getId()'), or any other specification supported by a configured
* {@link org.axonframework.common.property.PropertyAccessStrategy}.
*/
String commandTargetProperty();
/**
* The type of entity contained in the annotated map. By default, Axon attempts to identify the type by the
* generic parameters on the field declaration.
*/
Class<? extends AbstractAnnotatedEntity> entityType() default AbstractAnnotatedEntity.class;
}
| Minor code style fix
| core/src/main/java/org/axonframework/commandhandling/annotation/CommandHandlingMemberMap.java | Minor code style fix | <ide><path>ore/src/main/java/org/axonframework/commandhandling/annotation/CommandHandlingMemberMap.java
<ide> import java.lang.annotation.Target;
<ide>
<ide> /**
<del> * Marker annotation for fields that contain a {@link java.util.Map} of Entities capable of handling Commands on behalf of the aggregate. When
<del> * a field is annotated with <code>@CommandHandlerMemberMap</code>, it is a hint towards Command Handler discovery
<del> * mechanisms that the entity should also be inspected for {@link org.axonframework.commandhandling.annotation.CommandHandler} annotated methods.
<add> * Marker annotation for fields that contain a {@link java.util.Map} of Entities capable of handling Commands on behalf
<add> * of the aggregate. When a field is annotated with <code>@CommandHandlerMemberMap</code>, it is a hint towards Command
<add> * Handler discovery mechanisms that the entity should also be inspected for {@link
<add> * org.axonframework.commandhandling.annotation.CommandHandler} annotated methods.
<ide> * <p/>
<ide> * Note that CommandHandler detection is done using static typing. This means that only the declared type of the field
<ide> * can be inspected. If a subclass of that type is assigned to the field, any handlers declared on that subclass will |
|
Java | apache-2.0 | b3fc0a30c177fcaa40017610654967c8be663c86 | 0 | asedunov/intellij-community,ftomassetti/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,petteyg/intellij-community,supersven/intellij-community,Lekanich/intellij-community,robovm/robovm-studio,holmes/intellij-community,Lekanich/intellij-community,izonder/intellij-community,apixandru/intellij-community,muntasirsyed/intellij-community,idea4bsd/idea4bsd,amith01994/intellij-community,kdwink/intellij-community,mglukhikh/intellij-community,jagguli/intellij-community,ibinti/intellij-community,adedayo/intellij-community,fnouama/intellij-community,salguarnieri/intellij-community,pwoodworth/intellij-community,muntasirsyed/intellij-community,hurricup/intellij-community,Distrotech/intellij-community,kdwink/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,lucafavatella/intellij-community,clumsy/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,kool79/intellij-community,TangHao1987/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,TangHao1987/intellij-community,jagguli/intellij-community,ryano144/intellij-community,asedunov/intellij-community,izonder/intellij-community,michaelgallacher/intellij-community,MichaelNedzelsky/intellij-community,samthor/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,slisson/intellij-community,ol-loginov/intellij-community,supersven/intellij-community,kdwink/intellij-community,adedayo/intellij-community,alphafoobar/intellij-community,clumsy/intellij-community,salguarnieri/intellij-community,fitermay/intellij-community,diorcety/intellij-community,idea4bsd/idea4bsd,blademainer/intellij-community,nicolargo/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,jagguli/intellij-community,caot/intellij-community,asedunov/intellij-community,clumsy/intellij-community,mglukhikh/intellij-community,orekyuu/intellij-community,apixandru/intellij-community,akosyakov/intellij-community,muntasirsyed/intellij-community,ftomassetti/intellij-community,signed/intellij-community,slisson/intellij-community,gnuhub/intellij-community,ftomassetti/intellij-community,diorcety/intellij-community,fengbaicanhe/intellij-community,jagguli/intellij-community,fnouama/intellij-community,fitermay/intellij-community,xfournet/intellij-community,akosyakov/intellij-community,vladmm/intellij-community,blademainer/intellij-community,wreckJ/intellij-community,ftomassetti/intellij-community,jagguli/intellij-community,samthor/intellij-community,alphafoobar/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,vvv1559/intellij-community,diorcety/intellij-community,alphafoobar/intellij-community,MER-GROUP/intellij-community,da1z/intellij-community,FHannes/intellij-community,semonte/intellij-community,kdwink/intellij-community,da1z/intellij-community,Distrotech/intellij-community,fnouama/intellij-community,supersven/intellij-community,amith01994/intellij-community,jagguli/intellij-community,vvv1559/intellij-community,fengbaicanhe/intellij-community,fitermay/intellij-community,slisson/intellij-community,ryano144/intellij-community,amith01994/intellij-community,ivan-fedorov/intellij-community,idea4bsd/idea4bsd,ftomassetti/intellij-community,orekyuu/intellij-community,lucafavatella/intellij-community,fengbaicanhe/intellij-community,kool79/intellij-community,dslomov/intellij-community,ol-loginov/intellij-community,xfournet/intellij-community,allotria/intellij-community,diorcety/intellij-community,wreckJ/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,tmpgit/intellij-community,izonder/intellij-community,semonte/intellij-community,vvv1559/intellij-community,da1z/intellij-community,tmpgit/intellij-community,fnouama/intellij-community,kool79/intellij-community,holmes/intellij-community,TangHao1987/intellij-community,retomerz/intellij-community,petteyg/intellij-community,hurricup/intellij-community,allotria/intellij-community,MichaelNedzelsky/intellij-community,ivan-fedorov/intellij-community,Distrotech/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,ivan-fedorov/intellij-community,alphafoobar/intellij-community,robovm/robovm-studio,retomerz/intellij-community,clumsy/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,ftomassetti/intellij-community,nicolargo/intellij-community,gnuhub/intellij-community,fnouama/intellij-community,SerCeMan/intellij-community,signed/intellij-community,fengbaicanhe/intellij-community,fengbaicanhe/intellij-community,SerCeMan/intellij-community,blademainer/intellij-community,akosyakov/intellij-community,gnuhub/intellij-community,slisson/intellij-community,vvv1559/intellij-community,fnouama/intellij-community,idea4bsd/idea4bsd,kool79/intellij-community,amith01994/intellij-community,ibinti/intellij-community,tmpgit/intellij-community,kool79/intellij-community,alphafoobar/intellij-community,ivan-fedorov/intellij-community,suncycheng/intellij-community,diorcety/intellij-community,akosyakov/intellij-community,FHannes/intellij-community,nicolargo/intellij-community,MER-GROUP/intellij-community,ol-loginov/intellij-community,muntasirsyed/intellij-community,pwoodworth/intellij-community,petteyg/intellij-community,TangHao1987/intellij-community,nicolargo/intellij-community,salguarnieri/intellij-community,Lekanich/intellij-community,kdwink/intellij-community,adedayo/intellij-community,ThiagoGarciaAlves/intellij-community,fnouama/intellij-community,nicolargo/intellij-community,MER-GROUP/intellij-community,vladmm/intellij-community,ryano144/intellij-community,da1z/intellij-community,fitermay/intellij-community,signed/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,youdonghai/intellij-community,ahb0327/intellij-community,suncycheng/intellij-community,kool79/intellij-community,blademainer/intellij-community,da1z/intellij-community,vladmm/intellij-community,supersven/intellij-community,diorcety/intellij-community,adedayo/intellij-community,caot/intellij-community,clumsy/intellij-community,akosyakov/intellij-community,robovm/robovm-studio,retomerz/intellij-community,semonte/intellij-community,ibinti/intellij-community,orekyuu/intellij-community,wreckJ/intellij-community,youdonghai/intellij-community,pwoodworth/intellij-community,izonder/intellij-community,alphafoobar/intellij-community,SerCeMan/intellij-community,vladmm/intellij-community,jagguli/intellij-community,holmes/intellij-community,ibinti/intellij-community,clumsy/intellij-community,FHannes/intellij-community,signed/intellij-community,slisson/intellij-community,michaelgallacher/intellij-community,dslomov/intellij-community,mglukhikh/intellij-community,izonder/intellij-community,MichaelNedzelsky/intellij-community,ahb0327/intellij-community,akosyakov/intellij-community,da1z/intellij-community,slisson/intellij-community,vladmm/intellij-community,izonder/intellij-community,SerCeMan/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,slisson/intellij-community,akosyakov/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,samthor/intellij-community,suncycheng/intellij-community,SerCeMan/intellij-community,izonder/intellij-community,salguarnieri/intellij-community,kdwink/intellij-community,TangHao1987/intellij-community,semonte/intellij-community,apixandru/intellij-community,fitermay/intellij-community,ol-loginov/intellij-community,fitermay/intellij-community,samthor/intellij-community,caot/intellij-community,apixandru/intellij-community,semonte/intellij-community,FHannes/intellij-community,dslomov/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,wreckJ/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,muntasirsyed/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,holmes/intellij-community,semonte/intellij-community,vladmm/intellij-community,petteyg/intellij-community,ThiagoGarciaAlves/intellij-community,akosyakov/intellij-community,fengbaicanhe/intellij-community,blademainer/intellij-community,retomerz/intellij-community,petteyg/intellij-community,gnuhub/intellij-community,petteyg/intellij-community,retomerz/intellij-community,orekyuu/intellij-community,blademainer/intellij-community,akosyakov/intellij-community,asedunov/intellij-community,caot/intellij-community,orekyuu/intellij-community,kool79/intellij-community,ftomassetti/intellij-community,holmes/intellij-community,signed/intellij-community,mglukhikh/intellij-community,signed/intellij-community,pwoodworth/intellij-community,diorcety/intellij-community,amith01994/intellij-community,asedunov/intellij-community,Lekanich/intellij-community,petteyg/intellij-community,caot/intellij-community,wreckJ/intellij-community,TangHao1987/intellij-community,ThiagoGarciaAlves/intellij-community,SerCeMan/intellij-community,amith01994/intellij-community,tmpgit/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,wreckJ/intellij-community,MER-GROUP/intellij-community,ol-loginov/intellij-community,da1z/intellij-community,allotria/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,retomerz/intellij-community,xfournet/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,ol-loginov/intellij-community,ahb0327/intellij-community,tmpgit/intellij-community,lucafavatella/intellij-community,diorcety/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,vladmm/intellij-community,diorcety/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,supersven/intellij-community,supersven/intellij-community,fengbaicanhe/intellij-community,holmes/intellij-community,ivan-fedorov/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,orekyuu/intellij-community,fitermay/intellij-community,hurricup/intellij-community,caot/intellij-community,robovm/robovm-studio,adedayo/intellij-community,ol-loginov/intellij-community,allotria/intellij-community,gnuhub/intellij-community,robovm/robovm-studio,fitermay/intellij-community,ThiagoGarciaAlves/intellij-community,dslomov/intellij-community,ryano144/intellij-community,akosyakov/intellij-community,FHannes/intellij-community,retomerz/intellij-community,jagguli/intellij-community,Distrotech/intellij-community,salguarnieri/intellij-community,Distrotech/intellij-community,akosyakov/intellij-community,SerCeMan/intellij-community,retomerz/intellij-community,asedunov/intellij-community,ryano144/intellij-community,pwoodworth/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,michaelgallacher/intellij-community,kool79/intellij-community,semonte/intellij-community,orekyuu/intellij-community,kdwink/intellij-community,fengbaicanhe/intellij-community,dslomov/intellij-community,pwoodworth/intellij-community,retomerz/intellij-community,pwoodworth/intellij-community,MichaelNedzelsky/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,tmpgit/intellij-community,caot/intellij-community,samthor/intellij-community,tmpgit/intellij-community,TangHao1987/intellij-community,signed/intellij-community,pwoodworth/intellij-community,salguarnieri/intellij-community,wreckJ/intellij-community,orekyuu/intellij-community,alphafoobar/intellij-community,nicolargo/intellij-community,izonder/intellij-community,asedunov/intellij-community,ahb0327/intellij-community,samthor/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,MER-GROUP/intellij-community,wreckJ/intellij-community,kdwink/intellij-community,fnouama/intellij-community,nicolargo/intellij-community,pwoodworth/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,da1z/intellij-community,vladmm/intellij-community,tmpgit/intellij-community,asedunov/intellij-community,ivan-fedorov/intellij-community,gnuhub/intellij-community,MichaelNedzelsky/intellij-community,apixandru/intellij-community,amith01994/intellij-community,gnuhub/intellij-community,izonder/intellij-community,wreckJ/intellij-community,kdwink/intellij-community,wreckJ/intellij-community,MichaelNedzelsky/intellij-community,clumsy/intellij-community,dslomov/intellij-community,ol-loginov/intellij-community,asedunov/intellij-community,hurricup/intellij-community,dslomov/intellij-community,lucafavatella/intellij-community,supersven/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,ahb0327/intellij-community,signed/intellij-community,salguarnieri/intellij-community,gnuhub/intellij-community,SerCeMan/intellij-community,ibinti/intellij-community,muntasirsyed/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,wreckJ/intellij-community,blademainer/intellij-community,supersven/intellij-community,MichaelNedzelsky/intellij-community,dslomov/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,ivan-fedorov/intellij-community,caot/intellij-community,vvv1559/intellij-community,kdwink/intellij-community,lucafavatella/intellij-community,MichaelNedzelsky/intellij-community,Distrotech/intellij-community,lucafavatella/intellij-community,robovm/robovm-studio,supersven/intellij-community,amith01994/intellij-community,MER-GROUP/intellij-community,jagguli/intellij-community,amith01994/intellij-community,ryano144/intellij-community,xfournet/intellij-community,holmes/intellij-community,MichaelNedzelsky/intellij-community,pwoodworth/intellij-community,salguarnieri/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,dslomov/intellij-community,hurricup/intellij-community,signed/intellij-community,ibinti/intellij-community,orekyuu/intellij-community,youdonghai/intellij-community,semonte/intellij-community,nicolargo/intellij-community,nicolargo/intellij-community,dslomov/intellij-community,supersven/intellij-community,vvv1559/intellij-community,fengbaicanhe/intellij-community,mglukhikh/intellij-community,caot/intellij-community,clumsy/intellij-community,adedayo/intellij-community,SerCeMan/intellij-community,robovm/robovm-studio,Lekanich/intellij-community,idea4bsd/idea4bsd,Distrotech/intellij-community,salguarnieri/intellij-community,alphafoobar/intellij-community,ivan-fedorov/intellij-community,xfournet/intellij-community,signed/intellij-community,ryano144/intellij-community,caot/intellij-community,allotria/intellij-community,samthor/intellij-community,vvv1559/intellij-community,alphafoobar/intellij-community,vvv1559/intellij-community,blademainer/intellij-community,suncycheng/intellij-community,ryano144/intellij-community,holmes/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,ahb0327/intellij-community,ibinti/intellij-community,clumsy/intellij-community,kool79/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,caot/intellij-community,tmpgit/intellij-community,slisson/intellij-community,fitermay/intellij-community,ivan-fedorov/intellij-community,alphafoobar/intellij-community,apixandru/intellij-community,allotria/intellij-community,xfournet/intellij-community,ahb0327/intellij-community,tmpgit/intellij-community,orekyuu/intellij-community,pwoodworth/intellij-community,Lekanich/intellij-community,blademainer/intellij-community,gnuhub/intellij-community,ThiagoGarciaAlves/intellij-community,kdwink/intellij-community,samthor/intellij-community,slisson/intellij-community,allotria/intellij-community,FHannes/intellij-community,hurricup/intellij-community,kool79/intellij-community,suncycheng/intellij-community,samthor/intellij-community,orekyuu/intellij-community,SerCeMan/intellij-community,petteyg/intellij-community,wreckJ/intellij-community,slisson/intellij-community,blademainer/intellij-community,kool79/intellij-community,ahb0327/intellij-community,muntasirsyed/intellij-community,diorcety/intellij-community,jagguli/intellij-community,apixandru/intellij-community,TangHao1987/intellij-community,ivan-fedorov/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,allotria/intellij-community,youdonghai/intellij-community,tmpgit/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,dslomov/intellij-community,signed/intellij-community,kool79/intellij-community,semonte/intellij-community,gnuhub/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,vladmm/intellij-community,muntasirsyed/intellij-community,MER-GROUP/intellij-community,clumsy/intellij-community,muntasirsyed/intellij-community,dslomov/intellij-community,ftomassetti/intellij-community,TangHao1987/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,diorcety/intellij-community,allotria/intellij-community,MER-GROUP/intellij-community,idea4bsd/idea4bsd,adedayo/intellij-community,robovm/robovm-studio,youdonghai/intellij-community,TangHao1987/intellij-community,petteyg/intellij-community,Lekanich/intellij-community,xfournet/intellij-community,ol-loginov/intellij-community,blademainer/intellij-community,MichaelNedzelsky/intellij-community,allotria/intellij-community,jagguli/intellij-community,da1z/intellij-community,fitermay/intellij-community,Lekanich/intellij-community,blademainer/intellij-community,vvv1559/intellij-community,supersven/intellij-community,fengbaicanhe/intellij-community,nicolargo/intellij-community,robovm/robovm-studio,hurricup/intellij-community,MER-GROUP/intellij-community,ahb0327/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,orekyuu/intellij-community,fnouama/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,akosyakov/intellij-community,samthor/intellij-community,da1z/intellij-community,jagguli/intellij-community,FHannes/intellij-community,ftomassetti/intellij-community,ibinti/intellij-community,muntasirsyed/intellij-community,TangHao1987/intellij-community,idea4bsd/idea4bsd,slisson/intellij-community,adedayo/intellij-community,fitermay/intellij-community,apixandru/intellij-community,ryano144/intellij-community,amith01994/intellij-community,da1z/intellij-community,MER-GROUP/intellij-community,Lekanich/intellij-community,amith01994/intellij-community,ahb0327/intellij-community,michaelgallacher/intellij-community,vladmm/intellij-community,apixandru/intellij-community,adedayo/intellij-community,semonte/intellij-community,ol-loginov/intellij-community,ibinti/intellij-community,ol-loginov/intellij-community,Distrotech/intellij-community,vladmm/intellij-community,ahb0327/intellij-community,tmpgit/intellij-community,diorcety/intellij-community,fnouama/intellij-community,caot/intellij-community,samthor/intellij-community,muntasirsyed/intellij-community,ryano144/intellij-community,gnuhub/intellij-community,SerCeMan/intellij-community,mglukhikh/intellij-community,petteyg/intellij-community,Lekanich/intellij-community,izonder/intellij-community,SerCeMan/intellij-community,signed/intellij-community,vladmm/intellij-community,semonte/intellij-community,ol-loginov/intellij-community,semonte/intellij-community,supersven/intellij-community,lucafavatella/intellij-community,robovm/robovm-studio,Lekanich/intellij-community,fnouama/intellij-community,ibinti/intellij-community,nicolargo/intellij-community,izonder/intellij-community,TangHao1987/intellij-community,holmes/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,nicolargo/intellij-community,ahb0327/intellij-community,Distrotech/intellij-community,Lekanich/intellij-community,michaelgallacher/intellij-community,samthor/intellij-community,salguarnieri/intellij-community,michaelgallacher/intellij-community,Distrotech/intellij-community,ThiagoGarciaAlves/intellij-community,holmes/intellij-community,ftomassetti/intellij-community,allotria/intellij-community,adedayo/intellij-community,ryano144/intellij-community,holmes/intellij-community,MER-GROUP/intellij-community,MichaelNedzelsky/intellij-community,alphafoobar/intellij-community,izonder/intellij-community,michaelgallacher/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,petteyg/intellij-community,da1z/intellij-community,robovm/robovm-studio,robovm/robovm-studio,amith01994/intellij-community,holmes/intellij-community,muntasirsyed/intellij-community,clumsy/intellij-community,clumsy/intellij-community,hurricup/intellij-community,gnuhub/intellij-community,ivan-fedorov/intellij-community,retomerz/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,fengbaicanhe/intellij-community,alphafoobar/intellij-community,FHannes/intellij-community,fengbaicanhe/intellij-community,slisson/intellij-community,ftomassetti/intellij-community,ryano144/intellij-community,hurricup/intellij-community,petteyg/intellij-community,FHannes/intellij-community,Distrotech/intellij-community,fnouama/intellij-community,adedayo/intellij-community | /*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.jps.model.serialization;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.JDOMUtil;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.io.FileUtilRt;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.ArrayUtil;
import com.intellij.util.concurrency.BoundedTaskExecutor;
import org.jdom.Element;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.jps.TimingLog;
import org.jetbrains.jps.model.JpsDummyElement;
import org.jetbrains.jps.model.JpsElement;
import org.jetbrains.jps.model.JpsElementFactory;
import org.jetbrains.jps.model.JpsProject;
import org.jetbrains.jps.model.java.JpsJavaModuleType;
import org.jetbrains.jps.model.library.sdk.JpsSdkType;
import org.jetbrains.jps.model.module.JpsModule;
import org.jetbrains.jps.model.serialization.artifact.JpsArtifactSerializer;
import org.jetbrains.jps.model.serialization.facet.JpsFacetSerializer;
import org.jetbrains.jps.model.serialization.impl.JpsModuleSerializationDataExtensionImpl;
import org.jetbrains.jps.model.serialization.impl.JpsProjectSerializationDataExtensionImpl;
import org.jetbrains.jps.model.serialization.library.JpsLibraryTableSerializer;
import org.jetbrains.jps.model.serialization.library.JpsSdkTableSerializer;
import org.jetbrains.jps.model.serialization.module.JpsModuleClasspathSerializer;
import org.jetbrains.jps.model.serialization.module.JpsModulePropertiesSerializer;
import org.jetbrains.jps.model.serialization.module.JpsModuleRootModelSerializer;
import org.jetbrains.jps.model.serialization.runConfigurations.JpsRunConfigurationSerializer;
import org.jetbrains.jps.service.SharedThreadPool;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
/**
* @author nik
*/
public class JpsProjectLoader extends JpsLoaderBase {
private static final Logger LOG = Logger.getInstance(JpsProjectLoader.class);
private static final BoundedTaskExecutor ourThreadPool = new BoundedTaskExecutor(SharedThreadPool.getInstance(), Runtime.getRuntime().availableProcessors());
public static final String CLASSPATH_ATTRIBUTE = "classpath";
public static final String CLASSPATH_DIR_ATTRIBUTE = "classpath-dir";
private final JpsProject myProject;
private final Map<String, String> myPathVariables;
private JpsProjectLoader(JpsProject project, Map<String, String> pathVariables, File baseDir) {
super(createProjectMacroExpander(pathVariables, baseDir));
myProject = project;
myPathVariables = pathVariables;
myProject.getContainer().setChild(JpsProjectSerializationDataExtensionImpl.ROLE, new JpsProjectSerializationDataExtensionImpl(baseDir));
}
static JpsMacroExpander createProjectMacroExpander(Map<String, String> pathVariables, File baseDir) {
final JpsMacroExpander expander = new JpsMacroExpander(pathVariables);
expander.addFileHierarchyReplacements(PathMacroUtil.PROJECT_DIR_MACRO_NAME, baseDir);
return expander;
}
public static void loadProject(final JpsProject project, Map<String, String> pathVariables, String projectPath) throws IOException {
File file = new File(FileUtil.toCanonicalPath(projectPath));
if (file.isFile() && projectPath.endsWith(".ipr")) {
new JpsProjectLoader(project, pathVariables, file.getParentFile()).loadFromIpr(file);
}
else {
File dotIdea = new File(file, PathMacroUtil.DIRECTORY_STORE_NAME);
File directory;
if (dotIdea.isDirectory()) {
directory = dotIdea;
}
else if (file.isDirectory() && file.getName().equals(PathMacroUtil.DIRECTORY_STORE_NAME)) {
directory = file;
}
else {
throw new IOException("Cannot find IntelliJ IDEA project files at " + projectPath);
}
new JpsProjectLoader(project, pathVariables, directory.getParentFile()).loadFromDirectory(directory);
}
}
public static String getDirectoryBaseProjectName(File dir) {
File nameFile = new File(dir, ".name");
if (nameFile.isFile()) {
try {
return FileUtilRt.loadFile(nameFile).trim();
}
catch (IOException ignored) {
}
}
return StringUtil.replace(dir.getParentFile().getName(), ":", "");
}
private void loadFromDirectory(File dir) {
myProject.setName(getDirectoryBaseProjectName(dir));
JpsSdkType<?> projectSdkType = loadProjectRoot(loadRootElement(new File(dir, "misc.xml")));
for (JpsModelSerializerExtension extension : JpsModelSerializerExtension.getExtensions()) {
for (JpsProjectExtensionSerializer serializer : extension.getProjectExtensionSerializers()) {
loadComponents(dir, "misc.xml", serializer, myProject);
}
}
loadModules(loadRootElement(new File(dir, "modules.xml")), projectSdkType);
Runnable timingLog = TimingLog.startActivity("loading project libraries");
for (File libraryFile : listXmlFiles(new File(dir, "libraries"))) {
loadProjectLibraries(loadRootElement(libraryFile));
}
timingLog.run();
Runnable artifactsTimingLog = TimingLog.startActivity("loading artifacts");
for (File artifactFile : listXmlFiles(new File(dir, "artifacts"))) {
loadArtifacts(loadRootElement(artifactFile));
}
artifactsTimingLog.run();
if (hasRunConfigurationSerializers()) {
Runnable runConfTimingLog = TimingLog.startActivity("loading artifacts");
for (File configurationFile : listXmlFiles(new File(dir, "runConfigurations"))) {
JpsRunConfigurationSerializer.loadRunConfigurations(myProject, loadRootElement(configurationFile));
}
File workspaceFile = new File(dir, "workspace.xml");
if (workspaceFile.exists()) {
Element runManager = JDomSerializationUtil.findComponent(loadRootElement(workspaceFile), "RunManager");
JpsRunConfigurationSerializer.loadRunConfigurations(myProject, runManager);
}
runConfTimingLog.run();
}
}
private static boolean hasRunConfigurationSerializers() {
for (JpsModelSerializerExtension extension : JpsModelSerializerExtension.getExtensions()) {
if (!extension.getRunConfigurationPropertiesSerializers().isEmpty()) {
return true;
}
}
return false;
}
@NotNull
private static File[] listXmlFiles(final File dir) {
File[] files = dir.listFiles(new FileFilter() {
@Override
public boolean accept(File file) {
return isXmlFile(file);
}
});
return files != null ? files : ArrayUtil.EMPTY_FILE_ARRAY;
}
private void loadFromIpr(File iprFile) {
final Element iprRoot = loadRootElement(iprFile);
String projectName = FileUtil.getNameWithoutExtension(iprFile);
myProject.setName(projectName);
File iwsFile = new File(iprFile.getParent(), projectName + ".iws");
Element iwsRoot = iwsFile.exists() ? loadRootElement(iwsFile) : null;
JpsSdkType<?> projectSdkType = loadProjectRoot(iprRoot);
for (JpsModelSerializerExtension extension : JpsModelSerializerExtension.getExtensions()) {
for (JpsProjectExtensionSerializer serializer : extension.getProjectExtensionSerializers()) {
Element rootTag = JpsProjectExtensionSerializer.WORKSPACE_FILE.equals(serializer.getConfigFileName()) ? iwsRoot : iprRoot;
Element component = JDomSerializationUtil.findComponent(rootTag, serializer.getComponentName());
if (component != null) {
serializer.loadExtension(myProject, component);
}
else {
serializer.loadExtensionWithDefaultSettings(myProject);
}
}
}
loadModules(iprRoot, projectSdkType);
loadProjectLibraries(JDomSerializationUtil.findComponent(iprRoot, "libraryTable"));
loadArtifacts(JDomSerializationUtil.findComponent(iprRoot, "ArtifactManager"));
if (hasRunConfigurationSerializers()) {
JpsRunConfigurationSerializer.loadRunConfigurations(myProject, JDomSerializationUtil.findComponent(iprRoot, "ProjectRunConfigurationManager"));
JpsRunConfigurationSerializer.loadRunConfigurations(myProject, JDomSerializationUtil.findComponent(iwsRoot, "RunManager"));
}
}
private void loadArtifacts(@Nullable Element artifactManagerComponent) {
JpsArtifactSerializer.loadArtifacts(myProject, artifactManagerComponent);
}
@Nullable
private JpsSdkType<?> loadProjectRoot(Element root) {
JpsSdkType<?> sdkType = null;
Element rootManagerElement = JDomSerializationUtil.findComponent(root, "ProjectRootManager");
if (rootManagerElement != null) {
String sdkName = rootManagerElement.getAttributeValue("project-jdk-name");
String sdkTypeId = rootManagerElement.getAttributeValue("project-jdk-type");
if (sdkName != null) {
sdkType = JpsSdkTableSerializer.getSdkType(sdkTypeId);
JpsSdkTableSerializer.setSdkReference(myProject.getSdkReferencesTable(), sdkName, sdkType);
}
}
return sdkType;
}
private void loadProjectLibraries(@Nullable Element libraryTableElement) {
JpsLibraryTableSerializer.loadLibraries(libraryTableElement, myProject.getLibraryCollection());
}
private void loadModules(Element root, final @Nullable JpsSdkType<?> projectSdkType) {
Runnable timingLog = TimingLog.startActivity("loading modules");
Element componentRoot = JDomSerializationUtil.findComponent(root, "ProjectModuleManager");
if (componentRoot == null) return;
final Element modules = componentRoot.getChild("modules");
List<Future<JpsModule>> futures = new ArrayList<Future<JpsModule>>();
List<Future<Pair<File, Element>>> futureModuleFiles = new ArrayList<Future<Pair<File, Element>>>();
for (Element moduleElement : JDOMUtil.getChildren(modules, "module")) {
final String path = moduleElement.getAttributeValue("filepath");
final File file = new File(path);
if (!file.exists()) {
LOG.info("Module '" + FileUtil.getNameWithoutExtension(file) + "' is skipped: " + file.getAbsolutePath() + " doesn't exist");
continue;
}
futureModuleFiles.add(ourThreadPool.submit(new Callable<Pair<File, Element>>() {
@Override
public Pair<File, Element> call() throws Exception {
final JpsMacroExpander expander = createModuleMacroExpander(myPathVariables, file);
final Element moduleRoot = loadRootElement(file, expander);
return Pair.create(file, moduleRoot);
}
}));
}
try {
final List<String> classpathDirs = new ArrayList<String>();
for (Future<Pair<File, Element>> moduleFile : futureModuleFiles) {
final String classpathDir = moduleFile.get().getSecond().getAttributeValue(CLASSPATH_DIR_ATTRIBUTE);
if (classpathDir != null) {
classpathDirs.add(classpathDir);
}
}
for (final Future<Pair<File, Element>> futureModuleFile : futureModuleFiles) {
final Pair<File, Element> moduleFile = futureModuleFile.get();
futures.add(ourThreadPool.submit(new Callable<JpsModule>() {
@Override
public JpsModule call() throws Exception {
return loadModule(moduleFile.getFirst(), moduleFile.getSecond(), classpathDirs, projectSdkType);
}
}));
}
for (Future<JpsModule> future : futures) {
JpsModule module = future.get();
if (module != null) {
myProject.addModule(module);
}
}
}
catch (Exception e) {
throw new RuntimeException(e);
}
timingLog.run();
}
@Nullable
private JpsModule loadModule(@NotNull File file, @NotNull Element moduleRoot, List<String> paths, @Nullable JpsSdkType<?> projectSdkType) {
String name = FileUtil.getNameWithoutExtension(file);
final String typeId = moduleRoot.getAttributeValue("type");
final JpsModulePropertiesSerializer<?> serializer = getModulePropertiesSerializer(typeId);
final JpsModule module = createModule(name, moduleRoot, serializer);
module.getContainer().setChild(JpsModuleSerializationDataExtensionImpl.ROLE,
new JpsModuleSerializationDataExtensionImpl(file.getParentFile()));
for (JpsModelSerializerExtension extension : JpsModelSerializerExtension.getExtensions()) {
extension.loadModuleOptions(module, moduleRoot);
}
String baseModulePath = FileUtil.toSystemIndependentName(file.getParent());
String classpath = moduleRoot.getAttributeValue(CLASSPATH_ATTRIBUTE);
if (classpath == null) {
JpsModuleRootModelSerializer.loadRootModel(module, JDomSerializationUtil.findComponent(moduleRoot, "NewModuleRootManager"),
projectSdkType);
}
else {
for (JpsModelSerializerExtension extension : JpsModelSerializerExtension.getExtensions()) {
JpsModuleClasspathSerializer classpathSerializer = extension.getClasspathSerializer();
if (classpathSerializer != null && classpathSerializer.getClasspathId().equals(classpath)) {
String classpathDir = moduleRoot.getAttributeValue(CLASSPATH_DIR_ATTRIBUTE);
final JpsMacroExpander expander = createModuleMacroExpander(myPathVariables, file);
classpathSerializer.loadClasspath(module, classpathDir, baseModulePath, expander, paths, projectSdkType);
}
}
}
JpsFacetSerializer.loadFacets(module, JDomSerializationUtil.findComponent(moduleRoot, "FacetManager"));
return module;
}
static JpsMacroExpander createModuleMacroExpander(final Map<String, String> pathVariables, File moduleFile) {
final JpsMacroExpander expander = new JpsMacroExpander(pathVariables);
String moduleDirPath = PathMacroUtil.getModuleDir(moduleFile.getAbsolutePath());
if (moduleDirPath != null) {
expander.addFileHierarchyReplacements(PathMacroUtil.MODULE_DIR_MACRO_NAME, new File(FileUtil.toSystemDependentName(moduleDirPath)));
}
return expander;
}
private static <P extends JpsElement> JpsModule createModule(String name, Element moduleRoot, JpsModulePropertiesSerializer<P> loader) {
String componentName = loader.getComponentName();
Element component = componentName != null ? JDomSerializationUtil.findComponent(moduleRoot, componentName) : null;
return JpsElementFactory.getInstance().createModule(name, loader.getType(), loader.loadProperties(component));
}
private static JpsModulePropertiesSerializer<?> getModulePropertiesSerializer(@Nullable String typeId) {
for (JpsModelSerializerExtension extension : JpsModelSerializerExtension.getExtensions()) {
for (JpsModulePropertiesSerializer<?> loader : extension.getModulePropertiesSerializers()) {
if (loader.getTypeId().equals(typeId)) {
return loader;
}
}
}
return new JpsModulePropertiesSerializer<JpsDummyElement>(JpsJavaModuleType.INSTANCE, "JAVA_MODULE", null) {
@Override
public JpsDummyElement loadProperties(@Nullable Element componentElement) {
return JpsElementFactory.getInstance().createDummyElement();
}
@Override
public void saveProperties(@NotNull JpsDummyElement properties, @NotNull Element componentElement) {
}
};
}
}
| jps/model-serialization/src/org/jetbrains/jps/model/serialization/JpsProjectLoader.java | /*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.jps.model.serialization;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.JDOMUtil;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.io.FileUtilRt;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.ArrayUtil;
import com.intellij.util.concurrency.BoundedTaskExecutor;
import org.jdom.Element;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.jps.TimingLog;
import org.jetbrains.jps.model.JpsDummyElement;
import org.jetbrains.jps.model.JpsElement;
import org.jetbrains.jps.model.JpsElementFactory;
import org.jetbrains.jps.model.JpsProject;
import org.jetbrains.jps.model.java.JpsJavaModuleType;
import org.jetbrains.jps.model.library.sdk.JpsSdkType;
import org.jetbrains.jps.model.module.JpsModule;
import org.jetbrains.jps.model.serialization.artifact.JpsArtifactSerializer;
import org.jetbrains.jps.model.serialization.facet.JpsFacetSerializer;
import org.jetbrains.jps.model.serialization.impl.JpsModuleSerializationDataExtensionImpl;
import org.jetbrains.jps.model.serialization.impl.JpsProjectSerializationDataExtensionImpl;
import org.jetbrains.jps.model.serialization.library.JpsLibraryTableSerializer;
import org.jetbrains.jps.model.serialization.library.JpsSdkTableSerializer;
import org.jetbrains.jps.model.serialization.module.JpsModuleClasspathSerializer;
import org.jetbrains.jps.model.serialization.module.JpsModulePropertiesSerializer;
import org.jetbrains.jps.model.serialization.module.JpsModuleRootModelSerializer;
import org.jetbrains.jps.model.serialization.runConfigurations.JpsRunConfigurationSerializer;
import org.jetbrains.jps.service.SharedThreadPool;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
/**
* @author nik
*/
public class JpsProjectLoader extends JpsLoaderBase {
private static final Logger LOG = Logger.getInstance(JpsProjectLoader.class);
private static final BoundedTaskExecutor ourThreadPool = new BoundedTaskExecutor(SharedThreadPool.getInstance(), Runtime.getRuntime().availableProcessors());
public static final String CLASSPATH_ATTRIBUTE = "classpath";
public static final String CLASSPATH_DIR_ATTRIBUTE = "classpath-dir";
private final JpsProject myProject;
private final Map<String, String> myPathVariables;
private JpsProjectLoader(JpsProject project, Map<String, String> pathVariables, File baseDir) {
super(createProjectMacroExpander(pathVariables, baseDir));
myProject = project;
myPathVariables = pathVariables;
myProject.getContainer().setChild(JpsProjectSerializationDataExtensionImpl.ROLE, new JpsProjectSerializationDataExtensionImpl(baseDir));
}
static JpsMacroExpander createProjectMacroExpander(Map<String, String> pathVariables, File baseDir) {
final JpsMacroExpander expander = new JpsMacroExpander(pathVariables);
expander.addFileHierarchyReplacements(PathMacroUtil.PROJECT_DIR_MACRO_NAME, baseDir);
return expander;
}
public static void loadProject(final JpsProject project, Map<String, String> pathVariables, String projectPath) throws IOException {
File file = new File(FileUtil.toCanonicalPath(projectPath));
if (file.isFile() && projectPath.endsWith(".ipr")) {
new JpsProjectLoader(project, pathVariables, file.getParentFile()).loadFromIpr(file);
}
else {
File dotIdea = new File(file, PathMacroUtil.DIRECTORY_STORE_NAME);
File directory;
if (dotIdea.isDirectory()) {
directory = dotIdea;
}
else if (file.isDirectory() && file.getName().equals(PathMacroUtil.DIRECTORY_STORE_NAME)) {
directory = file;
}
else {
throw new IOException("Cannot find IntelliJ IDEA project files at " + projectPath);
}
new JpsProjectLoader(project, pathVariables, directory.getParentFile()).loadFromDirectory(directory);
}
}
public static String getDirectoryBaseProjectName(File dir) {
File nameFile = new File(dir, ".name");
if (nameFile.isFile()) {
try {
return FileUtilRt.loadFile(nameFile).trim();
}
catch (IOException ignored) {
}
}
return StringUtil.replace(dir.getParentFile().getName(), ":", "");
}
private void loadFromDirectory(File dir) {
myProject.setName(getDirectoryBaseProjectName(dir));
JpsSdkType<?> projectSdkType = loadProjectRoot(loadRootElement(new File(dir, "misc.xml")));
for (JpsModelSerializerExtension extension : JpsModelSerializerExtension.getExtensions()) {
for (JpsProjectExtensionSerializer serializer : extension.getProjectExtensionSerializers()) {
loadComponents(dir, "misc.xml", serializer, myProject);
}
}
loadModules(loadRootElement(new File(dir, "modules.xml")), projectSdkType);
Runnable timingLog = TimingLog.startActivity("loading project libraries");
for (File libraryFile : listXmlFiles(new File(dir, "libraries"))) {
loadProjectLibraries(loadRootElement(libraryFile));
}
timingLog.run();
Runnable artifactsTimingLog = TimingLog.startActivity("loading artifacts");
for (File artifactFile : listXmlFiles(new File(dir, "artifacts"))) {
loadArtifacts(loadRootElement(artifactFile));
}
artifactsTimingLog.run();
if (hasRunConfigurationSerializers()) {
Runnable runConfTimingLog = TimingLog.startActivity("loading artifacts");
for (File configurationFile : listXmlFiles(new File(dir, "runConfigurations"))) {
JpsRunConfigurationSerializer.loadRunConfigurations(myProject, loadRootElement(configurationFile));
}
File workspaceFile = new File(dir, "workspace.xml");
if (workspaceFile.exists()) {
Element runManager = JDomSerializationUtil.findComponent(loadRootElement(workspaceFile), "RunManager");
JpsRunConfigurationSerializer.loadRunConfigurations(myProject, runManager);
}
runConfTimingLog.run();
}
}
private static boolean hasRunConfigurationSerializers() {
for (JpsModelSerializerExtension extension : JpsModelSerializerExtension.getExtensions()) {
if (!extension.getRunConfigurationPropertiesSerializers().isEmpty()) {
return true;
}
}
return false;
}
@NotNull
private static File[] listXmlFiles(final File dir) {
File[] files = dir.listFiles(new FileFilter() {
@Override
public boolean accept(File file) {
return isXmlFile(file);
}
});
return files != null ? files : ArrayUtil.EMPTY_FILE_ARRAY;
}
private void loadFromIpr(File iprFile) {
final Element iprRoot = loadRootElement(iprFile);
String projectName = FileUtil.getNameWithoutExtension(iprFile);
myProject.setName(projectName);
File iwsFile = new File(iprFile.getParent(), projectName + ".iws");
Element iwsRoot = iwsFile.exists() ? loadRootElement(iwsFile) : null;
JpsSdkType<?> projectSdkType = loadProjectRoot(iprRoot);
for (JpsModelSerializerExtension extension : JpsModelSerializerExtension.getExtensions()) {
for (JpsProjectExtensionSerializer serializer : extension.getProjectExtensionSerializers()) {
Element rootTag = JpsProjectExtensionSerializer.WORKSPACE_FILE.equals(serializer.getConfigFileName()) ? iwsRoot : iprRoot;
Element component = JDomSerializationUtil.findComponent(rootTag, serializer.getComponentName());
if (component != null) {
serializer.loadExtension(myProject, component);
}
else {
serializer.loadExtensionWithDefaultSettings(myProject);
}
}
}
loadModules(iprRoot, projectSdkType);
loadProjectLibraries(JDomSerializationUtil.findComponent(iprRoot, "libraryTable"));
loadArtifacts(JDomSerializationUtil.findComponent(iprRoot, "ArtifactManager"));
if (hasRunConfigurationSerializers()) {
JpsRunConfigurationSerializer.loadRunConfigurations(myProject, JDomSerializationUtil.findComponent(iprRoot, "ProjectRunConfigurationManager"));
JpsRunConfigurationSerializer.loadRunConfigurations(myProject, JDomSerializationUtil.findComponent(iwsRoot, "RunManager"));
}
}
private void loadArtifacts(@Nullable Element artifactManagerComponent) {
JpsArtifactSerializer.loadArtifacts(myProject, artifactManagerComponent);
}
@Nullable
private JpsSdkType<?> loadProjectRoot(Element root) {
JpsSdkType<?> sdkType = null;
Element rootManagerElement = JDomSerializationUtil.findComponent(root, "ProjectRootManager");
if (rootManagerElement != null) {
String sdkName = rootManagerElement.getAttributeValue("project-jdk-name");
String sdkTypeId = rootManagerElement.getAttributeValue("project-jdk-type");
if (sdkName != null) {
sdkType = JpsSdkTableSerializer.getSdkType(sdkTypeId);
JpsSdkTableSerializer.setSdkReference(myProject.getSdkReferencesTable(), sdkName, sdkType);
}
}
return sdkType;
}
private void loadProjectLibraries(@Nullable Element libraryTableElement) {
JpsLibraryTableSerializer.loadLibraries(libraryTableElement, myProject.getLibraryCollection());
}
private void loadModules(Element root, final @Nullable JpsSdkType<?> projectSdkType) {
Runnable timingLog = TimingLog.startActivity("loading modules");
Element componentRoot = JDomSerializationUtil.findComponent(root, "ProjectModuleManager");
if (componentRoot == null) return;
final Element modules = componentRoot.getChild("modules");
List<Future<JpsModule>> futures = new ArrayList<Future<JpsModule>>();
final List<String> paths = new ArrayList<String>();
final List<String> classpathDirs = new ArrayList<String>();
for (Element moduleElement : JDOMUtil.getChildren(modules, "module")) {
final String path = moduleElement.getAttributeValue("filepath");
final File file = new File(path);
if (!file.exists()) {
LOG.info("Module '" + FileUtil.getNameWithoutExtension(file) + "' is skipped: " + file.getAbsolutePath() + " doesn't exist");
continue;
}
final JpsMacroExpander expander = createModuleMacroExpander(myPathVariables, file);
final Element moduleRoot = loadRootElement(file, expander);
final String classpathDir = moduleRoot.getAttributeValue(CLASSPATH_DIR_ATTRIBUTE);
if (classpathDir != null) {
classpathDirs.add(classpathDir);
}
paths.add(path);
}
for (final String path : paths) {
futures.add(ourThreadPool.submit(new Callable<JpsModule>() {
@Override
public JpsModule call() throws Exception {
return loadModule(path, classpathDirs, projectSdkType);
}
}));
}
try {
for (Future<JpsModule> future : futures) {
JpsModule module = future.get();
if (module != null) {
myProject.addModule(module);
}
}
}
catch (Exception e) {
throw new RuntimeException(e);
}
timingLog.run();
}
@Nullable
private JpsModule loadModule(@NotNull String path, List<String> paths, @Nullable JpsSdkType<?> projectSdkType) {
final File file = new File(path);
String name = FileUtil.getNameWithoutExtension(file);
if (!file.exists()) {
LOG.info("Module '" + name + "' is skipped: " + file.getAbsolutePath() + " doesn't exist");
return null;
}
final JpsMacroExpander expander = createModuleMacroExpander(myPathVariables, file);
final Element moduleRoot = loadRootElement(file, expander);
final String typeId = moduleRoot.getAttributeValue("type");
final JpsModulePropertiesSerializer<?> serializer = getModulePropertiesSerializer(typeId);
final JpsModule module = createModule(name, moduleRoot, serializer);
module.getContainer().setChild(JpsModuleSerializationDataExtensionImpl.ROLE,
new JpsModuleSerializationDataExtensionImpl(file.getParentFile()));
for (JpsModelSerializerExtension extension : JpsModelSerializerExtension.getExtensions()) {
extension.loadModuleOptions(module, moduleRoot);
}
String baseModulePath = FileUtil.toSystemIndependentName(file.getParent());
String classpath = moduleRoot.getAttributeValue(CLASSPATH_ATTRIBUTE);
if (classpath == null) {
JpsModuleRootModelSerializer.loadRootModel(module, JDomSerializationUtil.findComponent(moduleRoot, "NewModuleRootManager"),
projectSdkType);
}
else {
for (JpsModelSerializerExtension extension : JpsModelSerializerExtension.getExtensions()) {
JpsModuleClasspathSerializer classpathSerializer = extension.getClasspathSerializer();
if (classpathSerializer != null && classpathSerializer.getClasspathId().equals(classpath)) {
String classpathDir = moduleRoot.getAttributeValue(CLASSPATH_DIR_ATTRIBUTE);
classpathSerializer.loadClasspath(module, classpathDir, baseModulePath, expander, paths, projectSdkType);
}
}
}
JpsFacetSerializer.loadFacets(module, JDomSerializationUtil.findComponent(moduleRoot, "FacetManager"));
return module;
}
static JpsMacroExpander createModuleMacroExpander(final Map<String, String> pathVariables, File moduleFile) {
final JpsMacroExpander expander = new JpsMacroExpander(pathVariables);
String moduleDirPath = PathMacroUtil.getModuleDir(moduleFile.getAbsolutePath());
if (moduleDirPath != null) {
expander.addFileHierarchyReplacements(PathMacroUtil.MODULE_DIR_MACRO_NAME, new File(FileUtil.toSystemDependentName(moduleDirPath)));
}
return expander;
}
private static <P extends JpsElement> JpsModule createModule(String name, Element moduleRoot, JpsModulePropertiesSerializer<P> loader) {
String componentName = loader.getComponentName();
Element component = componentName != null ? JDomSerializationUtil.findComponent(moduleRoot, componentName) : null;
return JpsElementFactory.getInstance().createModule(name, loader.getType(), loader.loadProperties(component));
}
private static JpsModulePropertiesSerializer<?> getModulePropertiesSerializer(@Nullable String typeId) {
for (JpsModelSerializerExtension extension : JpsModelSerializerExtension.getExtensions()) {
for (JpsModulePropertiesSerializer<?> loader : extension.getModulePropertiesSerializers()) {
if (loader.getTypeId().equals(typeId)) {
return loader;
}
}
}
return new JpsModulePropertiesSerializer<JpsDummyElement>(JpsJavaModuleType.INSTANCE, "JAVA_MODULE", null) {
@Override
public JpsDummyElement loadProperties(@Nullable Element componentElement) {
return JpsElementFactory.getInstance().createDummyElement();
}
@Override
public void saveProperties(@NotNull JpsDummyElement properties, @NotNull Element componentElement) {
}
};
}
}
| jps model: don't load and parse each iml file twice
| jps/model-serialization/src/org/jetbrains/jps/model/serialization/JpsProjectLoader.java | jps model: don't load and parse each iml file twice | <ide><path>ps/model-serialization/src/org/jetbrains/jps/model/serialization/JpsProjectLoader.java
<ide>
<ide> import com.intellij.openapi.diagnostic.Logger;
<ide> import com.intellij.openapi.util.JDOMUtil;
<add>import com.intellij.openapi.util.Pair;
<ide> import com.intellij.openapi.util.io.FileUtil;
<ide> import com.intellij.openapi.util.io.FileUtilRt;
<ide> import com.intellij.openapi.util.text.StringUtil;
<ide> if (componentRoot == null) return;
<ide> final Element modules = componentRoot.getChild("modules");
<ide> List<Future<JpsModule>> futures = new ArrayList<Future<JpsModule>>();
<del> final List<String> paths = new ArrayList<String>();
<del> final List<String> classpathDirs = new ArrayList<String>();
<add>
<add> List<Future<Pair<File, Element>>> futureModuleFiles = new ArrayList<Future<Pair<File, Element>>>();
<ide> for (Element moduleElement : JDOMUtil.getChildren(modules, "module")) {
<ide> final String path = moduleElement.getAttributeValue("filepath");
<ide> final File file = new File(path);
<ide> continue;
<ide> }
<ide>
<del> final JpsMacroExpander expander = createModuleMacroExpander(myPathVariables, file);
<del> final Element moduleRoot = loadRootElement(file, expander);
<del> final String classpathDir = moduleRoot.getAttributeValue(CLASSPATH_DIR_ATTRIBUTE);
<del> if (classpathDir != null) {
<del> classpathDirs.add(classpathDir);
<del> }
<del> paths.add(path);
<del> }
<del> for (final String path : paths) {
<del> futures.add(ourThreadPool.submit(new Callable<JpsModule>() {
<add> futureModuleFiles.add(ourThreadPool.submit(new Callable<Pair<File, Element>>() {
<ide> @Override
<del> public JpsModule call() throws Exception {
<del> return loadModule(path, classpathDirs, projectSdkType);
<add> public Pair<File, Element> call() throws Exception {
<add> final JpsMacroExpander expander = createModuleMacroExpander(myPathVariables, file);
<add> final Element moduleRoot = loadRootElement(file, expander);
<add> return Pair.create(file, moduleRoot);
<ide> }
<ide> }));
<ide> }
<add>
<ide> try {
<add> final List<String> classpathDirs = new ArrayList<String>();
<add> for (Future<Pair<File, Element>> moduleFile : futureModuleFiles) {
<add> final String classpathDir = moduleFile.get().getSecond().getAttributeValue(CLASSPATH_DIR_ATTRIBUTE);
<add> if (classpathDir != null) {
<add> classpathDirs.add(classpathDir);
<add> }
<add> }
<add>
<add> for (final Future<Pair<File, Element>> futureModuleFile : futureModuleFiles) {
<add> final Pair<File, Element> moduleFile = futureModuleFile.get();
<add> futures.add(ourThreadPool.submit(new Callable<JpsModule>() {
<add> @Override
<add> public JpsModule call() throws Exception {
<add> return loadModule(moduleFile.getFirst(), moduleFile.getSecond(), classpathDirs, projectSdkType);
<add> }
<add> }));
<add> }
<ide> for (Future<JpsModule> future : futures) {
<ide> JpsModule module = future.get();
<ide> if (module != null) {
<ide> }
<ide>
<ide> @Nullable
<del> private JpsModule loadModule(@NotNull String path, List<String> paths, @Nullable JpsSdkType<?> projectSdkType) {
<del> final File file = new File(path);
<add> private JpsModule loadModule(@NotNull File file, @NotNull Element moduleRoot, List<String> paths, @Nullable JpsSdkType<?> projectSdkType) {
<ide> String name = FileUtil.getNameWithoutExtension(file);
<del> if (!file.exists()) {
<del> LOG.info("Module '" + name + "' is skipped: " + file.getAbsolutePath() + " doesn't exist");
<del> return null;
<del> }
<del>
<del> final JpsMacroExpander expander = createModuleMacroExpander(myPathVariables, file);
<del> final Element moduleRoot = loadRootElement(file, expander);
<ide> final String typeId = moduleRoot.getAttributeValue("type");
<ide> final JpsModulePropertiesSerializer<?> serializer = getModulePropertiesSerializer(typeId);
<ide> final JpsModule module = createModule(name, moduleRoot, serializer);
<ide> module.getContainer().setChild(JpsModuleSerializationDataExtensionImpl.ROLE,
<del> new JpsModuleSerializationDataExtensionImpl(file.getParentFile()));
<add> new JpsModuleSerializationDataExtensionImpl(file.getParentFile()));
<ide>
<ide> for (JpsModelSerializerExtension extension : JpsModelSerializerExtension.getExtensions()) {
<ide> extension.loadModuleOptions(module, moduleRoot);
<ide> JpsModuleClasspathSerializer classpathSerializer = extension.getClasspathSerializer();
<ide> if (classpathSerializer != null && classpathSerializer.getClasspathId().equals(classpath)) {
<ide> String classpathDir = moduleRoot.getAttributeValue(CLASSPATH_DIR_ATTRIBUTE);
<add> final JpsMacroExpander expander = createModuleMacroExpander(myPathVariables, file);
<ide> classpathSerializer.loadClasspath(module, classpathDir, baseModulePath, expander, paths, projectSdkType);
<ide> }
<ide> } |
|
Java | mit | 4868ab621369d567e7f8a10c8ea5743d37577c60 | 0 | toyama0919/embulk-filter-crawler,toyama0919/embulk-filter-crawler | package org.embulk.filter.crawler;
import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.embulk.config.Config;
import org.embulk.config.ConfigDefault;
import org.embulk.config.ConfigSource;
import org.embulk.config.Task;
import org.embulk.config.TaskSource;
import org.embulk.spi.Column;
import org.embulk.spi.Exec;
import org.embulk.spi.FilterPlugin;
import org.embulk.spi.Page;
import org.embulk.spi.PageBuilder;
import org.embulk.spi.PageOutput;
import org.embulk.spi.PageReader;
import org.embulk.spi.Schema;
import org.embulk.spi.type.Types;
import org.slf4j.Logger;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import edu.uci.ics.crawler4j.crawler.CrawlConfig;
import edu.uci.ics.crawler4j.crawler.CrawlController;
import edu.uci.ics.crawler4j.fetcher.PageFetcher;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtConfig;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtServer;
public class CrawlerFilterPlugin
implements FilterPlugin
{
private static final Logger logger = Exec.getLogger(CrawlerFilterPlugin.class);
public interface PluginTask
extends Task
{
@Config("max_depth_of_crawling")
@ConfigDefault("null")
public Optional<Integer> getMaxDepthOfCrawling();
@Config("number_of_crawlers")
@ConfigDefault("2")
public int getNumberOfCrawlers();
@Config("max_pages_to_fetch")
@ConfigDefault("-1")
public int getMaxPagesToFetch();
@Config("target_key")
public String getTargetKey();
@Config("crawl_storage_folder")
public String getCrawlStorageFolder();
@Config("politeness_delay")
@ConfigDefault("null")
public Optional<Integer> getPolitenessDelay();
@Config("user_agent_string")
@ConfigDefault("null")
public Optional<String> getUserAgentString();
@Config("keep_input")
@ConfigDefault("true")
public boolean getKeepInput();
@Config("output_prefix")
@ConfigDefault("\"\"")
public String getOutputPrefix();
@Config("should_not_visit_pattern")
@ConfigDefault("null")
public Optional<String> getShouldNotVisitPattern();
@Config("connection_timeout")
@ConfigDefault("null")
public Optional<Integer> getConnectionTimeout();
@Config("socket_timeout")
@ConfigDefault("null")
public Optional<Integer> getSocketTimeout();
}
@Override
public void transaction(ConfigSource config, Schema inputSchema,
FilterPlugin.Control control)
{
PluginTask task = config.loadConfig(PluginTask.class);
ImmutableList.Builder<Column> builder = ImmutableList.builder();
int i = 0;
builder.addAll(getOutputColumns(i, task.getOutputPrefix()));
Schema outputSchema = new Schema(builder.build());
control.run(task.dump(), outputSchema);
}
/**
* @param i
* @param outputPrefix
* @return
*/
private List<Column> getOutputColumns(int i, String outputPrefix) {
List<Column> list = Lists.newArrayList();
list.add(new Column(i++, outputPrefix + Constants.URL, Types.STRING));
list.add(new Column(i++, outputPrefix + Constants.DOMAIN, Types.STRING));
list.add(new Column(i++, outputPrefix + Constants.SUBDOMAIN, Types.STRING));
list.add(new Column(i++, outputPrefix + Constants.PATH, Types.STRING));
list.add(new Column(i++, outputPrefix + Constants.ANCHOR, Types.STRING));
list.add(new Column(i++, outputPrefix + Constants.PARENT_URL, Types.STRING));
list.add(new Column(i++, outputPrefix + Constants.CONTENT_CHARSET, Types.STRING));
list.add(new Column(i++, outputPrefix + Constants.REDIRECT_TO_URL, Types.STRING));
list.add(new Column(i++, outputPrefix + Constants.LANGUAGE, Types.STRING));
list.add(new Column(i++, outputPrefix + Constants.STATUS_CODE, Types.LONG));
list.add(new Column(i++, outputPrefix + Constants.TITLE, Types.STRING));
list.add(new Column(i++, outputPrefix + Constants.TEXT, Types.STRING));
list.add(new Column(i++, outputPrefix + Constants.HTML, Types.STRING));
return list;
}
@Override
public PageOutput open(TaskSource taskSource, final Schema inputSchema,
final Schema outputSchema, final PageOutput output)
{
final PluginTask task = taskSource.loadTask(PluginTask.class);
final Column keyNameColumn = inputSchema.lookupColumn(task.getTargetKey());
return new PageOutput() {
private PageReader reader = new PageReader(inputSchema);
private PageBuilder builder = new PageBuilder(Exec.getBufferAllocator(), outputSchema, output);
@Override
public void finish()
{
builder.finish();
}
@Override
public void close()
{
builder.close();
}
@Override
public void add(Page page)
{
CrawlController controller = getController();
reader.setPage(page);
while (reader.nextRecord()) {
controller.addSeed(reader.getString(keyNameColumn));
}
Map<String, Object> customData = Maps.newHashMap();
customData.put("output_prefix", task.getOutputPrefix());
if (task.getShouldNotVisitPattern().isPresent()) {
customData.put("should_not_visit_pattern", task.getShouldNotVisitPattern().get());
}
controller.setCustomData(customData);
controller.start(EmbulkCrawler.class, task.getNumberOfCrawlers() < 2 ? 2 : task.getNumberOfCrawlers());
for (Object object : controller.getCrawlersLocalData()) {
CrawlStat crawlStat = (CrawlStat) object;
for (Map<String, Object> map : crawlStat.getPages()) {
for (Column outputColumn : outputSchema.getColumns()) {
final Object value = map.get(outputColumn.getName());
setValue(value, outputColumn);
}
builder.addRecord();
}
}
}
/**
* @param seeds
*/
private void setValue(Object value, Column column)
{
if (value == null) {
builder.setNull(column);
}
else if (column.getType().equals(Types.STRING)) {
builder.setString(column, (String) value);
}
else if (column.getType().equals(Types.LONG)) {
builder.setLong(column, (Integer) value);
}
}
/**
* @param seeds
* @return
*/
private CrawlController getController()
{
CrawlConfig config = new CrawlConfig();
String directoryPath = String.format(task.getCrawlStorageFolder(), UUID.randomUUID());
File dir = new File(directoryPath);
dir.mkdirs();
config.setCrawlStorageFolder(directoryPath);
if (task.getMaxDepthOfCrawling().isPresent()) {
config.setMaxDepthOfCrawling(task.getMaxDepthOfCrawling().get());
}
config.setMaxPagesToFetch(task.getMaxPagesToFetch());
if (task.getPolitenessDelay().isPresent()) {
config.setPolitenessDelay(task.getPolitenessDelay().get());
}
if (task.getUserAgentString().isPresent()) {
config.setUserAgentString(task.getUserAgentString().get());
}
if (task.getSocketTimeout().isPresent()) {
config.setSocketTimeout(task.getSocketTimeout().get());
}
if (task.getConnectionTimeout().isPresent()) {
config.setConnectionTimeout(task.getConnectionTimeout().get());
}
PageFetcher pageFetcher = new PageFetcher(config);
RobotstxtConfig robotstxtConfig = new RobotstxtConfig();
RobotstxtServer robotstxtServer = new RobotstxtServer(robotstxtConfig, pageFetcher);
CrawlController crawlController = null;
try {
crawlController = new CrawlController(config, pageFetcher, robotstxtServer);
}
catch (Exception e) {
e.printStackTrace();
}
return crawlController;
}
};
}
}
| src/main/java/org/embulk/filter/crawler/CrawlerFilterPlugin.java | package org.embulk.filter.crawler;
import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.embulk.config.Config;
import org.embulk.config.ConfigDefault;
import org.embulk.config.ConfigSource;
import org.embulk.config.Task;
import org.embulk.config.TaskSource;
import org.embulk.spi.Column;
import org.embulk.spi.Exec;
import org.embulk.spi.FilterPlugin;
import org.embulk.spi.Page;
import org.embulk.spi.PageBuilder;
import org.embulk.spi.PageOutput;
import org.embulk.spi.PageReader;
import org.embulk.spi.Schema;
import org.embulk.spi.type.Types;
import org.slf4j.Logger;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import edu.uci.ics.crawler4j.crawler.CrawlConfig;
import edu.uci.ics.crawler4j.crawler.CrawlController;
import edu.uci.ics.crawler4j.fetcher.PageFetcher;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtConfig;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtServer;
public class CrawlerFilterPlugin
implements FilterPlugin
{
private static final Logger logger = Exec.getLogger(CrawlerFilterPlugin.class);
public interface PluginTask
extends Task
{
@Config("max_depth_of_crawling")
@ConfigDefault("null")
public Optional<Integer> getMaxDepthOfCrawling();
@Config("number_of_crawlers")
@ConfigDefault("1")
public int getNumberOfCrawlers();
@Config("max_pages_to_fetch")
@ConfigDefault("-1")
public int getMaxPagesToFetch();
@Config("target_key")
public String getTargetKey();
@Config("crawl_storage_folder")
public String getCrawlStorageFolder();
@Config("politeness_delay")
@ConfigDefault("null")
public Optional<Integer> getPolitenessDelay();
@Config("user_agent_string")
@ConfigDefault("null")
public Optional<String> getUserAgentString();
@Config("keep_input")
@ConfigDefault("true")
public boolean getKeepInput();
@Config("output_prefix")
@ConfigDefault("\"\"")
public String getOutputPrefix();
@Config("should_not_visit_pattern")
@ConfigDefault("null")
public Optional<String> getShouldNotVisitPattern();
@Config("connection_timeout")
@ConfigDefault("null")
public Optional<Integer> getConnectionTimeout();
@Config("socket_timeout")
@ConfigDefault("null")
public Optional<Integer> getSocketTimeout();
}
@Override
public void transaction(ConfigSource config, Schema inputSchema,
FilterPlugin.Control control)
{
PluginTask task = config.loadConfig(PluginTask.class);
ImmutableList.Builder<Column> builder = ImmutableList.builder();
int i = 0;
builder.addAll(getOutputColumns(i, task.getOutputPrefix()));
Schema outputSchema = new Schema(builder.build());
control.run(task.dump(), outputSchema);
}
/**
* @param i
* @param outputPrefix
* @return
*/
private List<Column> getOutputColumns(int i, String outputPrefix) {
List<Column> list = Lists.newArrayList();
list.add(new Column(i++, outputPrefix + Constants.URL, Types.STRING));
list.add(new Column(i++, outputPrefix + Constants.DOMAIN, Types.STRING));
list.add(new Column(i++, outputPrefix + Constants.SUBDOMAIN, Types.STRING));
list.add(new Column(i++, outputPrefix + Constants.PATH, Types.STRING));
list.add(new Column(i++, outputPrefix + Constants.ANCHOR, Types.STRING));
list.add(new Column(i++, outputPrefix + Constants.PARENT_URL, Types.STRING));
list.add(new Column(i++, outputPrefix + Constants.CONTENT_CHARSET, Types.STRING));
list.add(new Column(i++, outputPrefix + Constants.REDIRECT_TO_URL, Types.STRING));
list.add(new Column(i++, outputPrefix + Constants.LANGUAGE, Types.STRING));
list.add(new Column(i++, outputPrefix + Constants.STATUS_CODE, Types.LONG));
list.add(new Column(i++, outputPrefix + Constants.TITLE, Types.STRING));
list.add(new Column(i++, outputPrefix + Constants.TEXT, Types.STRING));
list.add(new Column(i++, outputPrefix + Constants.HTML, Types.STRING));
return list;
}
@Override
public PageOutput open(TaskSource taskSource, final Schema inputSchema,
final Schema outputSchema, final PageOutput output)
{
final PluginTask task = taskSource.loadTask(PluginTask.class);
final Column keyNameColumn = inputSchema.lookupColumn(task.getTargetKey());
return new PageOutput() {
private PageReader reader = new PageReader(inputSchema);
private PageBuilder builder = new PageBuilder(Exec.getBufferAllocator(), outputSchema, output);
@Override
public void finish()
{
builder.finish();
}
@Override
public void close()
{
builder.close();
}
@Override
public void add(Page page)
{
CrawlController controller = getController();
reader.setPage(page);
while (reader.nextRecord()) {
controller.addSeed(reader.getString(keyNameColumn));
}
Map<String, Object> customData = Maps.newHashMap();
customData.put("output_prefix", task.getOutputPrefix());
if (task.getShouldNotVisitPattern().isPresent()) {
customData.put("should_not_visit_pattern", task.getShouldNotVisitPattern().get());
}
controller.setCustomData(customData);
controller.start(EmbulkCrawler.class, task.getNumberOfCrawlers());
for (Object object : controller.getCrawlersLocalData()) {
CrawlStat crawlStat = (CrawlStat) object;
for (Map<String, Object> map : crawlStat.getPages()) {
for (Column outputColumn : outputSchema.getColumns()) {
final Object value = map.get(outputColumn.getName());
setValue(value, outputColumn);
}
builder.addRecord();
}
}
}
/**
* @param seeds
*/
private void setValue(Object value, Column column)
{
if (value == null) {
builder.setNull(column);
}
else if (column.getType().equals(Types.STRING)) {
builder.setString(column, (String) value);
}
else if (column.getType().equals(Types.LONG)) {
builder.setLong(column, (Integer) value);
}
}
/**
* @param seeds
* @return
*/
private CrawlController getController()
{
CrawlConfig config = new CrawlConfig();
String directoryPath = String.format(task.getCrawlStorageFolder(), UUID.randomUUID());
File dir = new File(directoryPath);
dir.mkdirs();
config.setCrawlStorageFolder(directoryPath);
if (task.getMaxDepthOfCrawling().isPresent()) {
config.setMaxDepthOfCrawling(task.getMaxDepthOfCrawling().get());
}
config.setMaxPagesToFetch(task.getMaxPagesToFetch());
if (task.getPolitenessDelay().isPresent()) {
config.setPolitenessDelay(task.getPolitenessDelay().get());
}
if (task.getUserAgentString().isPresent()) {
config.setUserAgentString(task.getUserAgentString().get());
}
if (task.getSocketTimeout().isPresent()) {
config.setSocketTimeout(task.getSocketTimeout().get());
}
if (task.getConnectionTimeout().isPresent()) {
config.setConnectionTimeout(task.getConnectionTimeout().get());
}
PageFetcher pageFetcher = new PageFetcher(config);
RobotstxtConfig robotstxtConfig = new RobotstxtConfig();
RobotstxtServer robotstxtServer = new RobotstxtServer(robotstxtConfig, pageFetcher);
CrawlController crawlController = null;
try {
crawlController = new CrawlController(config, pageFetcher, robotstxtServer);
}
catch (Exception e) {
e.printStackTrace();
}
return crawlController;
}
};
}
}
| fix bug. Not crawling with not more than 2 Numberofcrwlers.
| src/main/java/org/embulk/filter/crawler/CrawlerFilterPlugin.java | fix bug. Not crawling with not more than 2 Numberofcrwlers. | <ide><path>rc/main/java/org/embulk/filter/crawler/CrawlerFilterPlugin.java
<ide> public Optional<Integer> getMaxDepthOfCrawling();
<ide>
<ide> @Config("number_of_crawlers")
<del> @ConfigDefault("1")
<add> @ConfigDefault("2")
<ide> public int getNumberOfCrawlers();
<ide>
<ide> @Config("max_pages_to_fetch")
<ide> customData.put("should_not_visit_pattern", task.getShouldNotVisitPattern().get());
<ide> }
<ide> controller.setCustomData(customData);
<del> controller.start(EmbulkCrawler.class, task.getNumberOfCrawlers());
<add> controller.start(EmbulkCrawler.class, task.getNumberOfCrawlers() < 2 ? 2 : task.getNumberOfCrawlers());
<ide> for (Object object : controller.getCrawlersLocalData()) {
<ide> CrawlStat crawlStat = (CrawlStat) object;
<ide> for (Map<String, Object> map : crawlStat.getPages()) { |
|
JavaScript | mit | e0bc8b7f34d3a4d0878672cba5ff4eda195bb286 | 0 | manifoldjs/ManifoldJS | 'use strict';
var utils = require('../common/utils'),
url = require('url'),
fs = require('fs'),
path = require('path'),
request = require('request'),
archiver = require('archiver'),
cloudappx = require('cloudappx-server'),
log = require('loglevel'),
os = require('os');
var version = require('../common/version');
var metadataItemTemplate= '\r\n\t\t<build:Item Name ="{0}" Version ="{1}" />';
var serviceEndpoint = 'http://cloudappx.azurewebsites.net';
var baseAcurMatch;
function findRuleByMatch(acurList, match) {
for (var i = 0; i < acurList.length; i++) {
if (acurList[i].match === match) {
return acurList[i];
}
}
}
function tryAddAcurToList(acurList, acur) {
// if match is '*', replace match with base match
if (acur.match === '*') {
acur.match = baseAcurMatch;
}
// if the match url ends with '/*', remove the '*'.
if (acur.match.indexOf('/*', acur.match.length - 2) !== -1) {
acur.match = acur.match.substring(0, acur.match.length - 1);
}
// ensure rule is not duplicated
var rule = findRuleByMatch(acurList, acur.match);
if (!rule) {
// if no type is specified in rule and access is 'none', ignore the rule
if (!acur.type && acur.runtimeAccess === 'none') {
return;
}
rule = { match: acur.match };
acurList.push(rule);
}
// override the runtimeAccess property (if any) or use default value ('none')
rule.runtimeAccess = acur.runtimeAccess || rule.runtimeAccess || 'none';
// override the type (if any) or use default value ('include')
rule.type = acur.type || rule.type || 'include';
}
function replaceManifestValues(w3cManifestInfo, content) {
var w3cManifest = w3cManifestInfo.content;
var timestamp = w3cManifestInfo.timestamp || new Date().toISOString().replace(/T/, ' ').replace(/\.[0-9]+/, ' ');
var replacedContent = content;
var guid = utils.newGuid();
var applicationId = utils.sanitizeName(w3cManifest.short_name);
// Update general properties
replacedContent = replacedContent.replace(/{IdentityName}/g, guid)
.replace(/{PhoneProductId}/g, guid)
.replace(/{DisplayName}/g, w3cManifest.short_name)
.replace(/{ApplicationId}/g, applicationId)
.replace(/{StartPage}/g, w3cManifest.start_url)
.replace(/{DisplayName}/g, w3cManifest.short_name)
.replace(/{Description}/g, w3cManifest.name || w3cManifest.short_name)
.replace(/{RotationPreference}/g, w3cManifest.orientation || 'portrait')
.replace(/{ManifoldJSVersion}/g, version.getCurrentPackageVersion())
.replace(/{GeneratedFrom}/g, w3cManifestInfo.generatedFrom || 'API')
.replace(/{GenerationDate}/g, timestamp)
.replace(/{theme_color}/g, w3cManifest.theme_color || 'blue');
// Add additional metadata items
var metadataItems = '';
if (w3cManifestInfo.generatedUrl) {
metadataItems += metadataItemTemplate.replace(/\{0}/g, 'GeneratedURL')
.replace(/\{1}/g, w3cManifestInfo.generatedUrl);
}
replacedContent = replacedContent.replace(/{MetadataItems}/g, metadataItems);
// Update ACURs
var indentationChars = '\r\n\t\t\t\t';
var applicationContentUriRules = '';
var acurList = [];
// Set the base acur rule using the start_url's base url
baseAcurMatch = url.resolve(w3cManifest.start_url, '/');
if (w3cManifest.scope && w3cManifest.scope.length) {
// If the scope is defined, the base access rule is defined by the scope
var parsedScopeUrl = url.parse(w3cManifest.scope);
if (parsedScopeUrl.host && parsedScopeUrl.protocol) {
baseAcurMatch = w3cManifest.scope;
} else {
baseAcurMatch = url.resolve(baseAcurMatch, w3cManifest.scope);
}
}
// Add base rule to ACUR list
tryAddAcurToList(acurList, { 'match': baseAcurMatch, 'type': 'include' });
// Add rules from mjs_access_whitelist to ACUR list
// TODO: mjs_access_whitelist is deprecated. Should be removed in future versions
if (w3cManifest.mjs_access_whitelist) {
w3cManifest.mjs_access_whitelist.forEach(function(whitelistRule) {
tryAddAcurToList(acurList, { 'match': whitelistRule.url, 'type': 'include', 'runtimeAccess': whitelistRule.apiAccess });
});
}
// Add rules from mjs_extended_scope to ACUR list
if (w3cManifest.mjs_extended_scope) {
w3cManifest.mjs_extended_scope.forEach(function(scopeRule) {
tryAddAcurToList(acurList, { 'match': scopeRule, 'type': 'include' });
});
}
// Add rules from mjs_api_access to ACUR list
if (w3cManifest.mjs_api_access) {
w3cManifest.mjs_api_access.forEach(function (apiRule) {
// ensure rule applies to current platform
if (apiRule.platform && apiRule.platform.split(';')
.map(function (item) { return item.trim(); })
.indexOf('windows10') < 0) {
return false;
}
tryAddAcurToList(acurList, { match: apiRule.match, runtimeAccess: apiRule.access || 'all' });
});
}
// Create XML entries for ACUR rules
acurList.forEach(function (acur) {
applicationContentUriRules += indentationChars + '<uap:Rule Type="' + acur.type + '" WindowsRuntimeAccess="' + acur.runtimeAccess + '" Match="' + acur.match + '" />';
});
replacedContent = replacedContent.replace(/{ApplicationContentUriRules}/g, applicationContentUriRules);
return replacedContent;
}
function invokeCloudAppX(appName, appFolder, outputPath, callback) {
var archive = archiver('zip');
var zipFile = path.join(os.tmpdir(), appName + '.zip');
var output = fs.createWriteStream(zipFile);
archive.on('error', function (err) {
return callback && callback(err);
});
archive.pipe(output);
archive.directory(appFolder, appName);
archive.finalize();
output.on('close', function () {
var options = {
method: 'POST',
url: url.resolve(serviceEndpoint, '/v2/build'),
encoding: 'binary'
};
log.debug('Invoking the CloudAppX service...');
var req = request.post(options, function (err, resp, body) {
if (err) {
return callback && callback(err);
}
if (resp.statusCode !== 200) {
return callback && callback(new Error('Failed to create the package. The CloudAppX service returned an error - ' + resp.statusMessage + ' (' + resp.statusCode + '): ' + body));
}
fs.writeFile(outputPath, body, { 'encoding': 'binary' }, function (err) {
if (err) {
return callback && callback(err);
}
fs.unlink(zipFile, function (err) {
return callback && callback(err);
});
});
});
req.form().append('xml', fs.createReadStream(zipFile));
});
}
// Quick sanity check to ensure that the placeholder parameters in the manifest
// have been replaced by the user with their publisher details before generating
// a package.
function validateManifestPublisherDetails(appFolder, callback) {
var manifestPath = path.join(appFolder, 'appxmanifest.xml');
fs.readFile(manifestPath, 'utf8', function (err, data) {
if (err) {
err = new Error('The specified path does not contain a valid app manifest file - ' + err.message);
}
if (!err) {
var packageIdentityPlaceholders = /<Identity.*(Name\s*=\s*"INSERT-YOUR-PACKAGE-IDENTITY-NAME-HERE"|Publisher\s*=\s*"CN=INSERT-YOUR-PACKAGE-IDENTITY-PUBLISHER-HERE")/g;
var publisherDisplayNamePlaceholder = /<PublisherDisplayName>\s*INSERT-YOUR-PACKAGE-PROPERTIES-PUBLISHERDISPLAYNAME-HERE\s*<\/PublisherDisplayName>/g;
if (packageIdentityPlaceholders.test(data) || publisherDisplayNamePlaceholder.test(data)) {
err = new Error('You must register the app in the Windows Store and obtain the Package/Identity/Name, Package/Identity/Publisher, and Package/Properties/PublisherDisplayName details. Update the placeholders in the appxmanifest.xml file with this information before creating the App Store package.');
}
}
return callback && callback(err);
});
}
var makeAppx = function (appFolder, outputPath, callback) {
var outputData = path.parse(outputPath);
var options = { 'dir': appFolder, 'name': outputData.name, 'out': outputData.dir };
validateManifestPublisherDetails(appFolder, function (err) {
if (err) {
return callback && callback(err);
}
cloudappx.makeAppx(options).then(
function () {
return callback && callback();
},
function () {
log.debug('Unable to create the package locally. Invoking the CloudAppX service instead...');
invokeCloudAppX(outputData.name, appFolder, outputPath, function (err) {
return callback && callback(err);
});
});
});
};
module.exports = {
replaceManifestValues: replaceManifestValues,
makeAppx: makeAppx
};
| lib/platformUtils/windows10Utils.js | 'use strict';
var utils = require('../common/utils'),
url = require('url'),
fs = require('fs'),
path = require('path'),
request = require('request'),
archiver = require('archiver'),
cloudappx = require('cloudappx-server'),
log = require('loglevel'),
os = require('os');
var version = require('../common/version');
var metadataItemTemplate= '\r\n\t\t<build:Item Name ="{0}" Version ="{1}" />';
var serviceEndpoint = 'http://cloudappx.azurewebsites.net';
var baseAcurMatch;
function findRuleByMatch(acurList, match) {
for (var i = 0; i < acurList.length; i++) {
if (acurList[i].match === match) {
return acurList[i];
}
}
}
function tryAddAcurToList(acurList, acur) {
// if match is '*', replace match with base match
if (acur.match === '*') {
acur.match = baseAcurMatch;
}
// if the match url ends with '/*', remove the '*'.
if (acur.match.indexOf('/*', acur.match.length - 2) !== -1) {
acur.match = acur.match.substring(0, acur.match.length - 1);
}
// ensure rule is not duplicated
var rule = findRuleByMatch(acurList, acur.match);
if (!rule) {
// if no type is specified in rule and access is 'none', ignore the rule
if (!acur.type && acur.runtimeAccess === 'none') {
return;
}
rule = { match: acur.match };
acurList.push(rule);
}
// override the runtimeAccess property (if any) or use default value ('none')
rule.runtimeAccess = acur.runtimeAccess || rule.runtimeAccess || 'none';
// override the type (if any) or use default value ('include')
rule.type = acur.type || rule.type || 'include';
}
function replaceManifestValues(w3cManifestInfo, content) {
var w3cManifest = w3cManifestInfo.content;
var timestamp = w3cManifestInfo.timestamp || new Date().toISOString().replace(/T/, ' ').replace(/\.[0-9]+/, ' ');
var replacedContent = content;
var guid = utils.newGuid();
var applicationId = utils.sanitizeName(w3cManifest.short_name);
// Update general properties
replacedContent = replacedContent.replace(/{IdentityName}/g, guid)
.replace(/{PhoneProductId}/g, guid)
.replace(/{DisplayName}/g, w3cManifest.short_name)
.replace(/{ApplicationId}/g, applicationId)
.replace(/{StartPage}/g, w3cManifest.start_url)
.replace(/{DisplayName}/g, w3cManifest.short_name)
.replace(/{Description}/g, w3cManifest.name || w3cManifest.short_name)
.replace(/{RotationPreference}/g, w3cManifest.orientation || 'portrait')
.replace(/{ManifoldJSVersion}/g, version.getCurrentPackageVersion())
.replace(/{GeneratedFrom}/g, w3cManifestInfo.generatedFrom || 'API')
.replace(/{GenerationDate}/g, timestamp)
.replace(/{theme_color}/g, w3cManifest.theme_color || 'blue');
// Add additional metadata items
var metadataItems = '';
if (w3cManifestInfo.generatedUrl) {
metadataItems += metadataItemTemplate.replace(/\{0}/g, 'GeneratedURL')
.replace(/\{1}/g, w3cManifestInfo.generatedUrl);
}
replacedContent = replacedContent.replace(/{MetadataItems}/g, metadataItems);
// Update ACURs
var indentationChars = '\r\n\t\t\t\t';
var applicationContentUriRules = '';
var acurList = [];
// Set the base acur rule using the start_url's base url
baseAcurMatch = url.resolve(w3cManifest.start_url, '/');
if (w3cManifest.scope && w3cManifest.scope.length) {
// If the scope is defined, the base access rule is defined by the scope
var parsedScopeUrl = url.parse(w3cManifest.scope);
if (parsedScopeUrl.host && parsedScopeUrl.protocol) {
baseAcurMatch = w3cManifest.scope;
} else {
baseAcurMatch = url.resolve(baseAcurMatch, w3cManifest.scope);
}
}
// Add base rule to ACUR list
tryAddAcurToList(acurList, { 'match': baseAcurMatch, 'type': 'include' });
// Add rules from mjs_access_whitelist to ACUR list
// TODO: mjs_access_whitelist is deprecated. Should be removed in future versions
if (w3cManifest.mjs_access_whitelist) {
w3cManifest.mjs_access_whitelist.forEach(function(whitelistRule) {
tryAddAcurToList(acurList, { 'match': whitelistRule.url, 'type': 'include', 'runtimeAccess': whitelistRule.apiAccess });
});
}
// Add rules from mjs_extended_scope to ACUR list
if (w3cManifest.mjs_extended_scope) {
w3cManifest.mjs_extended_scope.forEach(function(whitelistRule) {
tryAddAcurToList(acurList, { 'match': whitelistRule.url, 'type': 'include' });
});
}
// Add rules from mjs_api_access to ACUR list
if (w3cManifest.mjs_api_access) {
w3cManifest.mjs_api_access.forEach(function (apiRule) {
// ensure rule applies to current platform
if (apiRule.platform && apiRule.platform.split(';')
.map(function (item) { return item.trim(); })
.indexOf('windows10') < 0) {
return false;
}
tryAddAcurToList(acurList, { match: apiRule.match, runtimeAccess: apiRule.access || 'all' });
});
}
// Create XML entries for ACUR rules
acurList.forEach(function (acur) {
applicationContentUriRules += indentationChars + '<uap:Rule Type="' + acur.type + '" WindowsRuntimeAccess="' + acur.runtimeAccess + '" Match="' + acur.match + '" />';
});
replacedContent = replacedContent.replace(/{ApplicationContentUriRules}/g, applicationContentUriRules);
return replacedContent;
}
function invokeCloudAppX(appName, appFolder, outputPath, callback) {
var archive = archiver('zip');
var zipFile = path.join(os.tmpdir(), appName + '.zip');
var output = fs.createWriteStream(zipFile);
archive.on('error', function (err) {
return callback && callback(err);
});
archive.pipe(output);
archive.directory(appFolder, appName);
archive.finalize();
output.on('close', function () {
var options = {
method: 'POST',
url: url.resolve(serviceEndpoint, '/v2/build'),
encoding: 'binary'
};
log.debug('Invoking the CloudAppX service...');
var req = request.post(options, function (err, resp, body) {
if (err) {
return callback && callback(err);
}
if (resp.statusCode !== 200) {
return callback && callback(new Error('Failed to create the package. The CloudAppX service returned an error - ' + resp.statusMessage + ' (' + resp.statusCode + '): ' + body));
}
fs.writeFile(outputPath, body, { 'encoding': 'binary' }, function (err) {
if (err) {
return callback && callback(err);
}
fs.unlink(zipFile, function (err) {
return callback && callback(err);
});
});
});
req.form().append('xml', fs.createReadStream(zipFile));
});
}
// Quick sanity check to ensure that the placeholder parameters in the manifest
// have been replaced by the user with their publisher details before generating
// a package.
function validateManifestPublisherDetails(appFolder, callback) {
var manifestPath = path.join(appFolder, 'appxmanifest.xml');
fs.readFile(manifestPath, 'utf8', function (err, data) {
if (err) {
err = new Error('The specified path does not contain a valid app manifest file - ' + err.message);
}
if (!err) {
var packageIdentityPlaceholders = /<Identity.*(Name\s*=\s*"INSERT-YOUR-PACKAGE-IDENTITY-NAME-HERE"|Publisher\s*=\s*"CN=INSERT-YOUR-PACKAGE-IDENTITY-PUBLISHER-HERE")/g;
var publisherDisplayNamePlaceholder = /<PublisherDisplayName>\s*INSERT-YOUR-PACKAGE-PROPERTIES-PUBLISHERDISPLAYNAME-HERE\s*<\/PublisherDisplayName>/g;
if (packageIdentityPlaceholders.test(data) || publisherDisplayNamePlaceholder.test(data)) {
err = new Error('You must register the app in the Windows Store and obtain the Package/Identity/Name, Package/Identity/Publisher, and Package/Properties/PublisherDisplayName details. Update the placeholders in the appxmanifest.xml file with this information before creating the App Store package.');
}
}
return callback && callback(err);
});
}
var makeAppx = function (appFolder, outputPath, callback) {
var outputData = path.parse(outputPath);
var options = { 'dir': appFolder, 'name': outputData.name, 'out': outputData.dir };
validateManifestPublisherDetails(appFolder, function (err) {
if (err) {
return callback && callback(err);
}
cloudappx.makeAppx(options).then(
function () {
return callback && callback();
},
function () {
log.debug('Unable to create the package locally. Invoking the CloudAppX service instead...');
invokeCloudAppX(outputData.name, appFolder, outputPath, function (err) {
return callback && callback(err);
});
});
});
};
module.exports = {
replaceManifestValues: replaceManifestValues,
makeAppx: makeAppx
};
| Fixed issue processing extended_scope rules in Windows 10
| lib/platformUtils/windows10Utils.js | Fixed issue processing extended_scope rules in Windows 10 | <ide><path>ib/platformUtils/windows10Utils.js
<ide>
<ide> // Add rules from mjs_extended_scope to ACUR list
<ide> if (w3cManifest.mjs_extended_scope) {
<del> w3cManifest.mjs_extended_scope.forEach(function(whitelistRule) {
<del> tryAddAcurToList(acurList, { 'match': whitelistRule.url, 'type': 'include' });
<add> w3cManifest.mjs_extended_scope.forEach(function(scopeRule) {
<add> tryAddAcurToList(acurList, { 'match': scopeRule, 'type': 'include' });
<ide> });
<ide> }
<ide> |
|
Java | bsd-2-clause | error: pathspec 'src/com/jme/widget/image/WidgetImage.java' did not match any file(s) known to git
| 7f1839ac382c93b545b882e50645eaf8b34805ec | 1 | chototsu/MikuMikuStudio,chototsu/MikuMikuStudio,chototsu/MikuMikuStudio,chototsu/MikuMikuStudio | /*
* Copyright (c) 2003, jMonkeyEngine - Mojo Monkey Coding
* 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 Mojo Monkey Coding, jME, jMonkey Engine, 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 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.
*
*/
package com.jme.widget.image;
import com.jme.image.Image;
import com.jme.math.Vector2f;
import com.jme.renderer.Renderer;
import com.jme.widget.WidgetAlignmentType;
import com.jme.widget.WidgetAbstractImpl;
import com.jme.widget.WidgetInsets;
import com.jme.widget.WidgetRenderer;
import com.jme.widget.impl.lwjgl.WidgetLWJGLImage;
import com.jme.widget.renderer.WidgetRendererFactory;
/**
* <code>ImageWidget</code>
* @author Mike Kienenberger
*
* <code>ImageWidget</code> is a widget that draws a 2d image.
*
* The image may be scaled by four methods:
* SCALE_MODE_NONE - The image will not be scaled.
* SCALE_MODE_SIZE_TO_FIT - The image will be scaled to fill the size of the widget. Alignment is unused.
* SCALE_MODE_ABSOLUTE - The image is scaled vertically and horizontally by a percentage of the original size of the image.
* SCALE_MODE_RELATIVE - The image is scaled vertically and horizontally by a percentage of the size of the widget.
*
* KNOWN ISSUES:
* Drawing isn't clipped to the widget bounds.
* Alignment code doesn't work properly.
*
* @since 0.6
* @version $$Id: WidgetImage.java,v 1.3 2004-04-18 20:17:12 mojomonkey Exp $$
*/
public class WidgetImage extends WidgetAbstractImpl {
public final static int SCALE_MODE_NONE = 0;
public final static int SCALE_MODE_SIZE_TO_FIT = 1;
public final static int SCALE_MODE_ABSOLUTE = 2;
public final static int SCALE_MODE_RELATIVE = 3;
private int scaleMode = SCALE_MODE_SIZE_TO_FIT;
private float scaleHorizontal = 1f;
private float scaleVertical = 1f;
private Image image;
public WidgetImage() {
this(null, WidgetAlignmentType.ALIGN_NONE, SCALE_MODE_SIZE_TO_FIT);
}
public WidgetImage(Image image) {
this(image, WidgetAlignmentType.ALIGN_NONE, SCALE_MODE_SIZE_TO_FIT);
}
public WidgetImage(Image image, WidgetAlignmentType alignment, int scaleMode) {
super();
setImage(image);
setAlignment(alignment);
setScaleMode(scaleMode);
}
public Image getImage() {
return image;
}
public void setImage(Image image) {
this.image = image;
}
public void onDraw(Renderer r) {
super.onDraw(r);
}
public void draw(Renderer r) {
r.draw(getWidgetRenderer());
}
public void drawBounds(Renderer r) {
//ignore
}
public float getHorizontalScale() {
return scaleHorizontal;
}
public void setHorizontalScale(float f) {
scaleHorizontal = f;
}
public float getVerticalScale() {
return scaleVertical;
}
public void setVerticalScale(float f) {
scaleVertical = f;
}
public int getScaleMode() {
return scaleMode;
}
public void setScaleMode(int mode) {
scaleMode = mode;
}
public void doMouseButtonDown() {
}
public void doMouseButtonUp() {
}
public void setSize(Vector2f size) {
updateWorldBound();
}
public void setSize(int width, int height) {
updateWorldBound();
}
public void setPreferredSize(Vector2f size) {
}
// TODO: Fix alignment code for non-SCALE_MODE_SIZE_TO_FIT
protected void alignCenter(Vector2f size, WidgetInsets insets) {
if (SCALE_MODE_SIZE_TO_FIT == scaleMode) return;
else if (SCALE_MODE_ABSOLUTE == scaleMode)
{
int x = getX() + (int) ((size.x / 2) - (getWidth() * getHorizontalScale() / 2));
int y = getY() + (int) ((size.y / 2) - (getHeight() * getVerticalScale() / 2));
setLocation(x, y);
}
else super.alignCenter(size, insets);
}
// protected void alignWest(Vector2f size, WidgetInsets insets) {
// setX(insets.left);
// }
//
// protected void alignEast(Vector2f size, WidgetInsets insets) {
// setX((int) (size.x - getWidth() - insets.right));
// }
//
// protected void alignNorth(Vector2f size, WidgetInsets insets) {
// setY((int) (size.y - getHeight() - insets.top));
// }
//
// protected void alignSouth(Vector2f size, WidgetInsets insets) {
// setY(insets.bottom);
// }
//
protected void alignWest(Vector2f size, WidgetInsets insets) {
if (SCALE_MODE_SIZE_TO_FIT == scaleMode) return;
super.alignWest(size, insets);
}
protected void alignEast(Vector2f size, WidgetInsets insets) {
if (SCALE_MODE_SIZE_TO_FIT == scaleMode) return;
super.alignEast(size, insets);
}
protected void alignNorth(Vector2f size, WidgetInsets insets) {
if (SCALE_MODE_SIZE_TO_FIT == scaleMode) return;
super.alignNorth(size, insets);
}
protected void alignSouth(Vector2f size, WidgetInsets insets) {
if (SCALE_MODE_SIZE_TO_FIT == scaleMode) return;
super.alignSouth(size, insets);
}
public void setLocation(int x, int y) {
float w = localBound.getWidth();
float h = localBound.getHeight();
super.setLocation(x, y);
localBound.setWidthHeight(w, h);
updateWorldBound();
}
public void setLocation(Vector2f at) {
float w = localBound.getWidth();
float h = localBound.getHeight();
super.setLocation(at);
localBound.setWidthHeight(w, h);
updateWorldBound();
}
public void setX(int x) {
float w = localBound.getWidth();
super.setX(x);
localBound.setWidth(w);
updateWorldBound();
}
public void setY(int y) {
float h = localBound.getHeight();
super.setY(y);
localBound.setHeight(h);
updateWorldBound();
}
// TODO: handle in WidgetRendererFactory
public void initWidgetRenderer() {
WidgetRenderer renderer = null;
renderer = new WidgetLWJGLImage(this);
setWidgetRenderer(renderer);
}
}
| src/com/jme/widget/image/WidgetImage.java | ImageWidget first-pass source by mkienenb
git-svn-id: 5afc437a751a4ff2ced778146f5faadda0b504ab@872 75d07b2b-3a1a-0410-a2c5-0572b91ccdca
| src/com/jme/widget/image/WidgetImage.java | ImageWidget first-pass source by mkienenb | <ide><path>rc/com/jme/widget/image/WidgetImage.java
<add>/*
<add> * Copyright (c) 2003, jMonkeyEngine - Mojo Monkey Coding
<add> * All rights reserved.
<add> *
<add> * Redistribution and use in source and binary forms, with or without
<add> * modification, are permitted provided that the following conditions are met:
<add> *
<add> * Redistributions of source code must retain the above copyright notice, this
<add> * list of conditions and the following disclaimer.
<add> *
<add> * Redistributions in binary form must reproduce the above copyright notice,
<add> * this list of conditions and the following disclaimer in the documentation
<add> * and/or other materials provided with the distribution.
<add> *
<add> * Neither the name of the Mojo Monkey Coding, jME, jMonkey Engine, nor the
<add> * names of its contributors may be used to endorse or promote products derived
<add> * from this software without specific prior written permission.
<add> *
<add> * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
<add> * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
<add> * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
<add> * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
<add> * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
<add> * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
<add> * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
<add> * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
<add> * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
<add> * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
<add> * POSSIBILITY OF SUCH DAMAGE.
<add> *
<add> */
<add>package com.jme.widget.image;
<add>
<add>import com.jme.image.Image;
<add>import com.jme.math.Vector2f;
<add>import com.jme.renderer.Renderer;
<add>import com.jme.widget.WidgetAlignmentType;
<add>import com.jme.widget.WidgetAbstractImpl;
<add>import com.jme.widget.WidgetInsets;
<add>import com.jme.widget.WidgetRenderer;
<add>import com.jme.widget.impl.lwjgl.WidgetLWJGLImage;
<add>import com.jme.widget.renderer.WidgetRendererFactory;
<add>
<add>
<add>/**
<add> * <code>ImageWidget</code>
<add> * @author Mike Kienenberger
<add> *
<add> * <code>ImageWidget</code> is a widget that draws a 2d image.
<add> *
<add> * The image may be scaled by four methods:
<add> * SCALE_MODE_NONE - The image will not be scaled.
<add> * SCALE_MODE_SIZE_TO_FIT - The image will be scaled to fill the size of the widget. Alignment is unused.
<add> * SCALE_MODE_ABSOLUTE - The image is scaled vertically and horizontally by a percentage of the original size of the image.
<add> * SCALE_MODE_RELATIVE - The image is scaled vertically and horizontally by a percentage of the size of the widget.
<add> *
<add> * KNOWN ISSUES:
<add> * Drawing isn't clipped to the widget bounds.
<add> * Alignment code doesn't work properly.
<add> *
<add> * @since 0.6
<add> * @version $$Id: WidgetImage.java,v 1.3 2004-04-18 20:17:12 mojomonkey Exp $$
<add> */
<add>public class WidgetImage extends WidgetAbstractImpl {
<add>
<add> public final static int SCALE_MODE_NONE = 0;
<add> public final static int SCALE_MODE_SIZE_TO_FIT = 1;
<add> public final static int SCALE_MODE_ABSOLUTE = 2;
<add> public final static int SCALE_MODE_RELATIVE = 3;
<add>
<add> private int scaleMode = SCALE_MODE_SIZE_TO_FIT;
<add> private float scaleHorizontal = 1f;
<add> private float scaleVertical = 1f;
<add>
<add> private Image image;
<add>
<add> public WidgetImage() {
<add> this(null, WidgetAlignmentType.ALIGN_NONE, SCALE_MODE_SIZE_TO_FIT);
<add> }
<add>
<add> public WidgetImage(Image image) {
<add> this(image, WidgetAlignmentType.ALIGN_NONE, SCALE_MODE_SIZE_TO_FIT);
<add> }
<add>
<add> public WidgetImage(Image image, WidgetAlignmentType alignment, int scaleMode) {
<add> super();
<add>
<add> setImage(image);
<add> setAlignment(alignment);
<add> setScaleMode(scaleMode);
<add> }
<add>
<add> public Image getImage() {
<add> return image;
<add> }
<add>
<add> public void setImage(Image image) {
<add> this.image = image;
<add> }
<add>
<add> public void onDraw(Renderer r) {
<add> super.onDraw(r);
<add> }
<add>
<add> public void draw(Renderer r) {
<add> r.draw(getWidgetRenderer());
<add> }
<add>
<add> public void drawBounds(Renderer r) {
<add> //ignore
<add> }
<add>
<add> public float getHorizontalScale() {
<add> return scaleHorizontal;
<add> }
<add>
<add> public void setHorizontalScale(float f) {
<add> scaleHorizontal = f;
<add> }
<add>
<add> public float getVerticalScale() {
<add> return scaleVertical;
<add> }
<add>
<add> public void setVerticalScale(float f) {
<add> scaleVertical = f;
<add> }
<add>
<add> public int getScaleMode() {
<add> return scaleMode;
<add> }
<add>
<add> public void setScaleMode(int mode) {
<add> scaleMode = mode;
<add> }
<add>
<add> public void doMouseButtonDown() {
<add> }
<add>
<add> public void doMouseButtonUp() {
<add> }
<add>
<add> public void setSize(Vector2f size) {
<add> updateWorldBound();
<add> }
<add>
<add> public void setSize(int width, int height) {
<add> updateWorldBound();
<add> }
<add>
<add> public void setPreferredSize(Vector2f size) {
<add> }
<add>
<add> // TODO: Fix alignment code for non-SCALE_MODE_SIZE_TO_FIT
<add> protected void alignCenter(Vector2f size, WidgetInsets insets) {
<add> if (SCALE_MODE_SIZE_TO_FIT == scaleMode) return;
<add> else if (SCALE_MODE_ABSOLUTE == scaleMode)
<add> {
<add> int x = getX() + (int) ((size.x / 2) - (getWidth() * getHorizontalScale() / 2));
<add> int y = getY() + (int) ((size.y / 2) - (getHeight() * getVerticalScale() / 2));
<add> setLocation(x, y);
<add> }
<add> else super.alignCenter(size, insets);
<add> }
<add>
<add>// protected void alignWest(Vector2f size, WidgetInsets insets) {
<add>// setX(insets.left);
<add>// }
<add>//
<add>// protected void alignEast(Vector2f size, WidgetInsets insets) {
<add>// setX((int) (size.x - getWidth() - insets.right));
<add>// }
<add>//
<add>// protected void alignNorth(Vector2f size, WidgetInsets insets) {
<add>// setY((int) (size.y - getHeight() - insets.top));
<add>// }
<add>//
<add>// protected void alignSouth(Vector2f size, WidgetInsets insets) {
<add>// setY(insets.bottom);
<add>// }
<add>//
<add> protected void alignWest(Vector2f size, WidgetInsets insets) {
<add> if (SCALE_MODE_SIZE_TO_FIT == scaleMode) return;
<add>
<add> super.alignWest(size, insets);
<add> }
<add>
<add> protected void alignEast(Vector2f size, WidgetInsets insets) {
<add> if (SCALE_MODE_SIZE_TO_FIT == scaleMode) return;
<add>
<add> super.alignEast(size, insets);
<add> }
<add>
<add> protected void alignNorth(Vector2f size, WidgetInsets insets) {
<add> if (SCALE_MODE_SIZE_TO_FIT == scaleMode) return;
<add>
<add> super.alignNorth(size, insets);
<add> }
<add>
<add> protected void alignSouth(Vector2f size, WidgetInsets insets) {
<add> if (SCALE_MODE_SIZE_TO_FIT == scaleMode) return;
<add>
<add> super.alignSouth(size, insets);
<add> }
<add>
<add> public void setLocation(int x, int y) {
<add> float w = localBound.getWidth();
<add> float h = localBound.getHeight();
<add>
<add> super.setLocation(x, y);
<add>
<add> localBound.setWidthHeight(w, h);
<add> updateWorldBound();
<add> }
<add>
<add> public void setLocation(Vector2f at) {
<add> float w = localBound.getWidth();
<add> float h = localBound.getHeight();
<add>
<add> super.setLocation(at);
<add>
<add> localBound.setWidthHeight(w, h);
<add> updateWorldBound();
<add> }
<add>
<add> public void setX(int x) {
<add> float w = localBound.getWidth();
<add> super.setX(x);
<add> localBound.setWidth(w);
<add> updateWorldBound();
<add> }
<add>
<add> public void setY(int y) {
<add> float h = localBound.getHeight();
<add> super.setY(y);
<add> localBound.setHeight(h);
<add> updateWorldBound();
<add> }
<add>
<add> // TODO: handle in WidgetRendererFactory
<add> public void initWidgetRenderer() {
<add> WidgetRenderer renderer = null;
<add>
<add> renderer = new WidgetLWJGLImage(this);
<add>
<add> setWidgetRenderer(renderer);
<add> }
<add>
<add>} |
|
Java | apache-2.0 | 78fa9c54e1cca657d25c50d0afa67d32b33b744b | 0 | MythTV-Clients/MythTV-Service-API | /*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.http.converter.json.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.List;
import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.type.TypeFactory;
import org.codehaus.jackson.type.JavaType;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.util.Assert;
/**
* Implementation of {@link org.springframework.http.converter.HttpMessageConverter HttpMessageConverter}
* that can read and write JSON using <a href="http://jackson.codehaus.org/">Jackson's</a> {@link ObjectMapper}.
*
* <p>This converter can be used to bind to typed beans, or untyped {@link java.util.HashMap HashMap} instances.
*
* <p>By default, this converter supports {@code application/json}. This can be overridden by setting the
* {@link #setSupportedMediaTypes(List) supportedMediaTypes} property.
*
* @author Arjen Poutsma
* @author Roy Clarkson
* @since 1.0
*/
public class MappingJacksonHttpMessageConverter extends AbstractHttpMessageConverter<Object> {
public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
private ObjectMapper objectMapper = new ObjectMapper();
private boolean prefixJson = false;
/**
* Construct a new {@code BindingJacksonHttpMessageConverter}.
*/
public MappingJacksonHttpMessageConverter() {
super(new MediaType("application", "json", DEFAULT_CHARSET));
}
/**
* Set the {@code ObjectMapper} for this view. If not set, a default
* {@link ObjectMapper#ObjectMapper() ObjectMapper} is used.
* <p>Setting a custom-configured {@code ObjectMapper} is one way to take further control of the JSON
* serialization process. For example, an extended {@link org.codehaus.jackson.map.SerializerFactory}
* can be configured that provides custom serializers for specific types. The other option for refining
* the serialization process is to use Jackson's provided annotations on the types to be serialized,
* in which case a custom-configured ObjectMapper is unnecessary.
*/
public void setObjectMapper(ObjectMapper objectMapper) {
Assert.notNull(objectMapper, "ObjectMapper must not be null");
this.objectMapper = objectMapper;
}
/**
* Return the underlying {@code ObjectMapper} for this view.
*/
public ObjectMapper getObjectMapper() {
return this.objectMapper;
}
/**
* Indicate whether the JSON output by this view should be prefixed with "{} &&". Default is false.
* <p>Prefixing the JSON string in this manner is used to help prevent JSON Hijacking.
* The prefix renders the string syntactically invalid as a script so that it cannot be hijacked.
* This prefix does not affect the evaluation of JSON, but if JSON validation is performed on the
* string, the prefix would need to be ignored.
*/
public void setPrefixJson(boolean prefixJson) {
this.prefixJson = prefixJson;
}
@Override
public boolean canRead(Class<?> clazz, MediaType mediaType) {
JavaType javaType = getJavaType(clazz);
return (this.objectMapper.canDeserialize(javaType) && canRead(mediaType));
}
@Override
public boolean canWrite(Class<?> clazz, MediaType mediaType) {
return (this.objectMapper.canSerialize(clazz) && canWrite(mediaType));
}
@Override
protected boolean supports(Class<?> clazz) {
// should not be called, since we override canRead/Write instead
throw new UnsupportedOperationException();
}
@Override
protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage)
throws IOException, HttpMessageNotReadableException {
JavaType javaType = getJavaType(clazz);
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputMessage.getBody()));
String s = reader.readLine();
while(s != null){
System.out.println(s);
s = reader.readLine();
}
reader.reset();
return this.objectMapper.readValue(inputMessage.getBody(), javaType);
}
catch (JsonProcessingException ex) {
throw new HttpMessageNotReadableException("Could not read JSON: " + ex.getMessage(), ex);
}
}
@Override
protected void writeInternal(Object object, HttpOutputMessage outputMessage)
throws IOException, HttpMessageNotWritableException {
JsonEncoding encoding = getJsonEncoding(outputMessage.getHeaders().getContentType());
JsonGenerator jsonGenerator =
this.objectMapper.getJsonFactory().createJsonGenerator(outputMessage.getBody(), encoding);
try {
if (this.prefixJson) {
jsonGenerator.writeRaw("{} && ");
}
this.objectMapper.writeValue(jsonGenerator, object);
}
catch (JsonProcessingException ex) {
throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getMessage(), ex);
}
}
/**
* Return the Jackson {@link JavaType} for the specified class.
* <p>The default implementation returns {@link TypeFactory#type(java.lang.reflect.Type)},
* but this can be overridden in subclasses, to allow for custom generic collection handling.
* For instance:
* <pre class="code">
* protected JavaType getJavaType(Class<?> clazz) {
* if (List.class.isAssignableFrom(clazz)) {
* return TypeFactory.collectionType(ArrayList.class, MyBean.class);
* } else {
* return super.getJavaType(clazz);
* }
* }
* </pre>
* @param clazz the class to return the java type for
* @return the java type
*/
protected JavaType getJavaType(Class<?> clazz) {
return this.objectMapper.getTypeFactory().constructType(clazz);
}
/**
* Determine the JSON encoding to use for the given content type.
* @param contentType the media type as requested by the caller
* @return the JSON encoding to use (never <code>null</code>)
*/
protected JsonEncoding getJsonEncoding(MediaType contentType) {
if (contentType != null && contentType.getCharSet() != null) {
Charset charset = contentType.getCharSet();
for (JsonEncoding encoding : JsonEncoding.values()) {
if (charset.name().equals(encoding.getJavaName())) {
return encoding;
}
}
}
return JsonEncoding.UTF8;
}
}
| src/test/java/org/springframework/http/converter/json/test/MappingJacksonHttpMessageConverter.java | /*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.http.converter.json.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.nio.charset.Charset;
import java.util.List;
import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.type.TypeFactory;
import org.codehaus.jackson.type.JavaType;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.util.Assert;
/**
* Implementation of {@link org.springframework.http.converter.HttpMessageConverter HttpMessageConverter}
* that can read and write JSON using <a href="http://jackson.codehaus.org/">Jackson's</a> {@link ObjectMapper}.
*
* <p>This converter can be used to bind to typed beans, or untyped {@link java.util.HashMap HashMap} instances.
*
* <p>By default, this converter supports {@code application/json}. This can be overridden by setting the
* {@link #setSupportedMediaTypes(List) supportedMediaTypes} property.
*
* @author Arjen Poutsma
* @author Roy Clarkson
* @since 1.0
*/
public class MappingJacksonHttpMessageConverter extends AbstractHttpMessageConverter<Object> {
public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
private ObjectMapper objectMapper = new ObjectMapper();
private boolean prefixJson = false;
/**
* Construct a new {@code BindingJacksonHttpMessageConverter}.
*/
public MappingJacksonHttpMessageConverter() {
super(new MediaType("application", "json", DEFAULT_CHARSET));
}
/**
* Set the {@code ObjectMapper} for this view. If not set, a default
* {@link ObjectMapper#ObjectMapper() ObjectMapper} is used.
* <p>Setting a custom-configured {@code ObjectMapper} is one way to take further control of the JSON
* serialization process. For example, an extended {@link org.codehaus.jackson.map.SerializerFactory}
* can be configured that provides custom serializers for specific types. The other option for refining
* the serialization process is to use Jackson's provided annotations on the types to be serialized,
* in which case a custom-configured ObjectMapper is unnecessary.
*/
public void setObjectMapper(ObjectMapper objectMapper) {
Assert.notNull(objectMapper, "ObjectMapper must not be null");
this.objectMapper = objectMapper;
}
/**
* Return the underlying {@code ObjectMapper} for this view.
*/
public ObjectMapper getObjectMapper() {
return this.objectMapper;
}
/**
* Indicate whether the JSON output by this view should be prefixed with "{} &&". Default is false.
* <p>Prefixing the JSON string in this manner is used to help prevent JSON Hijacking.
* The prefix renders the string syntactically invalid as a script so that it cannot be hijacked.
* This prefix does not affect the evaluation of JSON, but if JSON validation is performed on the
* string, the prefix would need to be ignored.
*/
public void setPrefixJson(boolean prefixJson) {
this.prefixJson = prefixJson;
}
@Override
public boolean canRead(Class<?> clazz, MediaType mediaType) {
JavaType javaType = getJavaType(clazz);
return (this.objectMapper.canDeserialize(javaType) && canRead(mediaType));
}
@Override
public boolean canWrite(Class<?> clazz, MediaType mediaType) {
return (this.objectMapper.canSerialize(clazz) && canWrite(mediaType));
}
@Override
protected boolean supports(Class<?> clazz) {
// should not be called, since we override canRead/Write instead
throw new UnsupportedOperationException();
}
@Override
protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage)
throws IOException, HttpMessageNotReadableException {
JavaType javaType = getJavaType(clazz);
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputMessage.getBody()));
String s = reader.readLine();
while(s != null){
System.out.println(s);
s = reader.readLine();
}
reader.reset();
return this.objectMapper.readValue(inputMessage.getBody(), javaType);
}
catch (JsonProcessingException ex) {
throw new HttpMessageNotReadableException("Could not read JSON: " + ex.getMessage(), ex);
}
}
@Override
protected void writeInternal(Object object, HttpOutputMessage outputMessage)
throws IOException, HttpMessageNotWritableException {
JsonEncoding encoding = getJsonEncoding(outputMessage.getHeaders().getContentType());
JsonGenerator jsonGenerator =
this.objectMapper.getJsonFactory().createJsonGenerator(outputMessage.getBody(), encoding);
try {
if (this.prefixJson) {
jsonGenerator.writeRaw("{} && ");
}
this.objectMapper.writeValue(jsonGenerator, object);
}
catch (JsonProcessingException ex) {
throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getMessage(), ex);
}
}
/**
* Return the Jackson {@link JavaType} for the specified class.
* <p>The default implementation returns {@link TypeFactory#type(java.lang.reflect.Type)},
* but this can be overridden in subclasses, to allow for custom generic collection handling.
* For instance:
* <pre class="code">
* protected JavaType getJavaType(Class<?> clazz) {
* if (List.class.isAssignableFrom(clazz)) {
* return TypeFactory.collectionType(ArrayList.class, MyBean.class);
* } else {
* return super.getJavaType(clazz);
* }
* }
* </pre>
* @param clazz the class to return the java type for
* @return the java type
*/
protected JavaType getJavaType(Class<?> clazz) {
return this.objectMapper.getTypeFactory().constructType(clazz);
}
/**
* Determine the JSON encoding to use for the given content type.
* @param contentType the media type as requested by the caller
* @return the JSON encoding to use (never <code>null</code>)
*/
protected JsonEncoding getJsonEncoding(MediaType contentType) {
if (contentType != null && contentType.getCharSet() != null) {
Charset charset = contentType.getCharSet();
for (JsonEncoding encoding : JsonEncoding.values()) {
if (charset.name().equals(encoding.getJavaName())) {
return encoding;
}
}
}
return JsonEncoding.UTF8;
}
}
| Removed unused import | src/test/java/org/springframework/http/converter/json/test/MappingJacksonHttpMessageConverter.java | Removed unused import | <ide><path>rc/test/java/org/springframework/http/converter/json/test/MappingJacksonHttpMessageConverter.java
<ide> import java.io.BufferedReader;
<ide> import java.io.IOException;
<ide> import java.io.InputStreamReader;
<del>import java.io.StringReader;
<ide> import java.nio.charset.Charset;
<ide> import java.util.List;
<ide>
<ide> import org.codehaus.jackson.map.ObjectMapper;
<ide> import org.codehaus.jackson.map.type.TypeFactory;
<ide> import org.codehaus.jackson.type.JavaType;
<del>
<ide> import org.springframework.http.HttpInputMessage;
<ide> import org.springframework.http.HttpOutputMessage;
<ide> import org.springframework.http.MediaType; |
|
JavaScript | apache-2.0 | 50261908961abcd2274e961ae2e5843eb967bd50 | 0 | snowdream/awesome-android,snowdream/awesome-android | var gulp = require('gulp');
var ghPages = require('gulp-gh-pages');
gulp.task('deploy', function() {
return gulp.src('./website/**/*')
.pipe(ghPages({remoteUrl:"[email protected]:snowdream/awesome-android.git",message:"Create gh-pages branch via GitHub https://travis-ci.org/ [timestamp]"}));
});
| gulpfile.js | var gulp = require('gulp');
var ghPages = require('gulp-gh-pages');
gulp.task('deploy', function() {
return gulp.src('./website/**/*')
.pipe(ghPages({message:"Create gh-pages branch via GitHub https://travis-ci.org/ [timestamp]"}));
});
| Add: .travis
| gulpfile.js | Add: .travis | <ide><path>ulpfile.js
<ide>
<ide> gulp.task('deploy', function() {
<ide> return gulp.src('./website/**/*')
<del> .pipe(ghPages({message:"Create gh-pages branch via GitHub https://travis-ci.org/ [timestamp]"}));
<add> .pipe(ghPages({remoteUrl:"[email protected]:snowdream/awesome-android.git",message:"Create gh-pages branch via GitHub https://travis-ci.org/ [timestamp]"}));
<ide> });
<ide> |
|
Java | mit | 9c05a0bacbb52cf48e400b75c75a17dd0be1871b | 0 | TinusTinus/game-engine | package nl.mvdr.tinustris.engine;
import java.util.EnumSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import nl.mvdr.tinustris.model.Tetromino;
import org.junit.Assert;
import org.junit.Test;
/**
* Test class for {@link RandomTetrominoGenerator}.
*
* @author Martijn van de Rijdt
*/
public class RandomTetrominoGeneratorTest {
/** Random seed. */
private static final long SEED = 693741264L;
/** The number of threads in the executor service used for concurrency tests. */
int NUM_THREADS = 5;
/** Invokes the get method a few times and checks that it returns non-null values. */
@Test
public void testGet() {
RandomTetrominoGenerator generator = new RandomTetrominoGenerator();
for (int i = 0; i != 10; i++) {
Assert.assertNotNull("failed on i = " + i, generator.get(i));
}
}
/** Tests that the get method returns the same value when invoked with the same index multiple times. */
@Test
public void testGetMultipleCalls() {
RandomTetrominoGenerator generator = new RandomTetrominoGenerator();
Tetromino first = generator.get(0);
Assert.assertEquals(first, generator.get(0));
}
/**
* Tests that the get method returns the same value when invoked with the same index multiple times, even when other
* indices have been used as well.
*/
@Test
public void testGetMultipleCallsLater() {
RandomTetrominoGenerator generator = new RandomTetrominoGenerator();
Tetromino first = generator.get(0);
generator.get(1);
generator.get(2);
Assert.assertEquals(first, generator.get(0));
}
/**
* Tests that the get method works correctly when skipping a tetromino index (even though this should never happen
* in practice).
*/
@Test
public void testGetSkipValue() {
RandomTetrominoGenerator generator = new RandomTetrominoGenerator();
Assert.assertNotNull(generator.get(1));
}
/**
* Tests that the get method works correctly when skipping a tetromino index (even though this should never happen
* in practice).
*/
@Test
public void testGetSkipValueMultipleTimes() {
RandomTetrominoGenerator generator = new RandomTetrominoGenerator();
Tetromino first = generator.get(1);
Assert.assertEquals(first, generator.get(1));
}
/** Test case with a negative index. */
@Test(expected = IndexOutOfBoundsException.class)
public void testNegativeValue() {
RandomTetrominoGenerator generator = new RandomTetrominoGenerator();
generator.get(-1);
}
/** Tests that reusing the same random seed produces the same results. */
@Test
public void testRandomSeed() {
RandomTetrominoGenerator generator = new RandomTetrominoGenerator(0L);
Tetromino first = generator.get(0);
generator = new RandomTetrominoGenerator(0L);
Assert.assertEquals(first, generator.get(0));
}
/** Tests that reusing the same random seed in a new JVM instance still produces the same result. */
@Test
public void testRandomSeedFixed() {
RandomTetrominoGenerator generator = new RandomTetrominoGenerator(0L);
Assert.assertEquals(Tetromino.S, generator.get(0));
Assert.assertEquals(Tetromino.T, generator.get(1));
Assert.assertEquals(Tetromino.L, generator.get(2));
Assert.assertEquals(Tetromino.T, generator.get(3));
Assert.assertEquals(Tetromino.L, generator.get(4));
Assert.assertEquals(Tetromino.I, generator.get(5));
Assert.assertEquals(Tetromino.T, generator.get(6));
Assert.assertEquals(Tetromino.O, generator.get(7));
Assert.assertEquals(Tetromino.Z, generator.get(8));
Assert.assertEquals(Tetromino.T, generator.get(9));
}
/** Tests whether generators with the same random seed also result in the same value. */
@Test
public void testRepeatable() {
RandomTetrominoGenerator generator0 = new RandomTetrominoGenerator(SEED);
RandomTetrominoGenerator generator1 = new RandomTetrominoGenerator(SEED);
Tetromino tetromino0 = generator0.get(100);
Tetromino tetromino1 = generator1.get(100);
Assert.assertEquals(tetromino0, tetromino1);
}
/**
* Test case where {@link RandomTetrominoGenerator#get(int)} is called from several different threads. We expect
* each call to return the same tetromino.
*
* @throws ExecutionException
* unexpected exception
* @throws InterruptedException
* unexpected exception
*/
@Test
public void testGetMultiThreaded() throws ExecutionException, InterruptedException {
// repeat the test a few times, to increase the likelyhood of failure in case of synchronisation bugs
for (int i = 0; i != 100; i++) {
RandomTetrominoGenerator generator = new RandomTetrominoGenerator();
testMultithreaded(generator);
}
}
/**
* Tests whether generators with the same random seed also result in the same value, in a multithreaded environment.
* @throws ExecutionException
* unexpected exception
* @throws InterruptedException
* unexpected exception
*/
@Test
public void testRepeatableMultithreaded() throws InterruptedException, ExecutionException {
// repeat the test a few times, to increase the likelyhood of failure in case of synchronisation bugs
for (int i = 0; i != 100; i++){
RandomTetrominoGenerator generator0 = new RandomTetrominoGenerator(SEED);
RandomTetrominoGenerator generator1 = new RandomTetrominoGenerator(SEED);
Tetromino tetromino0 = testMultithreaded(generator0);
Tetromino tetromino1 = testMultithreaded(generator1);
Assert.assertEquals("Failed at iteration " + 0, tetromino0, tetromino1);
}
}
/**
* Calls {@link RandomTetrominoGenerator#get(int)} with the same value from several different threads. Checks that
* each thread results in the same tetromino value.
*
* @param generator generator
* @throws ExecutionException
* unexpected exception
* @throws InterruptedException
* unexpected exception
* @return tetromino value
*/
private Tetromino testMultithreaded(final RandomTetrominoGenerator generator) throws InterruptedException,
ExecutionException {
ExecutorService service = Executors.newFixedThreadPool(NUM_THREADS);
Callable<Tetromino> getTetrominoTask = () -> generator.get(10);
List<Future<Tetromino>> futures = IntStream.range(0, NUM_THREADS)
.mapToObj(i -> getTetrominoTask)
.map(service::submit)
.collect(Collectors.toList());
// wait for all threads to complete and combine the results into a Set
Set<Tetromino> results = EnumSet.noneOf(Tetromino.class);
for (Future<Tetromino> future: futures) {
Tetromino result = future.get();
results.add(result);
}
// check that each thread resulted in the same value
Assert.assertEquals("more than one unique tetromino returned", 1, results.size());
// return the tetromino
return results.iterator().next();
}
}
| tinustris/src/test/java/nl/mvdr/tinustris/engine/RandomTetrominoGeneratorTest.java | package nl.mvdr.tinustris.engine;
import java.util.EnumSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import nl.mvdr.tinustris.model.Tetromino;
import org.junit.Assert;
import org.junit.Test;
/**
* Test class for {@link RandomTetrominoGenerator}.
*
* @author Martijn van de Rijdt
*/
public class RandomTetrominoGeneratorTest {
/** Random seed. */
private static final long SEED = 693741264L;
/** The number of threads in the executor service used for concurrency tests. */
int NUM_THREADS = 5;
/** Invokes the get method a few times and checks that it returns non-null values. */
@Test
public void testGet() {
RandomTetrominoGenerator generator = new RandomTetrominoGenerator();
for (int i = 0; i != 10; i++) {
Assert.assertNotNull("failed on i = " + i, generator.get(i));
}
}
/** Tests that the get method returns the same value when invoked with the same index multiple times. */
@Test
public void testGetMultipleCalls() {
RandomTetrominoGenerator generator = new RandomTetrominoGenerator();
Tetromino first = generator.get(0);
Assert.assertEquals(first, generator.get(0));
}
/**
* Tests that the get method returns the same value when invoked with the same index multiple times, even when other
* indices have been used as well.
*/
@Test
public void testGetMultipleCallsLater() {
RandomTetrominoGenerator generator = new RandomTetrominoGenerator();
Tetromino first = generator.get(0);
generator.get(1);
generator.get(2);
Assert.assertEquals(first, generator.get(0));
}
/**
* Tests that the get method works correctly when skipping a tetromino index (even though this should never happen
* in practice).
*/
@Test
public void testGetSkipValue() {
RandomTetrominoGenerator generator = new RandomTetrominoGenerator();
Assert.assertNotNull(generator.get(1));
}
/**
* Tests that the get method works correctly when skipping a tetromino index (even though this should never happen
* in practice).
*/
@Test
public void testGetSkipValueMultipleTimes() {
RandomTetrominoGenerator generator = new RandomTetrominoGenerator();
Tetromino first = generator.get(1);
Assert.assertEquals(first, generator.get(1));
}
/** Test case with a negative index. */
@Test(expected = IndexOutOfBoundsException.class)
public void testNegativeValue() {
RandomTetrominoGenerator generator = new RandomTetrominoGenerator();
generator.get(-1);
}
/** Tests that reusing the same random seed produces the same results. */
@Test
public void testRandomSeed() {
RandomTetrominoGenerator generator = new RandomTetrominoGenerator(0L);
Tetromino first = generator.get(0);
generator = new RandomTetrominoGenerator(0L);
Assert.assertEquals(first, generator.get(0));
}
/** Tests that reusing the same random seed in a new JVM instance still produces the same result. */
@Test
public void testRandomSeedFixed() {
RandomTetrominoGenerator generator = new RandomTetrominoGenerator(0L);
Assert.assertEquals(Tetromino.S, generator.get(0));
Assert.assertEquals(Tetromino.T, generator.get(1));
Assert.assertEquals(Tetromino.L, generator.get(2));
Assert.assertEquals(Tetromino.T, generator.get(3));
Assert.assertEquals(Tetromino.L, generator.get(4));
Assert.assertEquals(Tetromino.I, generator.get(5));
Assert.assertEquals(Tetromino.T, generator.get(6));
Assert.assertEquals(Tetromino.O, generator.get(7));
Assert.assertEquals(Tetromino.Z, generator.get(8));
Assert.assertEquals(Tetromino.T, generator.get(9));
}
/** Tests whether generators with the same random seed also result in the same value. */
@Test
public void testRepeatable() {
RandomTetrominoGenerator generator0 = new RandomTetrominoGenerator(SEED);
RandomTetrominoGenerator generator1 = new RandomTetrominoGenerator(SEED);
Tetromino tetromino0 = generator0.get(100);
Tetromino tetromino1 = generator1.get(100);
Assert.assertEquals(tetromino0, tetromino1);
}
/**
* Test case where {@link RandomTetrominoGenerator#get(int)} is called from several different threads. We expect
* each call to return the same tetromino.
*
* @throws ExecutionException
* unexpected exception
* @throws InterruptedException
* unexpected exception
*/
@Test
public void testGetMultiThreaded() throws ExecutionException, InterruptedException {
// repeat the test a few times, to increase the likelyhood of failure in case of synchronisation bugs
for (int i = 0; i != 100; i++) {
RandomTetrominoGenerator generator = new RandomTetrominoGenerator();
testMultithreaded(generator);
}
}
/**
* Tests whether generators with the same random seed also result in the same value, in a multithreaded environment.
* @throws ExecutionException
* unexpected exception
* @throws InterruptedException
* unexpected exception
*/
@Test
public void testRepeatableMultithreaded() throws InterruptedException, ExecutionException {
// repeat the test a few times, to increase the likelyhood of failure in case of synchronisation bugs
for (int i = 0; i != 100; i++){
RandomTetrominoGenerator generator0 = new RandomTetrominoGenerator(SEED);
RandomTetrominoGenerator generator1 = new RandomTetrominoGenerator(SEED);
Tetromino tetromino0 = testMultithreaded(generator0);
Tetromino tetromino1 = testMultithreaded(generator1);
Assert.assertEquals("Failed at iteration " + 0, tetromino0, tetromino1);
}
}
/**
* Calls {@link RandomTetrominoGenerator#get(int)} with the same value from several different threads. Checks that
* each thread results in the same tetromino value.
*
* @param generator generator
* @throws ExecutionException
* unexpected exception
* @throws InterruptedException
* unexpected exception
* @return tetromino value
*/
private Tetromino testMultithreaded(final RandomTetrominoGenerator generator) throws InterruptedException,
ExecutionException {
ExecutorService service = Executors.newFixedThreadPool(NUM_THREADS);
Callable<Tetromino> getTetrominoTask = () -> generator.get(10);
List<Future<Tetromino>> futures = IntStream.range(0, NUM_THREADS)
.mapToObj(i -> getTetrominoTask)
.map(service::submit)
.collect(Collectors.toList());
// wait for all threads to complete and combine the results into a Set
Set<Tetromino> results = EnumSet.noneOf(Tetromino.class);
for (Future<Tetromino> future: futures) {
Tetromino result = future.get();
results.add(result);
}
// check that each thread resulted in the same value
Assert.assertEquals("more than one unique tetromino returned", 1, results.size());
// return the tetromino
return results.iterator().next();
}
}
| Removed unused import. | tinustris/src/test/java/nl/mvdr/tinustris/engine/RandomTetrominoGeneratorTest.java | Removed unused import. | <ide><path>inustris/src/test/java/nl/mvdr/tinustris/engine/RandomTetrominoGeneratorTest.java
<ide> package nl.mvdr.tinustris.engine;
<ide>
<ide> import java.util.EnumSet;
<del>import java.util.LinkedList;
<ide> import java.util.List;
<ide> import java.util.Set;
<ide> import java.util.concurrent.Callable; |
|
Java | apache-2.0 | 65e88449aa0f970d0d52e4e8364ce4b7faa51b94 | 0 | spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework | /*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.portlet;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.EventRequest;
import javax.portlet.EventResponse;
import javax.portlet.MimeResponse;
import javax.portlet.PortletException;
import javax.portlet.PortletRequest;
import javax.portlet.PortletResponse;
import javax.portlet.PortletSession;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.portlet.ResourceRequest;
import javax.portlet.ResourceResponse;
import javax.portlet.UnavailableException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.beans.factory.BeanInitializationException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.core.OrderComparator;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.portlet.multipart.MultipartActionRequest;
import org.springframework.web.portlet.multipart.PortletMultipartResolver;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewRendererServlet;
import org.springframework.web.servlet.ViewResolver;
/**
* Central dispatcher for use within the Portlet MVC framework, e.g. for web UI
* controllers. Dispatches to registered handlers for processing a portlet request.
*
* <p>This portlet is very flexible: It can be used with just about any workflow,
* with the installation of the appropriate adapter classes. It offers the
* following functionality that distinguishes it from other request-driven
* portlet MVC frameworks:
*
* <ul>
* <li>It is based around a JavaBeans configuration mechanism.
*
* <li>It can use any {@link HandlerMapping} implementation - pre-built or provided
* as part of an application - to control the routing of requests to handler objects.
* Default is a {@link org.springframework.web.portlet.mvc.annotation.DefaultAnnotationHandlerMapping}.
* HandlerMapping objects can be defined as beans in the portlet's application context,
* implementing the HandlerMapping interface, overriding the default HandlerMapping if present.
* HandlerMappings can be given any bean name (they are tested by type).
*
* <li>It can use any {@link HandlerAdapter}; this allows for using any handler interface.
* The default adapter is {@link org.springframework.web.portlet.mvc.SimpleControllerHandlerAdapter}
* for Spring's {@link org.springframework.web.portlet.mvc.Controller} interface.
* A default {@link org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter}
* will be registered as well. HandlerAdapter objects can be added as beans in the
* application context, overriding the default HandlerAdapter. Like HandlerMappings,
* HandlerAdapters can be given any bean name (they are tested by type).
*
* <li>The dispatcher's exception resolution strategy can be specified via a
* {@link HandlerExceptionResolver}, for example mapping certain exceptions to
* error pages. Default is none. Additional HandlerExceptionResolvers can be added
* through the application context. HandlerExceptionResolver can be given any
* bean name (they are tested by type).
*
* <li>Its view resolution strategy can be specified via a {@link ViewResolver}
* implementation, resolving symbolic view names into View objects. Default is
* {@link org.springframework.web.servlet.view.InternalResourceViewResolver}.
* ViewResolver objects can be added as beans in the application context,
* overriding the default ViewResolver. ViewResolvers can be given any bean name
* (they are tested by type).
*
* <li>The dispatcher's strategy for resolving multipart requests is determined by a
* {@link org.springframework.web.portlet.multipart.PortletMultipartResolver} implementation.
* An implementations for Jakarta Commons FileUpload is included:
* {@link org.springframework.web.portlet.multipart.CommonsPortletMultipartResolver}.
* The MultipartResolver bean name is "portletMultipartResolver"; default is none.
* </ul>
*
* <p><b>NOTE: The <code>@RequestMapping</code> annotation will only be processed
* if a corresponding <code>HandlerMapping</code> (for type level annotations)
* and/or <code>HandlerAdapter</code> (for method level annotations)
* is present in the dispatcher.</b> This is the case by default.
* However, if you are defining custom <code>HandlerMappings</code> or
* <code>HandlerAdapters</code>, then you need to make sure that a
* corresponding custom <code>DefaultAnnotationHandlerMapping</code>
* and/or <code>AnnotationMethodHandlerAdapter</code> is defined as well
* - provided that you intend to use <code>@RequestMapping</code>.
*
* <p><b>A web application can define any number of DispatcherPortlets.</b>
* Each portlet will operate in its own namespace, loading its own application
* context with mappings, handlers, etc. Only the root application context
* as loaded by {@link org.springframework.web.context.ContextLoaderListener},
* if any, will be shared.
*
* <p>Thanks to Rainer Schmitz and Nick Lothian for their suggestions!
*
* @author William G. Thompson, Jr.
* @author John A. Lewis
* @author Juergen Hoeller
* @since 2.0
* @see org.springframework.web.portlet.mvc.Controller
* @see org.springframework.web.servlet.ViewRendererServlet
* @see org.springframework.web.context.ContextLoaderListener
*/
public class DispatcherPortlet extends FrameworkPortlet {
/**
* Well-known name for the PortletMultipartResolver object in the bean factory for this namespace.
*/
public static final String MULTIPART_RESOLVER_BEAN_NAME = "portletMultipartResolver";
/**
* Well-known name for the HandlerMapping object in the bean factory for this namespace.
* Only used when "detectAllHandlerMappings" is turned off.
* @see #setDetectAllViewResolvers
*/
public static final String HANDLER_MAPPING_BEAN_NAME = "handlerMapping";
/**
* Well-known name for the HandlerAdapter object in the bean factory for this namespace.
* Only used when "detectAllHandlerAdapters" is turned off.
* @see #setDetectAllHandlerAdapters
*/
public static final String HANDLER_ADAPTER_BEAN_NAME = "handlerAdapter";
/**
* Well-known name for the HandlerExceptionResolver object in the bean factory for this
* namespace. Only used when "detectAllHandlerExceptionResolvers" is turned off.
* @see #setDetectAllViewResolvers
*/
public static final String HANDLER_EXCEPTION_RESOLVER_BEAN_NAME = "handlerExceptionResolver";
/**
* Well-known name for the ViewResolver object in the bean factory for this namespace.
*/
public static final String VIEW_RESOLVER_BEAN_NAME = "viewResolver";
/**
* Default URL to ViewRendererServlet. This bridge servlet is used to convert
* portlet render requests to servlet requests in order to leverage the view support
* in the <code>org.springframework.web.view</code> package.
*/
public static final String DEFAULT_VIEW_RENDERER_URL = "/WEB-INF/servlet/view";
/**
* Request attribute to hold the currently chosen HandlerExecutionChain.
* Only used for internal optimizations.
*/
public static final String HANDLER_EXECUTION_CHAIN_ATTRIBUTE =
DispatcherPortlet.class.getName() + ".HANDLER";
/**
* Unlike the Servlet version of this class, we have to deal with the
* two-phase nature of the portlet request. To do this, we need to pass
* forward any exception that occurs during the action phase, so that
* it can be displayed in the render phase. The only direct way to pass
* things forward and preserve them for each render request is through
* render parameters, but these are limited to String objects and we need
* to pass the Exception itself. The only other way to do this is in the
* session. The bad thing about using the session is that we have no way
* of knowing when we are done re-rendering the request and so we don't
* know when we can remove the objects from the session. So we will end
* up polluting the session with an old exception when we finally leave
* the render phase of one request and move on to something else.
*/
public static final String ACTION_EXCEPTION_SESSION_ATTRIBUTE =
DispatcherPortlet.class.getName() + ".ACTION_EXCEPTION";
/**
* This render parameter is used to indicate forward to the render phase
* that an exception occurred during the action phase.
*/
public static final String ACTION_EXCEPTION_RENDER_PARAMETER = "actionException";
/**
* Log category to use when no mapped handler is found for a request.
*/
public static final String PAGE_NOT_FOUND_LOG_CATEGORY = "org.springframework.web.portlet.PageNotFound";
/**
* Name of the class path resource (relative to the DispatcherPortlet class)
* that defines DispatcherPortet's default strategy names.
*/
private static final String DEFAULT_STRATEGIES_PATH = "DispatcherPortlet.properties";
/**
* Additional logger to use when no mapped handler is found for a request.
*/
protected static final Log pageNotFoundLogger = LogFactory.getLog(PAGE_NOT_FOUND_LOG_CATEGORY);
private static final Properties defaultStrategies;
static {
// Load default strategy implementations from properties file.
// This is currently strictly internal and not meant to be customized
// by application developers.
try {
ClassPathResource resource = new ClassPathResource(DEFAULT_STRATEGIES_PATH, DispatcherPortlet.class);
defaultStrategies = PropertiesLoaderUtils.loadProperties(resource);
}
catch (IOException ex) {
throw new IllegalStateException("Could not load 'DispatcherPortlet.properties': " + ex.getMessage());
}
}
/** Detect all HandlerMappings or just expect "handlerMapping" bean? */
private boolean detectAllHandlerMappings = true;
/** Detect all HandlerAdapters or just expect "handlerAdapter" bean? */
private boolean detectAllHandlerAdapters = true;
/** Detect all HandlerExceptionResolvers or just expect "handlerExceptionResolver" bean? */
private boolean detectAllHandlerExceptionResolvers = true;
/** Detect all ViewResolvers or just expect "viewResolver" bean? */
private boolean detectAllViewResolvers = true;
/** URL that points to the ViewRendererServlet */
private String viewRendererUrl = DEFAULT_VIEW_RENDERER_URL;
/** MultipartResolver used by this portlet */
private PortletMultipartResolver multipartResolver;
/** List of HandlerMappings used by this portlet */
private List<HandlerMapping> handlerMappings;
/** List of HandlerAdapters used by this portlet */
private List<HandlerAdapter> handlerAdapters;
/** List of HandlerExceptionResolvers used by this portlet */
private List<HandlerExceptionResolver> handlerExceptionResolvers;
/** List of ViewResolvers used by this portlet */
private List<ViewResolver> viewResolvers;
/**
* Set whether to detect all HandlerMapping beans in this portlet's context.
* Else, just a single bean with name "handlerMapping" will be expected.
* <p>Default is true. Turn this off if you want this portlet to use a
* single HandlerMapping, despite multiple HandlerMapping beans being
* defined in the context.
*/
public void setDetectAllHandlerMappings(boolean detectAllHandlerMappings) {
this.detectAllHandlerMappings = detectAllHandlerMappings;
}
/**
* Set whether to detect all HandlerAdapter beans in this portlet's context.
* Else, just a single bean with name "handlerAdapter" will be expected.
* <p>Default is "true". Turn this off if you want this portlet to use a
* single HandlerAdapter, despite multiple HandlerAdapter beans being
* defined in the context.
*/
public void setDetectAllHandlerAdapters(boolean detectAllHandlerAdapters) {
this.detectAllHandlerAdapters = detectAllHandlerAdapters;
}
/**
* Set whether to detect all HandlerExceptionResolver beans in this portlet's context.
* Else, just a single bean with name "handlerExceptionResolver" will be expected.
* <p>Default is true. Turn this off if you want this portlet to use a
* single HandlerExceptionResolver, despite multiple HandlerExceptionResolver
* beans being defined in the context.
*/
public void setDetectAllHandlerExceptionResolvers(boolean detectAllHandlerExceptionResolvers) {
this.detectAllHandlerExceptionResolvers = detectAllHandlerExceptionResolvers;
}
/**
* Set whether to detect all ViewResolver beans in this portlet's context.
* Else, just a single bean with name "viewResolver" will be expected.
* <p>Default is true. Turn this off if you want this portlet to use a
* single ViewResolver, despite multiple ViewResolver beans being
* defined in the context.
*/
public void setDetectAllViewResolvers(boolean detectAllViewResolvers) {
this.detectAllViewResolvers = detectAllViewResolvers;
}
/**
* Set the URL to the ViewRendererServlet. That servlet is used to
* ultimately render all views in the portlet application.
*/
public void setViewRendererUrl(String viewRendererUrl) {
this.viewRendererUrl = viewRendererUrl;
}
/**
* This implementation calls {@link #initStrategies}.
*/
@Override
public void onRefresh(ApplicationContext context) {
initStrategies(context);
}
/**
* Refresh the strategy objects that this portlet uses.
* <p>May be overridden in subclasses in order to initialize
* further strategy objects.
*/
protected void initStrategies(ApplicationContext context) {
initMultipartResolver(context);
initHandlerMappings(context);
initHandlerAdapters(context);
initHandlerExceptionResolvers(context);
initViewResolvers(context);
}
/**
* Initialize the PortletMultipartResolver used by this class.
* <p>If no valid bean is defined with the given name in the BeanFactory
* for this namespace, no multipart handling is provided.
*/
private void initMultipartResolver(ApplicationContext context) {
try {
this.multipartResolver = context.getBean(MULTIPART_RESOLVER_BEAN_NAME, PortletMultipartResolver.class);
if (logger.isDebugEnabled()) {
logger.debug("Using MultipartResolver [" + this.multipartResolver + "]");
}
}
catch (NoSuchBeanDefinitionException ex) {
// Default is no multipart resolver.
this.multipartResolver = null;
if (logger.isDebugEnabled()) {
logger.debug("Unable to locate PortletMultipartResolver with name '" + MULTIPART_RESOLVER_BEAN_NAME +
"': no multipart request handling provided");
}
}
}
/**
* Initialize the HandlerMappings used by this class.
* <p>If no HandlerMapping beans are defined in the BeanFactory
* for this namespace, we default to PortletModeHandlerMapping.
*/
private void initHandlerMappings(ApplicationContext context) {
this.handlerMappings = null;
if (this.detectAllHandlerMappings) {
// Find all HandlerMappings in the ApplicationContext, including ancestor contexts.
Map<String, HandlerMapping> matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(
context, HandlerMapping.class, true, false);
if (!matchingBeans.isEmpty()) {
this.handlerMappings = new ArrayList<HandlerMapping>(matchingBeans.values());
// We keep HandlerMappings in sorted order.
OrderComparator.sort(this.handlerMappings);
}
}
else {
try {
HandlerMapping hm = context.getBean(HANDLER_MAPPING_BEAN_NAME, HandlerMapping.class);
this.handlerMappings = Collections.singletonList(hm);
}
catch (NoSuchBeanDefinitionException ex) {
// Ignore, we'll add a default HandlerMapping later.
}
}
// Ensure we have at least one HandlerMapping, by registering
// a default HandlerMapping if no other mappings are found.
if (this.handlerMappings == null) {
this.handlerMappings = getDefaultStrategies(context, HandlerMapping.class);
if (logger.isDebugEnabled()) {
logger.debug("No HandlerMappings found in portlet '" + getPortletName() + "': using default");
}
}
}
/**
* Initialize the HandlerAdapters used by this class.
* <p>If no HandlerAdapter beans are defined in the BeanFactory
* for this namespace, we default to SimpleControllerHandlerAdapter.
*/
private void initHandlerAdapters(ApplicationContext context) {
this.handlerAdapters = null;
if (this.detectAllHandlerAdapters) {
// Find all HandlerAdapters in the ApplicationContext, including ancestor contexts.
Map<String, HandlerAdapter> matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(
context, HandlerAdapter.class, true, false);
if (!matchingBeans.isEmpty()) {
this.handlerAdapters = new ArrayList<HandlerAdapter>(matchingBeans.values());
// We keep HandlerAdapters in sorted order.
OrderComparator.sort(this.handlerAdapters);
}
}
else {
try {
HandlerAdapter ha = context.getBean(HANDLER_ADAPTER_BEAN_NAME, HandlerAdapter.class);
this.handlerAdapters = Collections.singletonList(ha);
}
catch (NoSuchBeanDefinitionException ex) {
// Ignore, we'll add a default HandlerAdapter later.
}
}
// Ensure we have at least some HandlerAdapters, by registering
// default HandlerAdapters if no other adapters are found.
if (this.handlerAdapters == null) {
this.handlerAdapters = getDefaultStrategies(context, HandlerAdapter.class);
if (logger.isDebugEnabled()) {
logger.debug("No HandlerAdapters found in portlet '" + getPortletName() + "': using default");
}
}
}
/**
* Initialize the HandlerExceptionResolver used by this class.
* <p>If no bean is defined with the given name in the BeanFactory
* for this namespace, we default to no exception resolver.
*/
private void initHandlerExceptionResolvers(ApplicationContext context) {
this.handlerExceptionResolvers = null;
if (this.detectAllHandlerExceptionResolvers) {
// Find all HandlerExceptionResolvers in the ApplicationContext, including ancestor contexts.
Map<String, HandlerExceptionResolver> matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(
context, HandlerExceptionResolver.class, true, false);
if (!matchingBeans.isEmpty()) {
this.handlerExceptionResolvers = new ArrayList<HandlerExceptionResolver>(matchingBeans.values());
// We keep HandlerExceptionResolvers in sorted order.
OrderComparator.sort(this.handlerExceptionResolvers);
}
}
else {
try {
HandlerExceptionResolver her = context.getBean(
HANDLER_EXCEPTION_RESOLVER_BEAN_NAME, HandlerExceptionResolver.class);
this.handlerExceptionResolvers = Collections.singletonList(her);
}
catch (NoSuchBeanDefinitionException ex) {
// Ignore, no HandlerExceptionResolver is fine too.
}
}
// Just for consistency, check for default HandlerExceptionResolvers...
// There aren't any in usual scenarios.
if (this.handlerExceptionResolvers == null) {
this.handlerExceptionResolvers = getDefaultStrategies(context, HandlerExceptionResolver.class);
if (logger.isDebugEnabled()) {
logger.debug("No HandlerExceptionResolvers found in portlet '" + getPortletName() + "': using default");
}
}
}
/**
* Initialize the ViewResolvers used by this class.
* <p>If no ViewResolver beans are defined in the BeanFactory
* for this namespace, we default to InternalResourceViewResolver.
*/
private void initViewResolvers(ApplicationContext context) {
this.viewResolvers = null;
if (this.detectAllViewResolvers) {
// Find all ViewResolvers in the ApplicationContext, including ancestor contexts.
Map<String, ViewResolver> matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(
context, ViewResolver.class, true, false);
if (!matchingBeans.isEmpty()) {
this.viewResolvers = new ArrayList<ViewResolver>(matchingBeans.values());
// We keep ViewResolvers in sorted order.
OrderComparator.sort(this.viewResolvers);
}
}
else {
try {
ViewResolver vr = context.getBean(VIEW_RESOLVER_BEAN_NAME, ViewResolver.class);
this.viewResolvers = Collections.singletonList(vr);
}
catch (NoSuchBeanDefinitionException ex) {
// Ignore, we'll add a default ViewResolver later.
}
}
// Ensure we have at least one ViewResolver, by registering
// a default ViewResolver if no other resolvers are found.
if (this.viewResolvers == null) {
this.viewResolvers = getDefaultStrategies(context, ViewResolver.class);
if (logger.isDebugEnabled()) {
logger.debug("No ViewResolvers found in portlet '" + getPortletName() + "': using default");
}
}
}
/**
* Return the default strategy object for the given strategy interface.
* <p>The default implementation delegates to {@link #getDefaultStrategies},
* expecting a single object in the list.
* @param context the current Portlet ApplicationContext
* @param strategyInterface the strategy interface
* @return the corresponding strategy object
* @see #getDefaultStrategies
*/
protected <T> T getDefaultStrategy(ApplicationContext context, Class<T> strategyInterface) {
List<T> strategies = getDefaultStrategies(context, strategyInterface);
if (strategies.size() != 1) {
throw new BeanInitializationException(
"DispatcherPortlet needs exactly 1 strategy for interface [" + strategyInterface.getName() + "]");
}
return strategies.get(0);
}
/**
* Create a List of default strategy objects for the given strategy interface.
* <p>The default implementation uses the "DispatcherPortlet.properties" file
* (in the same package as the DispatcherPortlet class) to determine the class names.
* It instantiates the strategy objects and satisifies ApplicationContextAware
* if necessary.
* @param context the current Portlet ApplicationContext
* @param strategyInterface the strategy interface
* @return the List of corresponding strategy objects
*/
@SuppressWarnings("unchecked")
protected <T> List<T> getDefaultStrategies(ApplicationContext context, Class<T> strategyInterface) {
String key = strategyInterface.getName();
String value = defaultStrategies.getProperty(key);
if (value != null) {
String[] classNames = StringUtils.commaDelimitedListToStringArray(value);
List<T> strategies = new ArrayList<T>(classNames.length);
for (String className : classNames) {
try {
Class clazz = ClassUtils.forName(className, DispatcherPortlet.class.getClassLoader());
Object strategy = createDefaultStrategy(context, clazz);
strategies.add((T) strategy);
}
catch (ClassNotFoundException ex) {
throw new BeanInitializationException(
"Could not find DispatcherPortlet's default strategy class [" + className +
"] for interface [" + key + "]", ex);
}
catch (LinkageError err) {
throw new BeanInitializationException(
"Error loading DispatcherPortlet's default strategy class [" + className +
"] for interface [" + key + "]: problem with class file or dependent class", err);
}
}
return strategies;
}
else {
return new LinkedList<T>();
}
}
/**
* Create a default strategy.
* <p>The default implementation uses
* {@link org.springframework.beans.factory.config.AutowireCapableBeanFactory#createBean}.
* @param context the current Portlet ApplicationContext
* @param clazz the strategy implementation class to instantiate
* @return the fully configured strategy instance
* @see org.springframework.context.ApplicationContext#getAutowireCapableBeanFactory()
*/
protected Object createDefaultStrategy(ApplicationContext context, Class<?> clazz) {
return context.getAutowireCapableBeanFactory().createBean(clazz);
}
/**
* Obtain this portlet's PortletMultipartResolver, if any.
* @return the PortletMultipartResolver used by this portlet, or <code>null</code>
* if none (indicating that no multipart support is available)
*/
public PortletMultipartResolver getMultipartResolver() {
return this.multipartResolver;
}
/**
* Processes the actual dispatching to the handler for action requests.
* <p>The handler will be obtained by applying the portlet's HandlerMappings in order.
* The HandlerAdapter will be obtained by querying the portlet's installed
* HandlerAdapters to find the first that supports the handler class.
* @param request current portlet action request
* @param response current portlet Action response
* @throws Exception in case of any kind of processing failure
*/
@Override
protected void doActionService(ActionRequest request, ActionResponse response) throws Exception {
if (logger.isDebugEnabled()) {
logger.debug("DispatcherPortlet with name '" + getPortletName() + "' received action request");
}
ActionRequest processedRequest = request;
HandlerExecutionChain mappedHandler = null;
int interceptorIndex = -1;
try {
processedRequest = checkMultipart(request);
// Determine handler for the current request.
mappedHandler = getHandler(processedRequest, false);
if (mappedHandler == null || mappedHandler.getHandler() == null) {
noHandlerFound(processedRequest, response);
return;
}
// Apply preHandle methods of registered interceptors.
HandlerInterceptor[] interceptors = mappedHandler.getInterceptors();
if (interceptors != null) {
for (int i = 0; i < interceptors.length; i++) {
HandlerInterceptor interceptor = interceptors[i];
if (!interceptor.preHandleAction(processedRequest, response, mappedHandler.getHandler())) {
triggerAfterActionCompletion(mappedHandler, interceptorIndex, processedRequest, response, null);
return;
}
interceptorIndex = i;
}
}
// Actually invoke the handler.
HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());
ha.handleAction(processedRequest, response, mappedHandler.getHandler());
// Trigger after-completion for successful outcome.
triggerAfterActionCompletion(mappedHandler, interceptorIndex, processedRequest, response, null);
}
catch (Exception ex) {
// Trigger after-completion for thrown exception.
triggerAfterActionCompletion(mappedHandler, interceptorIndex, processedRequest, response, ex);
// Forward the exception to the render phase to be displayed.
try {
response.setRenderParameter(ACTION_EXCEPTION_RENDER_PARAMETER, ex.toString());
request.getPortletSession().setAttribute(ACTION_EXCEPTION_SESSION_ATTRIBUTE, ex);
logger.debug("Caught exception during action phase - forwarding to render phase", ex);
}
catch (IllegalStateException ex2) {
// Probably sendRedirect called... need to rethrow exception immediately.
throw ex;
}
}
catch (Error err) {
PortletException ex =
new PortletException("Error occured during request processing: " + err.getMessage(), err);
// Trigger after-completion for thrown exception.
triggerAfterActionCompletion(mappedHandler, interceptorIndex, processedRequest, response, ex);
throw ex;
}
finally {
// Clean up any resources used by a multipart request.
if (processedRequest instanceof MultipartActionRequest && processedRequest != request) {
this.multipartResolver.cleanupMultipart((MultipartActionRequest) processedRequest);
}
}
}
/**
* Processes the actual dispatching to the handler for render requests.
* <p>The handler will be obtained by applying the portlet's HandlerMappings in order.
* The HandlerAdapter will be obtained by querying the portlet's installed
* HandlerAdapters to find the first that supports the handler class.
* @param request current portlet render request
* @param response current portlet render response
* @throws Exception in case of any kind of processing failure
*/
@Override
protected void doRenderService(RenderRequest request, RenderResponse response) throws Exception {
if (logger.isDebugEnabled()) {
logger.debug("DispatcherPortlet with name '" + getPortletName() + "' received render request");
}
HandlerExecutionChain mappedHandler = null;
int interceptorIndex = -1;
try {
ModelAndView mv;
try {
// Determine handler for the current request.
mappedHandler = getHandler(request, false);
if (mappedHandler == null || mappedHandler.getHandler() == null) {
noHandlerFound(request, response);
return;
}
// Apply preHandle methods of registered interceptors.
HandlerInterceptor[] interceptors = mappedHandler.getInterceptors();
if (interceptors != null) {
for (int i = 0; i < interceptors.length; i++) {
HandlerInterceptor interceptor = interceptors[i];
if (!interceptor.preHandleRender(request, response, mappedHandler.getHandler())) {
triggerAfterRenderCompletion(mappedHandler, interceptorIndex, request, response, null);
return;
}
interceptorIndex = i;
}
}
// Check for forwarded exception from the action phase
PortletSession session = request.getPortletSession(false);
if (session != null) {
if (request.getParameter(ACTION_EXCEPTION_RENDER_PARAMETER) != null) {
Exception ex = (Exception) session.getAttribute(ACTION_EXCEPTION_SESSION_ATTRIBUTE);
if (ex != null) {
logger.debug("Render phase found exception caught during action phase - rethrowing it");
throw ex;
}
}
else {
session.removeAttribute(ACTION_EXCEPTION_SESSION_ATTRIBUTE);
}
}
// Actually invoke the handler.
HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());
mv = ha.handleRender(request, response, mappedHandler.getHandler());
// Apply postHandle methods of registered interceptors.
if (interceptors != null) {
for (int i = interceptors.length - 1; i >= 0; i--) {
HandlerInterceptor interceptor = interceptors[i];
interceptor.postHandleRender(request, response, mappedHandler.getHandler(), mv);
}
}
}
catch (ModelAndViewDefiningException ex) {
logger.debug("ModelAndViewDefiningException encountered", ex);
mv = ex.getModelAndView();
}
catch (Exception ex) {
Object handler = (mappedHandler != null ? mappedHandler.getHandler() : null);
mv = processHandlerException(request, response, handler, ex);
}
// Did the handler return a view to render?
if (mv != null && !mv.isEmpty()) {
render(mv, request, response);
}
else {
if (logger.isDebugEnabled()) {
logger.debug("Null ModelAndView returned to DispatcherPortlet with name '" +
getPortletName() + "': assuming HandlerAdapter completed request handling");
}
}
// Trigger after-completion for successful outcome.
triggerAfterRenderCompletion(mappedHandler, interceptorIndex, request, response, null);
}
catch (Exception ex) {
// Trigger after-completion for thrown exception.
triggerAfterRenderCompletion(mappedHandler, interceptorIndex, request, response, ex);
throw ex;
}
catch (Error err) {
PortletException ex =
new PortletException("Error occured during request processing: " + err.getMessage(), err);
// Trigger after-completion for thrown exception.
triggerAfterRenderCompletion(mappedHandler, interceptorIndex, request, response, ex);
throw ex;
}
}
/**
* Processes the actual dispatching to the handler for resource requests.
* <p>The handler will be obtained by applying the portlet's HandlerMappings in order.
* The HandlerAdapter will be obtained by querying the portlet's installed
* HandlerAdapters to find the first that supports the handler class.
* @param request current portlet render request
* @param response current portlet render response
* @throws Exception in case of any kind of processing failure
*/
@Override
protected void doResourceService(ResourceRequest request, ResourceResponse response) throws Exception {
if (logger.isDebugEnabled()) {
logger.debug("DispatcherPortlet with name '" + getPortletName() + "' received resource request");
}
HandlerExecutionChain mappedHandler = null;
int interceptorIndex = -1;
try {
ModelAndView mv;
try {
// Determine handler for the current request.
mappedHandler = getHandler(request, false);
if (mappedHandler == null || mappedHandler.getHandler() == null) {
noHandlerFound(request, response);
return;
}
// Apply preHandle methods of registered interceptors.
HandlerInterceptor[] interceptors = mappedHandler.getInterceptors();
if (interceptors != null) {
for (int i = 0; i < interceptors.length; i++) {
HandlerInterceptor interceptor = interceptors[i];
if (!interceptor.preHandleResource(request, response, mappedHandler.getHandler())) {
triggerAfterResourceCompletion(mappedHandler, interceptorIndex, request, response, null);
return;
}
interceptorIndex = i;
}
}
// Actually invoke the handler.
HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());
mv = ha.handleResource(request, response, mappedHandler.getHandler());
// Apply postHandle methods of registered interceptors.
if (interceptors != null) {
for (int i = interceptors.length - 1; i >= 0; i--) {
HandlerInterceptor interceptor = interceptors[i];
interceptor.postHandleResource(request, response, mappedHandler.getHandler(), mv);
}
}
}
catch (ModelAndViewDefiningException ex) {
logger.debug("ModelAndViewDefiningException encountered", ex);
mv = ex.getModelAndView();
}
catch (Exception ex) {
Object handler = (mappedHandler != null ? mappedHandler.getHandler() : null);
mv = processHandlerException(request, response, handler, ex);
}
// Did the handler return a view to render?
if (mv != null && !mv.isEmpty()) {
render(mv, request, response);
}
else {
if (logger.isDebugEnabled()) {
logger.debug("Null ModelAndView returned to DispatcherPortlet with name '" +
getPortletName() + "': assuming HandlerAdapter completed request handling");
}
}
// Trigger after-completion for successful outcome.
triggerAfterResourceCompletion(mappedHandler, interceptorIndex, request, response, null);
}
catch (Exception ex) {
// Trigger after-completion for thrown exception.
triggerAfterResourceCompletion(mappedHandler, interceptorIndex, request, response, ex);
throw ex;
}
catch (Error err) {
PortletException ex =
new PortletException("Error occured during request processing: " + err.getMessage(), err);
// Trigger after-completion for thrown exception.
triggerAfterResourceCompletion(mappedHandler, interceptorIndex, request, response, ex);
throw ex;
}
}
/**
* Processes the actual dispatching to the handler for event requests.
* <p>The handler will be obtained by applying the portlet's HandlerMappings in order.
* The HandlerAdapter will be obtained by querying the portlet's installed
* HandlerAdapters to find the first that supports the handler class.
* @param request current portlet action request
* @param response current portlet Action response
* @throws Exception in case of any kind of processing failure
*/
@Override
protected void doEventService(EventRequest request, EventResponse response) throws Exception {
if (logger.isDebugEnabled()) {
logger.debug("DispatcherPortlet with name '" + getPortletName() + "' received action request");
}
HandlerExecutionChain mappedHandler = null;
int interceptorIndex = -1;
try {
// Determine handler for the current request.
mappedHandler = getHandler(request, false);
if (mappedHandler == null || mappedHandler.getHandler() == null) {
noHandlerFound(request, response);
return;
}
// Apply preHandle methods of registered interceptors.
HandlerInterceptor[] interceptors = mappedHandler.getInterceptors();
if (interceptors != null) {
for (int i = 0; i < interceptors.length; i++) {
HandlerInterceptor interceptor = interceptors[i];
if (!interceptor.preHandleEvent(request, response, mappedHandler.getHandler())) {
triggerAfterEventCompletion(mappedHandler, interceptorIndex, request, response, null);
return;
}
interceptorIndex = i;
}
}
// Actually invoke the handler.
HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());
ha.handleEvent(request, response, mappedHandler.getHandler());
// Trigger after-completion for successful outcome.
triggerAfterEventCompletion(mappedHandler, interceptorIndex, request, response, null);
}
catch (Exception ex) {
// Trigger after-completion for thrown exception.
triggerAfterEventCompletion(mappedHandler, interceptorIndex, request, response, ex);
// Forward the exception to the render phase to be displayed.
try {
response.setRenderParameter(ACTION_EXCEPTION_RENDER_PARAMETER, ex.toString());
request.getPortletSession().setAttribute(ACTION_EXCEPTION_SESSION_ATTRIBUTE, ex);
logger.debug("Caught exception during event phase - forwarding to render phase", ex);
}
catch (IllegalStateException ex2) {
// Probably sendRedirect called... need to rethrow exception immediately.
throw ex;
}
}
catch (Error err) {
PortletException ex =
new PortletException("Error occured during request processing: " + err.getMessage(), err);
// Trigger after-completion for thrown exception.
triggerAfterEventCompletion(mappedHandler, interceptorIndex, request, response, ex);
throw ex;
}
}
/**
* Convert the request into a multipart request, and make multipart resolver available.
* If no multipart resolver is set, simply use the existing request.
* @param request current HTTP request
* @return the processed request (multipart wrapper if necessary)
*/
protected ActionRequest checkMultipart(ActionRequest request) throws MultipartException {
if (this.multipartResolver != null && this.multipartResolver.isMultipart(request)) {
if (request instanceof MultipartActionRequest) {
logger.debug("Request is already a MultipartActionRequest - probably in a forward");
}
else {
return this.multipartResolver.resolveMultipart(request);
}
}
// If not returned before: return original request.
return request;
}
/**
* Return the HandlerExecutionChain for this request.
* Try all handler mappings in order.
* @param request current portlet request
* @param cache whether to cache the HandlerExecutionChain in a request attribute
* @return the HandlerExceutionChain, or null if no handler could be found
*/
protected HandlerExecutionChain getHandler(PortletRequest request, boolean cache) throws Exception {
HandlerExecutionChain handler =
(HandlerExecutionChain) request.getAttribute(HANDLER_EXECUTION_CHAIN_ATTRIBUTE);
if (handler != null) {
if (!cache) {
request.removeAttribute(HANDLER_EXECUTION_CHAIN_ATTRIBUTE);
}
return handler;
}
for (HandlerMapping hm : this.handlerMappings) {
if (logger.isDebugEnabled()) {
logger.debug(
"Testing handler map [" + hm + "] in DispatcherPortlet with name '" + getPortletName() + "'");
}
handler = hm.getHandler(request);
if (handler != null) {
if (cache) {
request.setAttribute(HANDLER_EXECUTION_CHAIN_ATTRIBUTE, handler);
}
return handler;
}
}
return null;
}
/**
* No handler found -> throw appropriate exception.
* @param request current portlet request
* @param response current portlet response
* @throws Exception if preparing the response failed
*/
protected void noHandlerFound(PortletRequest request, PortletResponse response) throws Exception {
if (pageNotFoundLogger.isWarnEnabled()) {
pageNotFoundLogger.warn("No mapping found for current request " +
"in DispatcherPortlet with name '" + getPortletName() +
"', mode '" + request.getPortletMode() +
"', phase '" + request.getAttribute(PortletRequest.LIFECYCLE_PHASE) +
"', session '" + request.getRequestedSessionId() +
"', user '" + getUsernameForRequest(request) + "'");
}
throw new UnavailableException("No handler found for request");
}
/**
* Return the HandlerAdapter for this handler object.
* @param handler the handler object to find an adapter for
* @throws PortletException if no HandlerAdapter can be found for the handler.
* This is a fatal error.
*/
protected HandlerAdapter getHandlerAdapter(Object handler) throws PortletException {
for (HandlerAdapter ha : this.handlerAdapters) {
if (logger.isDebugEnabled()) {
logger.debug("Testing handler adapter [" + ha + "]");
}
if (ha.supports(handler)) {
return ha;
}
}
throw new PortletException("No adapter for handler [" + handler +
"]: Does your handler implement a supported interface like Controller?");
}
/**
* Render the given ModelAndView. This is the last stage in handling a request.
* It may involve resolving the view by name.
* @param mv the ModelAndView to render
* @param request current portlet render request
* @param response current portlet render response
* @throws Exception if there's a problem rendering the view
*/
protected void render(ModelAndView mv, PortletRequest request, MimeResponse response) throws Exception {
View view;
if (mv.isReference()) {
// We need to resolve the view name.
view = resolveViewName(mv.getViewName(), mv.getModelInternal(), request);
if (view == null) {
throw new PortletException("Could not resolve view with name '" + mv.getViewName() +
"' in portlet with name '" + getPortletName() + "'");
}
}
else {
// No need to lookup: the ModelAndView object contains the actual View object.
Object viewObject = mv.getView();
if (viewObject == null) {
throw new PortletException("ModelAndView [" + mv + "] neither contains a view name nor a " +
"View object in portlet with name '" + getPortletName() + "'");
}
if (!(viewObject instanceof View)) {
throw new PortletException(
"View object [" + viewObject + "] is not an instance of [org.springframework.web.servlet.View] - " +
"DispatcherPortlet does not support any other view types");
}
view = (View) viewObject;
}
// Set the content type on the response if needed and if possible.
// The Portlet spec requires the content type to be set on the RenderResponse;
// it's not sufficient to let the View set it on the ServletResponse.
if (response.getContentType() != null) {
if (logger.isDebugEnabled()) {
logger.debug("Portlet response content type already set to [" + response.getContentType() + "]");
}
}
else {
// No Portlet content type specified yet -> use the view-determined type.
String contentType = view.getContentType();
if (contentType != null) {
if (logger.isDebugEnabled()) {
logger.debug("Setting portlet response content type to view-determined type [" + contentType + "]");
}
response.setContentType(contentType);
}
}
doRender(view, mv.getModelInternal(), request, response);
}
/**
* Resolve the given view name into a View object (to be rendered).
* <p>Default implementations asks all ViewResolvers of this dispatcher.
* Can be overridden for custom resolution strategies, potentially based
* on specific model attributes or request parameters.
* @param viewName the name of the view to resolve
* @param model the model to be passed to the view
* @param request current portlet render request
* @return the View object, or null if none found
* @throws Exception if the view cannot be resolved
* (typically in case of problems creating an actual View object)
* @see ViewResolver#resolveViewName
*/
protected View resolveViewName(String viewName, Map model, PortletRequest request) throws Exception {
for (ViewResolver viewResolver : this.viewResolvers) {
View view = viewResolver.resolveViewName(viewName, request.getLocale());
if (view != null) {
return view;
}
}
return null;
}
/**
* Actually render the given view.
* <p>The default implementation delegates to
* {@link org.springframework.web.servlet.ViewRendererServlet}.
* @param view the View to render
* @param model the associated model
* @param request current portlet render request
* @param response current portlet render response
* @throws Exception if there's a problem rendering the view
*/
protected void doRender(View view, Map model, PortletRequest request, MimeResponse response) throws Exception {
// Expose Portlet ApplicationContext to view objects.
request.setAttribute(ViewRendererServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE, getPortletApplicationContext());
// These attributes are required by the ViewRendererServlet.
request.setAttribute(ViewRendererServlet.VIEW_ATTRIBUTE, view);
request.setAttribute(ViewRendererServlet.MODEL_ATTRIBUTE, model);
// Include the content of the view in the render response.
getPortletContext().getRequestDispatcher(this.viewRendererUrl).include(request, response);
}
/**
* Determine an error ModelAndView via the registered HandlerExceptionResolvers.
* @param request current portlet request
* @param response current portlet response
* @param handler the executed handler, or null if none chosen at the time of
* the exception (for example, if multipart resolution failed)
* @param ex the exception that got thrown during handler execution
* @return a corresponding ModelAndView to forward to
* @throws Exception if no error ModelAndView found
*/
protected ModelAndView processHandlerException(
RenderRequest request, RenderResponse response, Object handler, Exception ex)
throws Exception {
ModelAndView exMv = null;
for (Iterator<HandlerExceptionResolver> it = this.handlerExceptionResolvers.iterator(); exMv == null && it.hasNext();) {
HandlerExceptionResolver resolver = it.next();
exMv = resolver.resolveException(request, response, handler, ex);
}
if (exMv != null) {
if (logger.isDebugEnabled()) {
logger.debug("HandlerExceptionResolver returned ModelAndView [" + exMv + "] for exception");
}
logger.warn("Handler execution resulted in exception - forwarding to resolved error view", ex);
return exMv;
}
else {
throw ex;
}
}
/**
* Determine an error ModelAndView via the registered HandlerExceptionResolvers.
* @param request current portlet request
* @param response current portlet response
* @param handler the executed handler, or null if none chosen at the time of
* the exception (for example, if multipart resolution failed)
* @param ex the exception that got thrown during handler execution
* @return a corresponding ModelAndView to forward to
* @throws Exception if no error ModelAndView found
*/
protected ModelAndView processHandlerException(
ResourceRequest request, ResourceResponse response, Object handler, Exception ex)
throws Exception {
ModelAndView exMv = null;
for (Iterator<HandlerExceptionResolver> it = this.handlerExceptionResolvers.iterator(); exMv == null && it.hasNext();) {
HandlerExceptionResolver resolver = it.next();
exMv = resolver.resolveException(request, response, handler, ex);
}
if (exMv != null) {
if (logger.isDebugEnabled()) {
logger.debug("HandlerExceptionResolver returned ModelAndView [" + exMv + "] for exception");
}
logger.warn("Handler execution resulted in exception - forwarding to resolved error view", ex);
return exMv;
}
else {
throw ex;
}
}
/**
* Trigger afterCompletion callbacks on the mapped HandlerInterceptors.
* Will just invoke afterCompletion for all interceptors whose preHandle
* invocation has successfully completed and returned true.
* @param mappedHandler the mapped HandlerExecutionChain
* @param interceptorIndex index of last interceptor that successfully completed
* @param ex Exception thrown on handler execution, or null if none
* @see HandlerInterceptor#afterRenderCompletion
*/
private void triggerAfterActionCompletion(HandlerExecutionChain mappedHandler, int interceptorIndex,
ActionRequest request, ActionResponse response, Exception ex)
throws Exception {
// Apply afterCompletion methods of registered interceptors.
if (mappedHandler != null) {
HandlerInterceptor[] interceptors = mappedHandler.getInterceptors();
if (interceptors != null) {
for (int i = interceptorIndex; i >= 0; i--) {
HandlerInterceptor interceptor = interceptors[i];
try {
interceptor.afterActionCompletion(request, response, mappedHandler.getHandler(), ex);
}
catch (Throwable ex2) {
logger.error("HandlerInterceptor.afterCompletion threw exception", ex2);
}
}
}
}
}
/**
* Trigger afterCompletion callbacks on the mapped HandlerInterceptors.
* Will just invoke afterCompletion for all interceptors whose preHandle
* invocation has successfully completed and returned true.
* @param mappedHandler the mapped HandlerExecutionChain
* @param interceptorIndex index of last interceptor that successfully completed
* @param ex Exception thrown on handler execution, or null if none
* @see HandlerInterceptor#afterRenderCompletion
*/
private void triggerAfterRenderCompletion(HandlerExecutionChain mappedHandler, int interceptorIndex,
RenderRequest request, RenderResponse response, Exception ex)
throws Exception {
// Apply afterCompletion methods of registered interceptors.
if (mappedHandler != null) {
HandlerInterceptor[] interceptors = mappedHandler.getInterceptors();
if (interceptors != null) {
for (int i = interceptorIndex; i >= 0; i--) {
HandlerInterceptor interceptor = interceptors[i];
try {
interceptor.afterRenderCompletion(request, response, mappedHandler.getHandler(), ex);
}
catch (Throwable ex2) {
logger.error("HandlerInterceptor.afterCompletion threw exception", ex2);
}
}
}
}
}
/**
* Trigger afterCompletion callbacks on the mapped HandlerInterceptors.
* Will just invoke afterCompletion for all interceptors whose preHandle
* invocation has successfully completed and returned true.
* @param mappedHandler the mapped HandlerExecutionChain
* @param interceptorIndex index of last interceptor that successfully completed
* @param ex Exception thrown on handler execution, or null if none
* @see HandlerInterceptor#afterRenderCompletion
*/
private void triggerAfterResourceCompletion(HandlerExecutionChain mappedHandler, int interceptorIndex,
ResourceRequest request, ResourceResponse response, Exception ex)
throws Exception {
// Apply afterCompletion methods of registered interceptors.
if (mappedHandler != null) {
HandlerInterceptor[] interceptors = mappedHandler.getInterceptors();
if (interceptors != null) {
for (int i = interceptorIndex; i >= 0; i--) {
HandlerInterceptor interceptor = interceptors[i];
try {
interceptor.afterResourceCompletion(request, response, mappedHandler.getHandler(), ex);
}
catch (Throwable ex2) {
logger.error("HandlerInterceptor.afterCompletion threw exception", ex2);
}
}
}
}
}
/**
* Trigger afterCompletion callbacks on the mapped HandlerInterceptors.
* Will just invoke afterCompletion for all interceptors whose preHandle
* invocation has successfully completed and returned true.
* @param mappedHandler the mapped HandlerExecutionChain
* @param interceptorIndex index of last interceptor that successfully completed
* @param ex Exception thrown on handler execution, or null if none
* @see HandlerInterceptor#afterRenderCompletion
*/
private void triggerAfterEventCompletion(HandlerExecutionChain mappedHandler, int interceptorIndex,
EventRequest request, EventResponse response, Exception ex)
throws Exception {
// Apply afterCompletion methods of registered interceptors.
if (mappedHandler != null) {
HandlerInterceptor[] interceptors = mappedHandler.getInterceptors();
if (interceptors != null) {
for (int i = interceptorIndex; i >= 0; i--) {
HandlerInterceptor interceptor = interceptors[i];
try {
interceptor.afterEventCompletion(request, response, mappedHandler.getHandler(), ex);
}
catch (Throwable ex2) {
logger.error("HandlerInterceptor.afterCompletion threw exception", ex2);
}
}
}
}
}
}
| org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/DispatcherPortlet.java | /*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.portlet;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.EventRequest;
import javax.portlet.EventResponse;
import javax.portlet.MimeResponse;
import javax.portlet.PortletException;
import javax.portlet.PortletRequest;
import javax.portlet.PortletResponse;
import javax.portlet.PortletSession;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.portlet.ResourceRequest;
import javax.portlet.ResourceResponse;
import javax.portlet.UnavailableException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.beans.factory.BeanInitializationException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.core.OrderComparator;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.portlet.multipart.MultipartActionRequest;
import org.springframework.web.portlet.multipart.PortletMultipartResolver;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewRendererServlet;
import org.springframework.web.servlet.ViewResolver;
/**
* Central dispatcher for use within the Portlet MVC framework, e.g. for web UI
* controllers. Dispatches to registered handlers for processing a portlet request.
*
* <p>This portlet is very flexible: It can be used with just about any workflow,
* with the installation of the appropriate adapter classes. It offers the
* following functionality that distinguishes it from other request-driven
* portlet MVC frameworks:
*
* <ul>
* <li>It is based around a JavaBeans configuration mechanism.
*
* <li>It can use any {@link HandlerMapping} implementation - pre-built or provided
* as part of an application - to control the routing of requests to handler objects.
* Default is a {@link org.springframework.web.portlet.mvc.annotation.DefaultAnnotationHandlerMapping}.
* HandlerMapping objects can be defined as beans in the portlet's application context,
* implementing the HandlerMapping interface, overriding the default HandlerMapping if present.
* HandlerMappings can be given any bean name (they are tested by type).
*
* <li>It can use any {@link HandlerAdapter}; this allows for using any handler interface.
* The default adapter is {@link org.springframework.web.portlet.mvc.SimpleControllerHandlerAdapter}
* for Spring's {@link org.springframework.web.portlet.mvc.Controller} interface.
* A default {@link org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter}
* will be registered as well. HandlerAdapter objects can be added as beans in the
* application context, overriding the default HandlerAdapter. Like HandlerMappings,
* HandlerAdapters can be given any bean name (they are tested by type).
*
* <li>The dispatcher's exception resolution strategy can be specified via a
* {@link HandlerExceptionResolver}, for example mapping certain exceptions to
* error pages. Default is none. Additional HandlerExceptionResolvers can be added
* through the application context. HandlerExceptionResolver can be given any
* bean name (they are tested by type).
*
* <li>Its view resolution strategy can be specified via a {@link ViewResolver}
* implementation, resolving symbolic view names into View objects. Default is
* {@link org.springframework.web.servlet.view.InternalResourceViewResolver}.
* ViewResolver objects can be added as beans in the application context,
* overriding the default ViewResolver. ViewResolvers can be given any bean name
* (they are tested by type).
*
* <li>The dispatcher's strategy for resolving multipart requests is determined by a
* {@link org.springframework.web.portlet.multipart.PortletMultipartResolver} implementation.
* An implementations for Jakarta Commons FileUpload is included:
* {@link org.springframework.web.portlet.multipart.CommonsPortletMultipartResolver}.
* The MultipartResolver bean name is "portletMultipartResolver"; default is none.
* </ul>
*
* <p><b>NOTE: The <code>@RequestMapping</code> annotation will only be processed
* if a corresponding <code>HandlerMapping</code> (for type level annotations)
* and/or <code>HandlerAdapter</code> (for method level annotations)
* is present in the dispatcher.</b> This is the case by default.
* However, if you are defining custom <code>HandlerMappings</code> or
* <code>HandlerAdapters</code>, then you need to make sure that a
* corresponding custom <code>DefaultAnnotationHandlerMapping</code>
* and/or <code>AnnotationMethodHandlerAdapter</code> is defined as well
* - provided that you intend to use <code>@RequestMapping</code>.
*
* <p><b>A web application can define any number of DispatcherPortlets.</b>
* Each portlet will operate in its own namespace, loading its own application
* context with mappings, handlers, etc. Only the root application context
* as loaded by {@link org.springframework.web.context.ContextLoaderListener},
* if any, will be shared.
*
* <p>Thanks to Rainer Schmitz and Nick Lothian for their suggestions!
*
* @author William G. Thompson, Jr.
* @author John A. Lewis
* @author Juergen Hoeller
* @since 2.0
* @see org.springframework.web.portlet.mvc.Controller
* @see org.springframework.web.servlet.ViewRendererServlet
* @see org.springframework.web.context.ContextLoaderListener
*/
public class DispatcherPortlet extends FrameworkPortlet {
/**
* Well-known name for the PortletMultipartResolver object in the bean factory for this namespace.
*/
public static final String MULTIPART_RESOLVER_BEAN_NAME = "portletMultipartResolver";
/**
* Well-known name for the HandlerMapping object in the bean factory for this namespace.
* Only used when "detectAllHandlerMappings" is turned off.
* @see #setDetectAllViewResolvers
*/
public static final String HANDLER_MAPPING_BEAN_NAME = "handlerMapping";
/**
* Well-known name for the HandlerAdapter object in the bean factory for this namespace.
* Only used when "detectAllHandlerAdapters" is turned off.
* @see #setDetectAllHandlerAdapters
*/
public static final String HANDLER_ADAPTER_BEAN_NAME = "handlerAdapter";
/**
* Well-known name for the HandlerExceptionResolver object in the bean factory for this
* namespace. Only used when "detectAllHandlerExceptionResolvers" is turned off.
* @see #setDetectAllViewResolvers
*/
public static final String HANDLER_EXCEPTION_RESOLVER_BEAN_NAME = "handlerExceptionResolver";
/**
* Well-known name for the ViewResolver object in the bean factory for this namespace.
*/
public static final String VIEW_RESOLVER_BEAN_NAME = "viewResolver";
/**
* Default URL to ViewRendererServlet. This bridge servlet is used to convert
* portlet render requests to servlet requests in order to leverage the view support
* in the <code>org.springframework.web.view</code> package.
*/
public static final String DEFAULT_VIEW_RENDERER_URL = "/WEB-INF/servlet/view";
/**
* Request attribute to hold the currently chosen HandlerExecutionChain.
* Only used for internal optimizations.
*/
public static final String HANDLER_EXECUTION_CHAIN_ATTRIBUTE =
DispatcherPortlet.class.getName() + ".HANDLER";
/**
* Unlike the Servlet version of this class, we have to deal with the
* two-phase nature of the portlet request. To do this, we need to pass
* forward any exception that occurs during the action phase, so that
* it can be displayed in the render phase. The only direct way to pass
* things forward and preserve them for each render request is through
* render parameters, but these are limited to String objects and we need
* to pass the Exception itself. The only other way to do this is in the
* session. The bad thing about using the session is that we have no way
* of knowing when we are done re-rendering the request and so we don't
* know when we can remove the objects from the session. So we will end
* up polluting the session with an old exception when we finally leave
* the render phase of one request and move on to something else.
*/
public static final String ACTION_EXCEPTION_SESSION_ATTRIBUTE =
DispatcherPortlet.class.getName() + ".ACTION_EXCEPTION";
/**
* This render parameter is used to indicate forward to the render phase
* that an exception occurred during the action phase.
*/
public static final String ACTION_EXCEPTION_RENDER_PARAMETER = "actionException";
/**
* Log category to use when no mapped handler is found for a request.
*/
public static final String PAGE_NOT_FOUND_LOG_CATEGORY = "org.springframework.web.portlet.PageNotFound";
/**
* Name of the class path resource (relative to the DispatcherPortlet class)
* that defines DispatcherPortet's default strategy names.
*/
private static final String DEFAULT_STRATEGIES_PATH = "DispatcherPortlet.properties";
/**
* Additional logger to use when no mapped handler is found for a request.
*/
protected static final Log pageNotFoundLogger = LogFactory.getLog(PAGE_NOT_FOUND_LOG_CATEGORY);
private static final Properties defaultStrategies;
static {
// Load default strategy implementations from properties file.
// This is currently strictly internal and not meant to be customized
// by application developers.
try {
ClassPathResource resource = new ClassPathResource(DEFAULT_STRATEGIES_PATH, DispatcherPortlet.class);
defaultStrategies = PropertiesLoaderUtils.loadProperties(resource);
}
catch (IOException ex) {
throw new IllegalStateException("Could not load 'DispatcherPortlet.properties': " + ex.getMessage());
}
}
/** Detect all HandlerMappings or just expect "handlerMapping" bean? */
private boolean detectAllHandlerMappings = true;
/** Detect all HandlerAdapters or just expect "handlerAdapter" bean? */
private boolean detectAllHandlerAdapters = true;
/** Detect all HandlerExceptionResolvers or just expect "handlerExceptionResolver" bean? */
private boolean detectAllHandlerExceptionResolvers = true;
/** Detect all ViewResolvers or just expect "viewResolver" bean? */
private boolean detectAllViewResolvers = true;
/** URL that points to the ViewRendererServlet */
private String viewRendererUrl = DEFAULT_VIEW_RENDERER_URL;
/** MultipartResolver used by this portlet */
private PortletMultipartResolver multipartResolver;
/** List of HandlerMappings used by this portlet */
private List<HandlerMapping> handlerMappings;
/** List of HandlerAdapters used by this portlet */
private List<HandlerAdapter> handlerAdapters;
/** List of HandlerExceptionResolvers used by this portlet */
private List<HandlerExceptionResolver> handlerExceptionResolvers;
/** List of ViewResolvers used by this portlet */
private List<ViewResolver> viewResolvers;
/**
* Set whether to detect all HandlerMapping beans in this portlet's context.
* Else, just a single bean with name "handlerMapping" will be expected.
* <p>Default is true. Turn this off if you want this portlet to use a
* single HandlerMapping, despite multiple HandlerMapping beans being
* defined in the context.
*/
public void setDetectAllHandlerMappings(boolean detectAllHandlerMappings) {
this.detectAllHandlerMappings = detectAllHandlerMappings;
}
/**
* Set whether to detect all HandlerAdapter beans in this portlet's context.
* Else, just a single bean with name "handlerAdapter" will be expected.
* <p>Default is "true". Turn this off if you want this portlet to use a
* single HandlerAdapter, despite multiple HandlerAdapter beans being
* defined in the context.
*/
public void setDetectAllHandlerAdapters(boolean detectAllHandlerAdapters) {
this.detectAllHandlerAdapters = detectAllHandlerAdapters;
}
/**
* Set whether to detect all HandlerExceptionResolver beans in this portlet's context.
* Else, just a single bean with name "handlerExceptionResolver" will be expected.
* <p>Default is true. Turn this off if you want this portlet to use a
* single HandlerExceptionResolver, despite multiple HandlerExceptionResolver
* beans being defined in the context.
*/
public void setDetectAllHandlerExceptionResolvers(boolean detectAllHandlerExceptionResolvers) {
this.detectAllHandlerExceptionResolvers = detectAllHandlerExceptionResolvers;
}
/**
* Set whether to detect all ViewResolver beans in this portlet's context.
* Else, just a single bean with name "viewResolver" will be expected.
* <p>Default is true. Turn this off if you want this portlet to use a
* single ViewResolver, despite multiple ViewResolver beans being
* defined in the context.
*/
public void setDetectAllViewResolvers(boolean detectAllViewResolvers) {
this.detectAllViewResolvers = detectAllViewResolvers;
}
/**
* Set the URL to the ViewRendererServlet. That servlet is used to
* ultimately render all views in the portlet application.
*/
public void setViewRendererUrl(String viewRendererUrl) {
this.viewRendererUrl = viewRendererUrl;
}
/**
* This implementation calls {@link #initStrategies}.
*/
@Override
public void onRefresh(ApplicationContext context) {
initStrategies(context);
}
/**
* Refresh the strategy objects that this portlet uses.
* <p>May be overridden in subclasses in order to initialize
* further strategy objects.
*/
protected void initStrategies(ApplicationContext context) {
initMultipartResolver(context);
initHandlerMappings(context);
initHandlerAdapters(context);
initHandlerExceptionResolvers(context);
initViewResolvers(context);
}
/**
* Initialize the PortletMultipartResolver used by this class.
* <p>If no valid bean is defined with the given name in the BeanFactory
* for this namespace, no multipart handling is provided.
*/
private void initMultipartResolver(ApplicationContext context) {
try {
this.multipartResolver = context.getBean(MULTIPART_RESOLVER_BEAN_NAME, PortletMultipartResolver.class);
if (logger.isDebugEnabled()) {
logger.debug("Using MultipartResolver [" + this.multipartResolver + "]");
}
}
catch (NoSuchBeanDefinitionException ex) {
// Default is no multipart resolver.
this.multipartResolver = null;
if (logger.isDebugEnabled()) {
logger.debug("Unable to locate PortletMultipartResolver with name '" + MULTIPART_RESOLVER_BEAN_NAME +
"': no multipart request handling provided");
}
}
}
/**
* Initialize the HandlerMappings used by this class.
* <p>If no HandlerMapping beans are defined in the BeanFactory
* for this namespace, we default to PortletModeHandlerMapping.
*/
private void initHandlerMappings(ApplicationContext context) {
this.handlerMappings = null;
if (this.detectAllHandlerMappings) {
// Find all HandlerMappings in the ApplicationContext, including ancestor contexts.
Map<String, HandlerMapping> matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(
context, HandlerMapping.class, true, false);
if (!matchingBeans.isEmpty()) {
this.handlerMappings = new ArrayList<HandlerMapping>(matchingBeans.values());
// We keep HandlerMappings in sorted order.
OrderComparator.sort(this.handlerMappings);
}
}
else {
try {
HandlerMapping hm = context.getBean(HANDLER_MAPPING_BEAN_NAME, HandlerMapping.class);
this.handlerMappings = Collections.singletonList(hm);
}
catch (NoSuchBeanDefinitionException ex) {
// Ignore, we'll add a default HandlerMapping later.
}
}
// Ensure we have at least one HandlerMapping, by registering
// a default HandlerMapping if no other mappings are found.
if (this.handlerMappings == null) {
this.handlerMappings = getDefaultStrategies(context, HandlerMapping.class);
if (logger.isDebugEnabled()) {
logger.debug("No HandlerMappings found in portlet '" + getPortletName() + "': using default");
}
}
}
/**
* Initialize the HandlerAdapters used by this class.
* <p>If no HandlerAdapter beans are defined in the BeanFactory
* for this namespace, we default to SimpleControllerHandlerAdapter.
*/
private void initHandlerAdapters(ApplicationContext context) {
this.handlerAdapters = null;
if (this.detectAllHandlerAdapters) {
// Find all HandlerAdapters in the ApplicationContext, including ancestor contexts.
Map<String, HandlerAdapter> matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(
context, HandlerAdapter.class, true, false);
if (!matchingBeans.isEmpty()) {
this.handlerAdapters = new ArrayList<HandlerAdapter>(matchingBeans.values());
// We keep HandlerAdapters in sorted order.
OrderComparator.sort(this.handlerAdapters);
}
}
else {
try {
HandlerAdapter ha = context.getBean(HANDLER_ADAPTER_BEAN_NAME, HandlerAdapter.class);
this.handlerAdapters = Collections.singletonList(ha);
}
catch (NoSuchBeanDefinitionException ex) {
// Ignore, we'll add a default HandlerAdapter later.
}
}
// Ensure we have at least some HandlerAdapters, by registering
// default HandlerAdapters if no other adapters are found.
if (this.handlerAdapters == null) {
this.handlerAdapters = getDefaultStrategies(context, HandlerAdapter.class);
if (logger.isDebugEnabled()) {
logger.debug("No HandlerAdapters found in portlet '" + getPortletName() + "': using default");
}
}
}
/**
* Initialize the HandlerExceptionResolver used by this class.
* <p>If no bean is defined with the given name in the BeanFactory
* for this namespace, we default to no exception resolver.
*/
private void initHandlerExceptionResolvers(ApplicationContext context) {
this.handlerExceptionResolvers = null;
if (this.detectAllHandlerExceptionResolvers) {
// Find all HandlerExceptionResolvers in the ApplicationContext, including ancestor contexts.
Map<String, HandlerExceptionResolver> matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(
context, HandlerExceptionResolver.class, true, false);
if (!matchingBeans.isEmpty()) {
this.handlerExceptionResolvers = new ArrayList<HandlerExceptionResolver>(matchingBeans.values());
// We keep HandlerExceptionResolvers in sorted order.
OrderComparator.sort(this.handlerExceptionResolvers);
}
}
else {
try {
HandlerExceptionResolver her = context.getBean(
HANDLER_EXCEPTION_RESOLVER_BEAN_NAME, HandlerExceptionResolver.class);
this.handlerExceptionResolvers = Collections.singletonList(her);
}
catch (NoSuchBeanDefinitionException ex) {
// Ignore, no HandlerExceptionResolver is fine too.
}
}
// Just for consistency, check for default HandlerExceptionResolvers...
// There aren't any in usual scenarios.
if (this.handlerExceptionResolvers == null) {
this.handlerExceptionResolvers = getDefaultStrategies(context, HandlerExceptionResolver.class);
if (logger.isDebugEnabled()) {
logger.debug("No HandlerExceptionResolvers found in portlet '" + getPortletName() + "': using default");
}
}
}
/**
* Initialize the ViewResolvers used by this class.
* <p>If no ViewResolver beans are defined in the BeanFactory
* for this namespace, we default to InternalResourceViewResolver.
*/
private void initViewResolvers(ApplicationContext context) {
this.viewResolvers = null;
if (this.detectAllViewResolvers) {
// Find all ViewResolvers in the ApplicationContext, including ancestor contexts.
Map<String, ViewResolver> matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(
context, ViewResolver.class, true, false);
if (!matchingBeans.isEmpty()) {
this.viewResolvers = new ArrayList<ViewResolver>(matchingBeans.values());
// We keep ViewResolvers in sorted order.
OrderComparator.sort(this.viewResolvers);
}
}
else {
try {
ViewResolver vr = context.getBean(VIEW_RESOLVER_BEAN_NAME, ViewResolver.class);
this.viewResolvers = Collections.singletonList(vr);
}
catch (NoSuchBeanDefinitionException ex) {
// Ignore, we'll add a default ViewResolver later.
}
}
// Ensure we have at least one ViewResolver, by registering
// a default ViewResolver if no other resolvers are found.
if (this.viewResolvers == null) {
this.viewResolvers = getDefaultStrategies(context, ViewResolver.class);
if (logger.isDebugEnabled()) {
logger.debug("No ViewResolvers found in portlet '" + getPortletName() + "': using default");
}
}
}
/**
* Return the default strategy object for the given strategy interface.
* <p>The default implementation delegates to {@link #getDefaultStrategies},
* expecting a single object in the list.
* @param context the current Portlet ApplicationContext
* @param strategyInterface the strategy interface
* @return the corresponding strategy object
* @see #getDefaultStrategies
*/
protected <T> T getDefaultStrategy(ApplicationContext context, Class<T> strategyInterface) {
List<T> strategies = getDefaultStrategies(context, strategyInterface);
if (strategies.size() != 1) {
throw new BeanInitializationException(
"DispatcherPortlet needs exactly 1 strategy for interface [" + strategyInterface.getName() + "]");
}
return strategies.get(0);
}
/**
* Create a List of default strategy objects for the given strategy interface.
* <p>The default implementation uses the "DispatcherPortlet.properties" file
* (in the same package as the DispatcherPortlet class) to determine the class names.
* It instantiates the strategy objects and satisifies ApplicationContextAware
* if necessary.
* @param context the current Portlet ApplicationContext
* @param strategyInterface the strategy interface
* @return the List of corresponding strategy objects
*/
@SuppressWarnings("unchecked")
protected <T> List<T> getDefaultStrategies(ApplicationContext context, Class<T> strategyInterface) {
String key = strategyInterface.getName();
String value = defaultStrategies.getProperty(key);
if (value != null) {
String[] classNames = StringUtils.commaDelimitedListToStringArray(value);
List<T> strategies = new ArrayList<T>(classNames.length);
for (String className : classNames) {
try {
Class clazz = ClassUtils.forName(className, DispatcherPortlet.class.getClassLoader());
Object strategy = createDefaultStrategy(context, clazz);
strategies.add((T) strategy);
}
catch (ClassNotFoundException ex) {
throw new BeanInitializationException(
"Could not find DispatcherPortlet's default strategy class [" + className +
"] for interface [" + key + "]", ex);
}
catch (LinkageError err) {
throw new BeanInitializationException(
"Error loading DispatcherPortlet's default strategy class [" + className +
"] for interface [" + key + "]: problem with class file or dependent class", err);
}
}
return strategies;
}
else {
return new LinkedList<T>();
}
}
/**
* Create a default strategy.
* <p>The default implementation uses
* {@link org.springframework.beans.factory.config.AutowireCapableBeanFactory#createBean}.
* @param context the current Portlet ApplicationContext
* @param clazz the strategy implementation class to instantiate
* @return the fully configured strategy instance
* @see org.springframework.context.ApplicationContext#getAutowireCapableBeanFactory()
*/
protected Object createDefaultStrategy(ApplicationContext context, Class<?> clazz) {
return context.getAutowireCapableBeanFactory().createBean(clazz);
}
/**
* Obtain this portlet's PortletMultipartResolver, if any.
* @return the PortletMultipartResolver used by this portlet, or <code>null</code>
* if none (indicating that no multipart support is available)
*/
public PortletMultipartResolver getMultipartResolver() {
return this.multipartResolver;
}
/**
* Processes the actual dispatching to the handler for action requests.
* <p>The handler will be obtained by applying the portlet's HandlerMappings in order.
* The HandlerAdapter will be obtained by querying the portlet's installed
* HandlerAdapters to find the first that supports the handler class.
* @param request current portlet action request
* @param response current portlet Action response
* @throws Exception in case of any kind of processing failure
*/
@Override
protected void doActionService(ActionRequest request, ActionResponse response) throws Exception {
if (logger.isDebugEnabled()) {
logger.debug("DispatcherPortlet with name '" + getPortletName() + "' received action request");
}
ActionRequest processedRequest = request;
HandlerExecutionChain mappedHandler = null;
int interceptorIndex = -1;
try {
processedRequest = checkMultipart(request);
// Determine handler for the current request.
mappedHandler = getHandler(processedRequest, false);
if (mappedHandler == null || mappedHandler.getHandler() == null) {
noHandlerFound(processedRequest, response);
return;
}
// Apply preHandle methods of registered interceptors.
HandlerInterceptor[] interceptors = mappedHandler.getInterceptors();
if (interceptors != null) {
for (int i = 0; i < interceptors.length; i++) {
HandlerInterceptor interceptor = interceptors[i];
if (!interceptor.preHandleAction(processedRequest, response, mappedHandler.getHandler())) {
triggerAfterActionCompletion(mappedHandler, interceptorIndex, processedRequest, response, null);
return;
}
interceptorIndex = i;
}
}
// Actually invoke the handler.
HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());
ha.handleAction(processedRequest, response, mappedHandler.getHandler());
// Trigger after-completion for successful outcome.
triggerAfterActionCompletion(mappedHandler, interceptorIndex, processedRequest, response, null);
}
catch (Exception ex) {
// Trigger after-completion for thrown exception.
triggerAfterActionCompletion(mappedHandler, interceptorIndex, processedRequest, response, ex);
// Forward the exception to the render phase to be displayed.
try {
response.setRenderParameter(ACTION_EXCEPTION_RENDER_PARAMETER, ex.toString());
request.getPortletSession().setAttribute(ACTION_EXCEPTION_SESSION_ATTRIBUTE, ex);
logger.debug("Caught exception during action phase - forwarding to render phase", ex);
}
catch (IllegalStateException ex2) {
// Probably sendRedirect called... need to rethrow exception immediately.
throw ex;
}
}
catch (Error err) {
PortletException ex =
new PortletException("Error occured during request processing: " + err.getMessage(), err);
// Trigger after-completion for thrown exception.
triggerAfterActionCompletion(mappedHandler, interceptorIndex, processedRequest, response, ex);
throw ex;
}
finally {
// Clean up any resources used by a multipart request.
if (processedRequest instanceof MultipartActionRequest && processedRequest != request) {
this.multipartResolver.cleanupMultipart((MultipartActionRequest) processedRequest);
}
}
}
/**
* Processes the actual dispatching to the handler for render requests.
* <p>The handler will be obtained by applying the portlet's HandlerMappings in order.
* The HandlerAdapter will be obtained by querying the portlet's installed
* HandlerAdapters to find the first that supports the handler class.
* @param request current portlet render request
* @param response current portlet render response
* @throws Exception in case of any kind of processing failure
*/
@Override
protected void doRenderService(RenderRequest request, RenderResponse response) throws Exception {
if (logger.isDebugEnabled()) {
logger.debug("DispatcherPortlet with name '" + getPortletName() + "' received render request");
}
HandlerExecutionChain mappedHandler = null;
int interceptorIndex = -1;
try {
ModelAndView mv;
try {
// Check for forwarded exception from the action phase
PortletSession session = request.getPortletSession(false);
if (session != null) {
if (request.getParameter(ACTION_EXCEPTION_RENDER_PARAMETER) != null) {
Exception ex = (Exception) session.getAttribute(ACTION_EXCEPTION_SESSION_ATTRIBUTE);
if (ex != null) {
logger.debug("Render phase found exception caught during action phase - rethrowing it");
throw ex;
}
}
else {
session.removeAttribute(ACTION_EXCEPTION_SESSION_ATTRIBUTE);
}
}
// Determine handler for the current request.
mappedHandler = getHandler(request, false);
if (mappedHandler == null || mappedHandler.getHandler() == null) {
noHandlerFound(request, response);
return;
}
// Apply preHandle methods of registered interceptors.
HandlerInterceptor[] interceptors = mappedHandler.getInterceptors();
if (interceptors != null) {
for (int i = 0; i < interceptors.length; i++) {
HandlerInterceptor interceptor = interceptors[i];
if (!interceptor.preHandleRender(request, response, mappedHandler.getHandler())) {
triggerAfterRenderCompletion(mappedHandler, interceptorIndex, request, response, null);
return;
}
interceptorIndex = i;
}
}
// Actually invoke the handler.
HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());
mv = ha.handleRender(request, response, mappedHandler.getHandler());
// Apply postHandle methods of registered interceptors.
if (interceptors != null) {
for (int i = interceptors.length - 1; i >= 0; i--) {
HandlerInterceptor interceptor = interceptors[i];
interceptor.postHandleRender(request, response, mappedHandler.getHandler(), mv);
}
}
}
catch (ModelAndViewDefiningException ex) {
logger.debug("ModelAndViewDefiningException encountered", ex);
mv = ex.getModelAndView();
}
catch (Exception ex) {
Object handler = (mappedHandler != null ? mappedHandler.getHandler() : null);
mv = processHandlerException(request, response, handler, ex);
}
// Did the handler return a view to render?
if (mv != null && !mv.isEmpty()) {
render(mv, request, response);
}
else {
if (logger.isDebugEnabled()) {
logger.debug("Null ModelAndView returned to DispatcherPortlet with name '" +
getPortletName() + "': assuming HandlerAdapter completed request handling");
}
}
// Trigger after-completion for successful outcome.
triggerAfterRenderCompletion(mappedHandler, interceptorIndex, request, response, null);
}
catch (Exception ex) {
// Trigger after-completion for thrown exception.
triggerAfterRenderCompletion(mappedHandler, interceptorIndex, request, response, ex);
throw ex;
}
catch (Error err) {
PortletException ex =
new PortletException("Error occured during request processing: " + err.getMessage(), err);
// Trigger after-completion for thrown exception.
triggerAfterRenderCompletion(mappedHandler, interceptorIndex, request, response, ex);
throw ex;
}
}
/**
* Processes the actual dispatching to the handler for resource requests.
* <p>The handler will be obtained by applying the portlet's HandlerMappings in order.
* The HandlerAdapter will be obtained by querying the portlet's installed
* HandlerAdapters to find the first that supports the handler class.
* @param request current portlet render request
* @param response current portlet render response
* @throws Exception in case of any kind of processing failure
*/
@Override
protected void doResourceService(ResourceRequest request, ResourceResponse response) throws Exception {
if (logger.isDebugEnabled()) {
logger.debug("DispatcherPortlet with name '" + getPortletName() + "' received resource request");
}
HandlerExecutionChain mappedHandler = null;
int interceptorIndex = -1;
try {
ModelAndView mv;
try {
// Determine handler for the current request.
mappedHandler = getHandler(request, false);
if (mappedHandler == null || mappedHandler.getHandler() == null) {
noHandlerFound(request, response);
return;
}
// Apply preHandle methods of registered interceptors.
HandlerInterceptor[] interceptors = mappedHandler.getInterceptors();
if (interceptors != null) {
for (int i = 0; i < interceptors.length; i++) {
HandlerInterceptor interceptor = interceptors[i];
if (!interceptor.preHandleResource(request, response, mappedHandler.getHandler())) {
triggerAfterResourceCompletion(mappedHandler, interceptorIndex, request, response, null);
return;
}
interceptorIndex = i;
}
}
// Actually invoke the handler.
HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());
mv = ha.handleResource(request, response, mappedHandler.getHandler());
// Apply postHandle methods of registered interceptors.
if (interceptors != null) {
for (int i = interceptors.length - 1; i >= 0; i--) {
HandlerInterceptor interceptor = interceptors[i];
interceptor.postHandleResource(request, response, mappedHandler.getHandler(), mv);
}
}
}
catch (ModelAndViewDefiningException ex) {
logger.debug("ModelAndViewDefiningException encountered", ex);
mv = ex.getModelAndView();
}
catch (Exception ex) {
Object handler = (mappedHandler != null ? mappedHandler.getHandler() : null);
mv = processHandlerException(request, response, handler, ex);
}
// Did the handler return a view to render?
if (mv != null && !mv.isEmpty()) {
render(mv, request, response);
}
else {
if (logger.isDebugEnabled()) {
logger.debug("Null ModelAndView returned to DispatcherPortlet with name '" +
getPortletName() + "': assuming HandlerAdapter completed request handling");
}
}
// Trigger after-completion for successful outcome.
triggerAfterResourceCompletion(mappedHandler, interceptorIndex, request, response, null);
}
catch (Exception ex) {
// Trigger after-completion for thrown exception.
triggerAfterResourceCompletion(mappedHandler, interceptorIndex, request, response, ex);
throw ex;
}
catch (Error err) {
PortletException ex =
new PortletException("Error occured during request processing: " + err.getMessage(), err);
// Trigger after-completion for thrown exception.
triggerAfterResourceCompletion(mappedHandler, interceptorIndex, request, response, ex);
throw ex;
}
}
/**
* Processes the actual dispatching to the handler for event requests.
* <p>The handler will be obtained by applying the portlet's HandlerMappings in order.
* The HandlerAdapter will be obtained by querying the portlet's installed
* HandlerAdapters to find the first that supports the handler class.
* @param request current portlet action request
* @param response current portlet Action response
* @throws Exception in case of any kind of processing failure
*/
@Override
protected void doEventService(EventRequest request, EventResponse response) throws Exception {
if (logger.isDebugEnabled()) {
logger.debug("DispatcherPortlet with name '" + getPortletName() + "' received action request");
}
HandlerExecutionChain mappedHandler = null;
int interceptorIndex = -1;
try {
// Determine handler for the current request.
mappedHandler = getHandler(request, false);
if (mappedHandler == null || mappedHandler.getHandler() == null) {
noHandlerFound(request, response);
return;
}
// Apply preHandle methods of registered interceptors.
HandlerInterceptor[] interceptors = mappedHandler.getInterceptors();
if (interceptors != null) {
for (int i = 0; i < interceptors.length; i++) {
HandlerInterceptor interceptor = interceptors[i];
if (!interceptor.preHandleEvent(request, response, mappedHandler.getHandler())) {
triggerAfterEventCompletion(mappedHandler, interceptorIndex, request, response, null);
return;
}
interceptorIndex = i;
}
}
// Actually invoke the handler.
HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());
ha.handleEvent(request, response, mappedHandler.getHandler());
// Trigger after-completion for successful outcome.
triggerAfterEventCompletion(mappedHandler, interceptorIndex, request, response, null);
}
catch (Exception ex) {
// Trigger after-completion for thrown exception.
triggerAfterEventCompletion(mappedHandler, interceptorIndex, request, response, ex);
// Forward the exception to the render phase to be displayed.
try {
response.setRenderParameter(ACTION_EXCEPTION_RENDER_PARAMETER, ex.toString());
request.getPortletSession().setAttribute(ACTION_EXCEPTION_SESSION_ATTRIBUTE, ex);
logger.debug("Caught exception during action phase - forwarding to render phase", ex);
}
catch (IllegalStateException ex2) {
// Probably sendRedirect called... need to rethrow exception immediately.
throw ex;
}
}
catch (Error err) {
PortletException ex =
new PortletException("Error occured during request processing: " + err.getMessage(), err);
// Trigger after-completion for thrown exception.
triggerAfterEventCompletion(mappedHandler, interceptorIndex, request, response, ex);
throw ex;
}
}
/**
* Convert the request into a multipart request, and make multipart resolver available.
* If no multipart resolver is set, simply use the existing request.
* @param request current HTTP request
* @return the processed request (multipart wrapper if necessary)
*/
protected ActionRequest checkMultipart(ActionRequest request) throws MultipartException {
if (this.multipartResolver != null && this.multipartResolver.isMultipart(request)) {
if (request instanceof MultipartActionRequest) {
logger.debug("Request is already a MultipartActionRequest - probably in a forward");
}
else {
return this.multipartResolver.resolveMultipart(request);
}
}
// If not returned before: return original request.
return request;
}
/**
* Return the HandlerExecutionChain for this request.
* Try all handler mappings in order.
* @param request current portlet request
* @param cache whether to cache the HandlerExecutionChain in a request attribute
* @return the HandlerExceutionChain, or null if no handler could be found
*/
protected HandlerExecutionChain getHandler(PortletRequest request, boolean cache) throws Exception {
HandlerExecutionChain handler =
(HandlerExecutionChain) request.getAttribute(HANDLER_EXECUTION_CHAIN_ATTRIBUTE);
if (handler != null) {
if (!cache) {
request.removeAttribute(HANDLER_EXECUTION_CHAIN_ATTRIBUTE);
}
return handler;
}
for (HandlerMapping hm : this.handlerMappings) {
if (logger.isDebugEnabled()) {
logger.debug(
"Testing handler map [" + hm + "] in DispatcherPortlet with name '" + getPortletName() + "'");
}
handler = hm.getHandler(request);
if (handler != null) {
if (cache) {
request.setAttribute(HANDLER_EXECUTION_CHAIN_ATTRIBUTE, handler);
}
return handler;
}
}
return null;
}
/**
* No handler found -> throw appropriate exception.
* @param request current portlet request
* @param response current portlet response
* @throws Exception if preparing the response failed
*/
protected void noHandlerFound(PortletRequest request, PortletResponse response) throws Exception {
if (pageNotFoundLogger.isWarnEnabled()) {
pageNotFoundLogger.warn("No mapping found for current request " +
"in DispatcherPortlet with name '" + getPortletName() +
"', mode '" + request.getPortletMode() +
"', phase '" + request.getAttribute(PortletRequest.LIFECYCLE_PHASE) +
"', session '" + request.getRequestedSessionId() +
"', user '" + getUsernameForRequest(request) + "'");
}
throw new UnavailableException("No handler found for request");
}
/**
* Return the HandlerAdapter for this handler object.
* @param handler the handler object to find an adapter for
* @throws PortletException if no HandlerAdapter can be found for the handler.
* This is a fatal error.
*/
protected HandlerAdapter getHandlerAdapter(Object handler) throws PortletException {
for (HandlerAdapter ha : this.handlerAdapters) {
if (logger.isDebugEnabled()) {
logger.debug("Testing handler adapter [" + ha + "]");
}
if (ha.supports(handler)) {
return ha;
}
}
throw new PortletException("No adapter for handler [" + handler +
"]: Does your handler implement a supported interface like Controller?");
}
/**
* Render the given ModelAndView. This is the last stage in handling a request.
* It may involve resolving the view by name.
* @param mv the ModelAndView to render
* @param request current portlet render request
* @param response current portlet render response
* @throws Exception if there's a problem rendering the view
*/
protected void render(ModelAndView mv, PortletRequest request, MimeResponse response) throws Exception {
View view;
if (mv.isReference()) {
// We need to resolve the view name.
view = resolveViewName(mv.getViewName(), mv.getModelInternal(), request);
if (view == null) {
throw new PortletException("Could not resolve view with name '" + mv.getViewName() +
"' in portlet with name '" + getPortletName() + "'");
}
}
else {
// No need to lookup: the ModelAndView object contains the actual View object.
Object viewObject = mv.getView();
if (viewObject == null) {
throw new PortletException("ModelAndView [" + mv + "] neither contains a view name nor a " +
"View object in portlet with name '" + getPortletName() + "'");
}
if (!(viewObject instanceof View)) {
throw new PortletException(
"View object [" + viewObject + "] is not an instance of [org.springframework.web.servlet.View] - " +
"DispatcherPortlet does not support any other view types");
}
view = (View) viewObject;
}
// Set the content type on the response if needed and if possible.
// The Portlet spec requires the content type to be set on the RenderResponse;
// it's not sufficient to let the View set it on the ServletResponse.
if (response.getContentType() != null) {
if (logger.isDebugEnabled()) {
logger.debug("Portlet response content type already set to [" + response.getContentType() + "]");
}
}
else {
// No Portlet content type specified yet -> use the view-determined type.
String contentType = view.getContentType();
if (contentType != null) {
if (logger.isDebugEnabled()) {
logger.debug("Setting portlet response content type to view-determined type [" + contentType + "]");
}
response.setContentType(contentType);
}
}
doRender(view, mv.getModelInternal(), request, response);
}
/**
* Resolve the given view name into a View object (to be rendered).
* <p>Default implementations asks all ViewResolvers of this dispatcher.
* Can be overridden for custom resolution strategies, potentially based
* on specific model attributes or request parameters.
* @param viewName the name of the view to resolve
* @param model the model to be passed to the view
* @param request current portlet render request
* @return the View object, or null if none found
* @throws Exception if the view cannot be resolved
* (typically in case of problems creating an actual View object)
* @see ViewResolver#resolveViewName
*/
protected View resolveViewName(String viewName, Map model, PortletRequest request) throws Exception {
for (ViewResolver viewResolver : this.viewResolvers) {
View view = viewResolver.resolveViewName(viewName, request.getLocale());
if (view != null) {
return view;
}
}
return null;
}
/**
* Actually render the given view.
* <p>The default implementation delegates to
* {@link org.springframework.web.servlet.ViewRendererServlet}.
* @param view the View to render
* @param model the associated model
* @param request current portlet render request
* @param response current portlet render response
* @throws Exception if there's a problem rendering the view
*/
protected void doRender(View view, Map model, PortletRequest request, MimeResponse response) throws Exception {
// Expose Portlet ApplicationContext to view objects.
request.setAttribute(ViewRendererServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE, getPortletApplicationContext());
// These attributes are required by the ViewRendererServlet.
request.setAttribute(ViewRendererServlet.VIEW_ATTRIBUTE, view);
request.setAttribute(ViewRendererServlet.MODEL_ATTRIBUTE, model);
// Include the content of the view in the render response.
getPortletContext().getRequestDispatcher(this.viewRendererUrl).include(request, response);
}
/**
* Determine an error ModelAndView via the registered HandlerExceptionResolvers.
* @param request current portlet request
* @param response current portlet response
* @param handler the executed handler, or null if none chosen at the time of
* the exception (for example, if multipart resolution failed)
* @param ex the exception that got thrown during handler execution
* @return a corresponding ModelAndView to forward to
* @throws Exception if no error ModelAndView found
*/
protected ModelAndView processHandlerException(
RenderRequest request, RenderResponse response, Object handler, Exception ex)
throws Exception {
ModelAndView exMv = null;
for (Iterator<HandlerExceptionResolver> it = this.handlerExceptionResolvers.iterator(); exMv == null && it.hasNext();) {
HandlerExceptionResolver resolver = it.next();
exMv = resolver.resolveException(request, response, handler, ex);
}
if (exMv != null) {
if (logger.isDebugEnabled()) {
logger.debug("HandlerExceptionResolver returned ModelAndView [" + exMv + "] for exception");
}
logger.warn("Handler execution resulted in exception - forwarding to resolved error view", ex);
return exMv;
}
else {
throw ex;
}
}
/**
* Determine an error ModelAndView via the registered HandlerExceptionResolvers.
* @param request current portlet request
* @param response current portlet response
* @param handler the executed handler, or null if none chosen at the time of
* the exception (for example, if multipart resolution failed)
* @param ex the exception that got thrown during handler execution
* @return a corresponding ModelAndView to forward to
* @throws Exception if no error ModelAndView found
*/
protected ModelAndView processHandlerException(
ResourceRequest request, ResourceResponse response, Object handler, Exception ex)
throws Exception {
ModelAndView exMv = null;
for (Iterator<HandlerExceptionResolver> it = this.handlerExceptionResolvers.iterator(); exMv == null && it.hasNext();) {
HandlerExceptionResolver resolver = it.next();
exMv = resolver.resolveException(request, response, handler, ex);
}
if (exMv != null) {
if (logger.isDebugEnabled()) {
logger.debug("HandlerExceptionResolver returned ModelAndView [" + exMv + "] for exception");
}
logger.warn("Handler execution resulted in exception - forwarding to resolved error view", ex);
return exMv;
}
else {
throw ex;
}
}
/**
* Trigger afterCompletion callbacks on the mapped HandlerInterceptors.
* Will just invoke afterCompletion for all interceptors whose preHandle
* invocation has successfully completed and returned true.
* @param mappedHandler the mapped HandlerExecutionChain
* @param interceptorIndex index of last interceptor that successfully completed
* @param ex Exception thrown on handler execution, or null if none
* @see HandlerInterceptor#afterRenderCompletion
*/
private void triggerAfterActionCompletion(HandlerExecutionChain mappedHandler, int interceptorIndex,
ActionRequest request, ActionResponse response, Exception ex)
throws Exception {
// Apply afterCompletion methods of registered interceptors.
if (mappedHandler != null) {
HandlerInterceptor[] interceptors = mappedHandler.getInterceptors();
if (interceptors != null) {
for (int i = interceptorIndex; i >= 0; i--) {
HandlerInterceptor interceptor = interceptors[i];
try {
interceptor.afterActionCompletion(request, response, mappedHandler.getHandler(), ex);
}
catch (Throwable ex2) {
logger.error("HandlerInterceptor.afterCompletion threw exception", ex2);
}
}
}
}
}
/**
* Trigger afterCompletion callbacks on the mapped HandlerInterceptors.
* Will just invoke afterCompletion for all interceptors whose preHandle
* invocation has successfully completed and returned true.
* @param mappedHandler the mapped HandlerExecutionChain
* @param interceptorIndex index of last interceptor that successfully completed
* @param ex Exception thrown on handler execution, or null if none
* @see HandlerInterceptor#afterRenderCompletion
*/
private void triggerAfterRenderCompletion(HandlerExecutionChain mappedHandler, int interceptorIndex,
RenderRequest request, RenderResponse response, Exception ex)
throws Exception {
// Apply afterCompletion methods of registered interceptors.
if (mappedHandler != null) {
HandlerInterceptor[] interceptors = mappedHandler.getInterceptors();
if (interceptors != null) {
for (int i = interceptorIndex; i >= 0; i--) {
HandlerInterceptor interceptor = interceptors[i];
try {
interceptor.afterRenderCompletion(request, response, mappedHandler.getHandler(), ex);
}
catch (Throwable ex2) {
logger.error("HandlerInterceptor.afterCompletion threw exception", ex2);
}
}
}
}
}
/**
* Trigger afterCompletion callbacks on the mapped HandlerInterceptors.
* Will just invoke afterCompletion for all interceptors whose preHandle
* invocation has successfully completed and returned true.
* @param mappedHandler the mapped HandlerExecutionChain
* @param interceptorIndex index of last interceptor that successfully completed
* @param ex Exception thrown on handler execution, or null if none
* @see HandlerInterceptor#afterRenderCompletion
*/
private void triggerAfterResourceCompletion(HandlerExecutionChain mappedHandler, int interceptorIndex,
ResourceRequest request, ResourceResponse response, Exception ex)
throws Exception {
// Apply afterCompletion methods of registered interceptors.
if (mappedHandler != null) {
HandlerInterceptor[] interceptors = mappedHandler.getInterceptors();
if (interceptors != null) {
for (int i = interceptorIndex; i >= 0; i--) {
HandlerInterceptor interceptor = interceptors[i];
try {
interceptor.afterResourceCompletion(request, response, mappedHandler.getHandler(), ex);
}
catch (Throwable ex2) {
logger.error("HandlerInterceptor.afterCompletion threw exception", ex2);
}
}
}
}
}
/**
* Trigger afterCompletion callbacks on the mapped HandlerInterceptors.
* Will just invoke afterCompletion for all interceptors whose preHandle
* invocation has successfully completed and returned true.
* @param mappedHandler the mapped HandlerExecutionChain
* @param interceptorIndex index of last interceptor that successfully completed
* @param ex Exception thrown on handler execution, or null if none
* @see HandlerInterceptor#afterRenderCompletion
*/
private void triggerAfterEventCompletion(HandlerExecutionChain mappedHandler, int interceptorIndex,
EventRequest request, EventResponse response, Exception ex)
throws Exception {
// Apply afterCompletion methods of registered interceptors.
if (mappedHandler != null) {
HandlerInterceptor[] interceptors = mappedHandler.getInterceptors();
if (interceptors != null) {
for (int i = interceptorIndex; i >= 0; i--) {
HandlerInterceptor interceptor = interceptors[i];
try {
interceptor.afterEventCompletion(request, response, mappedHandler.getHandler(), ex);
}
catch (Throwable ex2) {
logger.error("HandlerInterceptor.afterCompletion threw exception", ex2);
}
}
}
}
}
}
| DispatcherPortlet passes handler instance into HandlerExceptionResolver for action exception; DispatcherPortlet applies preHandleRender callbacks in case of action exception as well (SPR-6959)
| org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/DispatcherPortlet.java | DispatcherPortlet passes handler instance into HandlerExceptionResolver for action exception; DispatcherPortlet applies preHandleRender callbacks in case of action exception as well (SPR-6959) | <ide><path>rg.springframework.web.portlet/src/main/java/org/springframework/web/portlet/DispatcherPortlet.java
<ide> try {
<ide> ModelAndView mv;
<ide> try {
<del> // Check for forwarded exception from the action phase
<del> PortletSession session = request.getPortletSession(false);
<del> if (session != null) {
<del> if (request.getParameter(ACTION_EXCEPTION_RENDER_PARAMETER) != null) {
<del> Exception ex = (Exception) session.getAttribute(ACTION_EXCEPTION_SESSION_ATTRIBUTE);
<del> if (ex != null) {
<del> logger.debug("Render phase found exception caught during action phase - rethrowing it");
<del> throw ex;
<del> }
<del> }
<del> else {
<del> session.removeAttribute(ACTION_EXCEPTION_SESSION_ATTRIBUTE);
<del> }
<del> }
<del>
<ide> // Determine handler for the current request.
<ide> mappedHandler = getHandler(request, false);
<ide> if (mappedHandler == null || mappedHandler.getHandler() == null) {
<ide> }
<ide> }
<ide>
<add> // Check for forwarded exception from the action phase
<add> PortletSession session = request.getPortletSession(false);
<add> if (session != null) {
<add> if (request.getParameter(ACTION_EXCEPTION_RENDER_PARAMETER) != null) {
<add> Exception ex = (Exception) session.getAttribute(ACTION_EXCEPTION_SESSION_ATTRIBUTE);
<add> if (ex != null) {
<add> logger.debug("Render phase found exception caught during action phase - rethrowing it");
<add> throw ex;
<add> }
<add> }
<add> else {
<add> session.removeAttribute(ACTION_EXCEPTION_SESSION_ATTRIBUTE);
<add> }
<add> }
<add>
<ide> // Actually invoke the handler.
<ide> HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());
<ide> mv = ha.handleRender(request, response, mappedHandler.getHandler());
<ide> try {
<ide> response.setRenderParameter(ACTION_EXCEPTION_RENDER_PARAMETER, ex.toString());
<ide> request.getPortletSession().setAttribute(ACTION_EXCEPTION_SESSION_ATTRIBUTE, ex);
<del> logger.debug("Caught exception during action phase - forwarding to render phase", ex);
<add> logger.debug("Caught exception during event phase - forwarding to render phase", ex);
<ide> }
<ide> catch (IllegalStateException ex2) {
<ide> // Probably sendRedirect called... need to rethrow exception immediately. |
|
Java | apache-2.0 | error: pathspec 'tests/src/test/java/alluxio/client/FreeAndDeleteIntegrationTest.java' did not match any file(s) known to git
| 0e5f377089e6843c245fa20d286cf3ea391e4083 | 1 | ChangerYoung/alluxio,apc999/alluxio,EvilMcJerkface/alluxio,ShailShah/alluxio,maobaolong/alluxio,ShailShah/alluxio,ChangerYoung/alluxio,ShailShah/alluxio,madanadit/alluxio,Reidddddd/mo-alluxio,calvinjia/tachyon,jswudi/alluxio,WilliamZapata/alluxio,Alluxio/alluxio,uronce-cc/alluxio,Alluxio/alluxio,madanadit/alluxio,maobaolong/alluxio,aaudiber/alluxio,maobaolong/alluxio,calvinjia/tachyon,EvilMcJerkface/alluxio,aaudiber/alluxio,wwjiang007/alluxio,Alluxio/alluxio,maboelhassan/alluxio,PasaLab/tachyon,yuluo-ding/alluxio,ChangerYoung/alluxio,madanadit/alluxio,jsimsa/alluxio,EvilMcJerkface/alluxio,yuluo-ding/alluxio,Reidddddd/alluxio,apc999/alluxio,Alluxio/alluxio,Reidddddd/mo-alluxio,PasaLab/tachyon,jsimsa/alluxio,uronce-cc/alluxio,Reidddddd/alluxio,PasaLab/tachyon,apc999/alluxio,WilliamZapata/alluxio,riversand963/alluxio,calvinjia/tachyon,Reidddddd/mo-alluxio,EvilMcJerkface/alluxio,ChangerYoung/alluxio,maobaolong/alluxio,ChangerYoung/alluxio,wwjiang007/alluxio,riversand963/alluxio,jswudi/alluxio,Reidddddd/mo-alluxio,maobaolong/alluxio,riversand963/alluxio,jswudi/alluxio,calvinjia/tachyon,Reidddddd/alluxio,maobaolong/alluxio,maobaolong/alluxio,Reidddddd/alluxio,yuluo-ding/alluxio,EvilMcJerkface/alluxio,madanadit/alluxio,apc999/alluxio,WilliamZapata/alluxio,wwjiang007/alluxio,bf8086/alluxio,maboelhassan/alluxio,ShailShah/alluxio,madanadit/alluxio,maobaolong/alluxio,bf8086/alluxio,uronce-cc/alluxio,maboelhassan/alluxio,EvilMcJerkface/alluxio,riversand963/alluxio,Alluxio/alluxio,WilliamZapata/alluxio,wwjiang007/alluxio,ChangerYoung/alluxio,riversand963/alluxio,calvinjia/tachyon,calvinjia/tachyon,jswudi/alluxio,apc999/alluxio,wwjiang007/alluxio,PasaLab/tachyon,wwjiang007/alluxio,apc999/alluxio,jswudi/alluxio,maboelhassan/alluxio,EvilMcJerkface/alluxio,aaudiber/alluxio,Reidddddd/mo-alluxio,uronce-cc/alluxio,PasaLab/tachyon,jswudi/alluxio,aaudiber/alluxio,bf8086/alluxio,bf8086/alluxio,WilliamZapata/alluxio,wwjiang007/alluxio,wwjiang007/alluxio,maboelhassan/alluxio,PasaLab/tachyon,Alluxio/alluxio,uronce-cc/alluxio,maobaolong/alluxio,maboelhassan/alluxio,aaudiber/alluxio,Alluxio/alluxio,bf8086/alluxio,ShailShah/alluxio,calvinjia/tachyon,PasaLab/tachyon,ShailShah/alluxio,Reidddddd/alluxio,madanadit/alluxio,wwjiang007/alluxio,aaudiber/alluxio,Reidddddd/alluxio,yuluo-ding/alluxio,EvilMcJerkface/alluxio,wwjiang007/alluxio,jsimsa/alluxio,bf8086/alluxio,yuluo-ding/alluxio,aaudiber/alluxio,maboelhassan/alluxio,calvinjia/tachyon,uronce-cc/alluxio,bf8086/alluxio,apc999/alluxio,Reidddddd/alluxio,madanadit/alluxio,WilliamZapata/alluxio,Alluxio/alluxio,jsimsa/alluxio,yuluo-ding/alluxio,jsimsa/alluxio,madanadit/alluxio,maobaolong/alluxio,riversand963/alluxio,jsimsa/alluxio,Reidddddd/mo-alluxio,Alluxio/alluxio,Alluxio/alluxio,bf8086/alluxio | /*
* The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
* (the “License”). You may not use this work except in compliance with the License, which is
* available at www.apache.org/licenses/LICENSE-2.0
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied, as more fully set forth in the License.
*
* See the NOTICE file distributed with this work for information regarding copyright ownership.
*/
package alluxio.client;
import alluxio.AlluxioURI;
import alluxio.Configuration;
import alluxio.Constants;
import alluxio.LocalAlluxioClusterResource;
import alluxio.client.file.FileOutStream;
import alluxio.client.file.FileSystem;
import alluxio.client.file.URIStatus;
import alluxio.client.file.options.CreateFileOptions;
import alluxio.exception.FileDoesNotExistException;
import alluxio.heartbeat.HeartbeatContext;
import alluxio.heartbeat.HeartbeatScheduler;
import alluxio.master.PrivateAccess;
import alluxio.master.block.BlockMaster;
import alluxio.master.file.meta.PersistenceState;
import alluxio.util.io.PathUtils;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import java.util.concurrent.TimeUnit;
/**
* Integration tests for file free and delete with under storage persisted.
*
*/
public final class FreeAndDeleteIntegrationTest {
private static final int WORKER_CAPACITY_BYTES = 200 * Constants.MB;
private static final int USER_QUOTA_UNIT_BYTES = 1000;
/** The exception expected to be thrown. */
@Rule
public ExpectedException mThrown = ExpectedException.none();
@Rule
public LocalAlluxioClusterResource mLocalAlluxioClusterResource = new LocalAlluxioClusterResource(
WORKER_CAPACITY_BYTES, 100 * Constants.MB,
Constants.USER_FILE_BUFFER_BYTES, Integer.toString(USER_QUOTA_UNIT_BYTES));
private FileSystem mFileSystem = null;
private CreateFileOptions mWriteBoth;
@Before
public final void before() throws Exception {
mFileSystem = mLocalAlluxioClusterResource.get().getClient();
Configuration workerConfiguration = mLocalAlluxioClusterResource.get().getWorkerConf();
mWriteBoth = StreamOptionUtils.getCreateFileOptionsCacheThrough(workerConfiguration);
}
@BeforeClass
public static void beforeClass() {
HeartbeatContext.setTimerClass(HeartbeatContext.WORKER_BLOCK_SYNC,
HeartbeatContext.SCHEDULED_TIMER_CLASS);
HeartbeatContext.setTimerClass(HeartbeatContext.MASTER_LOST_FILES_DETECTION,
HeartbeatContext.SCHEDULED_TIMER_CLASS);
}
@AfterClass
public static void afterClass() {
HeartbeatContext.setTimerClass(HeartbeatContext.WORKER_BLOCK_SYNC,
HeartbeatContext.SLEEPING_TIMER_CLASS);
HeartbeatContext.setTimerClass(HeartbeatContext.MASTER_LOST_FILES_DETECTION,
HeartbeatContext.SLEEPING_TIMER_CLASS);
}
@Test
public void freeAndDeleteIntegrationTest() throws Exception {
AlluxioURI filePath = new AlluxioURI(PathUtils.uniqPath());
FileOutStream os = mFileSystem.createFile(filePath, mWriteBoth);
os.write((byte) 0);
os.write((byte) 1);
os.close();
URIStatus status = mFileSystem.getStatus(filePath);
Assert.assertEquals(PersistenceState.PERSISTED.toString(), status.getPersistenceState());
mFileSystem.free(filePath);
// Execute the blocks free, which needs two heartbeats
Assert.assertTrue(HeartbeatScheduler.await(HeartbeatContext.WORKER_BLOCK_SYNC, 5,
TimeUnit.SECONDS));
HeartbeatScheduler.schedule(HeartbeatContext.WORKER_BLOCK_SYNC);
Assert.assertTrue(HeartbeatScheduler.await(HeartbeatContext.WORKER_BLOCK_SYNC, 5,
TimeUnit.SECONDS));
HeartbeatScheduler.schedule(HeartbeatContext.WORKER_BLOCK_SYNC);
Assert.assertTrue(HeartbeatScheduler.await(HeartbeatContext.WORKER_BLOCK_SYNC, 5,
TimeUnit.SECONDS));
status = mFileSystem.getStatus(filePath);
Assert.assertEquals(PersistenceState.PERSISTED.toString(), status.getPersistenceState());
// Block metadata is still present after block freed.
Assert.assertEquals(1, status.getBlockIds().size());
mFileSystem.delete(filePath);
// File is immediately gone after delete.
mThrown.expect(FileDoesNotExistException.class);
mFileSystem.getStatus(filePath);
Assert.assertTrue(HeartbeatScheduler.await(HeartbeatContext.MASTER_LOST_FILES_DETECTION, 5,
TimeUnit.SECONDS));
HeartbeatScheduler.schedule(HeartbeatContext.MASTER_LOST_FILES_DETECTION);
Assert.assertTrue(HeartbeatScheduler.await(HeartbeatContext.MASTER_LOST_FILES_DETECTION, 5,
TimeUnit.SECONDS));
// Verify the blocks are not in mLostBlocks.
BlockMaster bm = PrivateAccess.getBlockMaster(mLocalAlluxioClusterResource.get().getMaster()
.getInternalMaster());
Assert.assertEquals(0, bm.getLostBlocks().size());
}
}
| tests/src/test/java/alluxio/client/FreeAndDeleteIntegrationTest.java | [ALLUXIO-1718] Add integration test for persisted file free and then
delete, check block metadata.
| tests/src/test/java/alluxio/client/FreeAndDeleteIntegrationTest.java | [ALLUXIO-1718] Add integration test for persisted file free and then delete, check block metadata. | <ide><path>ests/src/test/java/alluxio/client/FreeAndDeleteIntegrationTest.java
<add>/*
<add> * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
<add> * (the “License”). You may not use this work except in compliance with the License, which is
<add> * available at www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
<add> * either express or implied, as more fully set forth in the License.
<add> *
<add> * See the NOTICE file distributed with this work for information regarding copyright ownership.
<add> */
<add>
<add>package alluxio.client;
<add>
<add>import alluxio.AlluxioURI;
<add>import alluxio.Configuration;
<add>import alluxio.Constants;
<add>import alluxio.LocalAlluxioClusterResource;
<add>import alluxio.client.file.FileOutStream;
<add>import alluxio.client.file.FileSystem;
<add>import alluxio.client.file.URIStatus;
<add>import alluxio.client.file.options.CreateFileOptions;
<add>import alluxio.exception.FileDoesNotExistException;
<add>import alluxio.heartbeat.HeartbeatContext;
<add>import alluxio.heartbeat.HeartbeatScheduler;
<add>import alluxio.master.PrivateAccess;
<add>import alluxio.master.block.BlockMaster;
<add>import alluxio.master.file.meta.PersistenceState;
<add>import alluxio.util.io.PathUtils;
<add>
<add>import org.junit.AfterClass;
<add>import org.junit.Assert;
<add>import org.junit.Before;
<add>import org.junit.BeforeClass;
<add>import org.junit.Rule;
<add>import org.junit.Test;
<add>import org.junit.rules.ExpectedException;
<add>
<add>import java.util.concurrent.TimeUnit;
<add>
<add>/**
<add> * Integration tests for file free and delete with under storage persisted.
<add> *
<add> */
<add>public final class FreeAndDeleteIntegrationTest {
<add> private static final int WORKER_CAPACITY_BYTES = 200 * Constants.MB;
<add> private static final int USER_QUOTA_UNIT_BYTES = 1000;
<add>
<add> /** The exception expected to be thrown. */
<add> @Rule
<add> public ExpectedException mThrown = ExpectedException.none();
<add>
<add> @Rule
<add> public LocalAlluxioClusterResource mLocalAlluxioClusterResource = new LocalAlluxioClusterResource(
<add> WORKER_CAPACITY_BYTES, 100 * Constants.MB,
<add> Constants.USER_FILE_BUFFER_BYTES, Integer.toString(USER_QUOTA_UNIT_BYTES));
<add> private FileSystem mFileSystem = null;
<add> private CreateFileOptions mWriteBoth;
<add>
<add> @Before
<add> public final void before() throws Exception {
<add> mFileSystem = mLocalAlluxioClusterResource.get().getClient();
<add> Configuration workerConfiguration = mLocalAlluxioClusterResource.get().getWorkerConf();
<add> mWriteBoth = StreamOptionUtils.getCreateFileOptionsCacheThrough(workerConfiguration);
<add> }
<add>
<add> @BeforeClass
<add> public static void beforeClass() {
<add> HeartbeatContext.setTimerClass(HeartbeatContext.WORKER_BLOCK_SYNC,
<add> HeartbeatContext.SCHEDULED_TIMER_CLASS);
<add> HeartbeatContext.setTimerClass(HeartbeatContext.MASTER_LOST_FILES_DETECTION,
<add> HeartbeatContext.SCHEDULED_TIMER_CLASS);
<add> }
<add>
<add> @AfterClass
<add> public static void afterClass() {
<add> HeartbeatContext.setTimerClass(HeartbeatContext.WORKER_BLOCK_SYNC,
<add> HeartbeatContext.SLEEPING_TIMER_CLASS);
<add> HeartbeatContext.setTimerClass(HeartbeatContext.MASTER_LOST_FILES_DETECTION,
<add> HeartbeatContext.SLEEPING_TIMER_CLASS);
<add> }
<add>
<add> @Test
<add> public void freeAndDeleteIntegrationTest() throws Exception {
<add> AlluxioURI filePath = new AlluxioURI(PathUtils.uniqPath());
<add> FileOutStream os = mFileSystem.createFile(filePath, mWriteBoth);
<add> os.write((byte) 0);
<add> os.write((byte) 1);
<add> os.close();
<add>
<add> URIStatus status = mFileSystem.getStatus(filePath);
<add> Assert.assertEquals(PersistenceState.PERSISTED.toString(), status.getPersistenceState());
<add>
<add> mFileSystem.free(filePath);
<add> // Execute the blocks free, which needs two heartbeats
<add> Assert.assertTrue(HeartbeatScheduler.await(HeartbeatContext.WORKER_BLOCK_SYNC, 5,
<add> TimeUnit.SECONDS));
<add> HeartbeatScheduler.schedule(HeartbeatContext.WORKER_BLOCK_SYNC);
<add> Assert.assertTrue(HeartbeatScheduler.await(HeartbeatContext.WORKER_BLOCK_SYNC, 5,
<add> TimeUnit.SECONDS));
<add> HeartbeatScheduler.schedule(HeartbeatContext.WORKER_BLOCK_SYNC);
<add> Assert.assertTrue(HeartbeatScheduler.await(HeartbeatContext.WORKER_BLOCK_SYNC, 5,
<add> TimeUnit.SECONDS));
<add>
<add> status = mFileSystem.getStatus(filePath);
<add> Assert.assertEquals(PersistenceState.PERSISTED.toString(), status.getPersistenceState());
<add> // Block metadata is still present after block freed.
<add> Assert.assertEquals(1, status.getBlockIds().size());
<add>
<add> mFileSystem.delete(filePath);
<add> // File is immediately gone after delete.
<add> mThrown.expect(FileDoesNotExistException.class);
<add> mFileSystem.getStatus(filePath);
<add>
<add> Assert.assertTrue(HeartbeatScheduler.await(HeartbeatContext.MASTER_LOST_FILES_DETECTION, 5,
<add> TimeUnit.SECONDS));
<add> HeartbeatScheduler.schedule(HeartbeatContext.MASTER_LOST_FILES_DETECTION);
<add> Assert.assertTrue(HeartbeatScheduler.await(HeartbeatContext.MASTER_LOST_FILES_DETECTION, 5,
<add> TimeUnit.SECONDS));
<add>
<add> // Verify the blocks are not in mLostBlocks.
<add> BlockMaster bm = PrivateAccess.getBlockMaster(mLocalAlluxioClusterResource.get().getMaster()
<add> .getInternalMaster());
<add> Assert.assertEquals(0, bm.getLostBlocks().size());
<add> }
<add>} |
|
Java | apache-2.0 | error: pathspec 'core/cas-server-core-configuration-api/src/test/java/org/apereo/cas/configuration/CommaSeparatedStringToThrowablesConverterTests.java' did not match any file(s) known to git
| b5b587e92db76fea8f6e898986318be50e8274a4 | 1 | fogbeam/cas_mirror,apereo/cas,rkorn86/cas,pdrados/cas,apereo/cas,apereo/cas,leleuj/cas,pdrados/cas,Jasig/cas,leleuj/cas,fogbeam/cas_mirror,apereo/cas,philliprower/cas,fogbeam/cas_mirror,rkorn86/cas,pdrados/cas,pdrados/cas,philliprower/cas,philliprower/cas,philliprower/cas,Jasig/cas,philliprower/cas,rkorn86/cas,philliprower/cas,pdrados/cas,apereo/cas,fogbeam/cas_mirror,leleuj/cas,rkorn86/cas,fogbeam/cas_mirror,fogbeam/cas_mirror,Jasig/cas,Jasig/cas,leleuj/cas,apereo/cas,apereo/cas,philliprower/cas,leleuj/cas,leleuj/cas,pdrados/cas | package org.apereo.cas.configuration;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
import static org.junit.Assert.*;
/**
* This is {@link CommaSeparatedStringToThrowablesConverterTests}.
*
* @author Misagh Moayyed
* @since 5.3.0
*/
@RunWith(SpringRunner.class)
public class CommaSeparatedStringToThrowablesConverterTests {
@Test
public void verifyConverters() {
final CommaSeparatedStringToThrowablesConverter c = new CommaSeparatedStringToThrowablesConverter();
final List list = c.convert(Exception.class.getName() + "," + RuntimeException.class.getName());
assertEquals(2, list.size());
}
@Test
public void verifyConverter() {
final CommaSeparatedStringToThrowablesConverter c = new CommaSeparatedStringToThrowablesConverter();
final List list = c.convert(Exception.class.getName());
assertEquals(1, list.size());
}
}
| core/cas-server-core-configuration-api/src/test/java/org/apereo/cas/configuration/CommaSeparatedStringToThrowablesConverterTests.java | add test case
| core/cas-server-core-configuration-api/src/test/java/org/apereo/cas/configuration/CommaSeparatedStringToThrowablesConverterTests.java | add test case | <ide><path>ore/cas-server-core-configuration-api/src/test/java/org/apereo/cas/configuration/CommaSeparatedStringToThrowablesConverterTests.java
<add>package org.apereo.cas.configuration;
<add>
<add>import org.junit.Test;
<add>import org.junit.runner.RunWith;
<add>import org.springframework.test.context.junit4.SpringRunner;
<add>
<add>import java.util.List;
<add>
<add>import static org.junit.Assert.*;
<add>
<add>/**
<add> * This is {@link CommaSeparatedStringToThrowablesConverterTests}.
<add> *
<add> * @author Misagh Moayyed
<add> * @since 5.3.0
<add> */
<add>@RunWith(SpringRunner.class)
<add>public class CommaSeparatedStringToThrowablesConverterTests {
<add>
<add> @Test
<add> public void verifyConverters() {
<add> final CommaSeparatedStringToThrowablesConverter c = new CommaSeparatedStringToThrowablesConverter();
<add> final List list = c.convert(Exception.class.getName() + "," + RuntimeException.class.getName());
<add> assertEquals(2, list.size());
<add> }
<add>
<add> @Test
<add> public void verifyConverter() {
<add> final CommaSeparatedStringToThrowablesConverter c = new CommaSeparatedStringToThrowablesConverter();
<add> final List list = c.convert(Exception.class.getName());
<add> assertEquals(1, list.size());
<add> }
<add>} |
|
Java | apache-2.0 | 622c888566c2185371db89384bbf26bf639e7d76 | 0 | hgl888/realm-java,angcyo/realm-java,realm/realm-java,xxccll/realm-java,Ryan800/realm-java,angcyo/realm-java,ShikaSD/realm-java,nartex/realm-java,bunnyblue/realm-java,thdtjsdn/realm-java,teddywest32/realm-java,ppamorim/realm-java,awesome-niu/realm-java,mio4kon/realm-java,androiddream/realm-java,hgl888/realm-java,msdgwzhy6/realm-java,qingsong-xu/realm-java,ShikaSD/realm-java,GavinThePacMan/realm-java,FabianTerhorst/realm-java,arunlodhi/realm-java,thdtjsdn/realm-java,angcyo/realm-java,DuongNTdev/realm-java,ppamorim/realm-java,arunlodhi/realm-java,GeorgeMe/realm-java,myroid/realm-java,xxccll/realm-java,DuongNTdev/realm-java,mio4kon/realm-java,dantman/realm-java,teddywest32/realm-java,GavinThePacMan/realm-java,alwakelab/realm-java,santoshmehta82/realm-java,ysnows/realm-java,ppamorim/realm-java,hgl888/realm-java,GavinThePacMan/realm-java,JetXing/realm-java,cpinan/realm-java,GavinThePacMan/realm-java,msdgwzhy6/realm-java,GeorgeMe/realm-java,cpinan/realm-java,Rowandjj/realm-java,Rowandjj/realm-java,kidaa/realm-java,JetXing/realm-java,alwakelab/realm-java,realm/realm-java,horie1024/realm-java,myroid/realm-java,davicaetano/realm-java,androiddream/realm-java,davicaetano/realm-java,realm/realm-java,GeorgeMe/realm-java,awesome-niu/realm-java,angcyo/realm-java,DuongNTdev/realm-java,FabianTerhorst/realm-java,ShikaSD/realm-java,mobileperfman/realm-java,qingsong-xu/realm-java,ShikaSD/realm-java,thdtjsdn/realm-java,mobileperfman/realm-java,bunnyblue/realm-java,avipars/realm-java,realm/realm-java,teddywest32/realm-java,cpinan/realm-java,ShikaSD/realm-java,awesome-niu/realm-java,msdgwzhy6/realm-java,realm/realm-java,ysnows/realm-java,alwakelab/realm-java,avipars/realm-java,JetXing/realm-java,GeorgeMe/realm-java,horie1024/realm-java,santoshmehta82/realm-java,ysnows/realm-java,Ryan800/realm-java,santoshmehta82/realm-java,Rowandjj/realm-java,mio4kon/realm-java,hgl888/realm-java,mobileperfman/realm-java,kidaa/realm-java,nartex/realm-java,kidaa/realm-java,dantman/realm-java,realm/realm-java,nartex/realm-java,qingsong-xu/realm-java,FabianTerhorst/realm-java,yuuki1224/realm-java,ppamorim/realm-java,msdgwzhy6/realm-java,Ryan800/realm-java,xxccll/realm-java,teddywest32/realm-java,awesome-niu/realm-java,arunlodhi/realm-java,avipars/realm-java,thdtjsdn/realm-java,davicaetano/realm-java,myroid/realm-java,yuuki1224/realm-java,androiddream/realm-java,bunnyblue/realm-java,teddywest32/realm-java,horie1024/realm-java,realm/realm-java,dantman/realm-java,yuuki1224/realm-java,DuongNTdev/realm-java | package com.tightdb.lib;
import static org.testng.AssertJUnit.*;
import org.testng.annotations.Test;
import com.tightdb.example.generated.Employee;
import com.tightdb.example.generated.EmployeeTable;
import com.tightdb.example.generated.PhoneTable;
public class MixedSubtableTest extends AbstractTableTest {
@Test
public void shouldStoreSubtableInMixedTypeColumn() {
Employee employee = employees.at(0);
PhoneTable phones = employee.extra.createSubtable(PhoneTable.class);
phones.add("mobile", "123");
assertEquals(1, phones.size());
PhoneTable phones2 = employee.extra.getSubtable(PhoneTable.class);
assertEquals(1, phones2.size());
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void shouldFailOnOnWrongSubtableRetrievalFromMixedTypeColumn() {
Employee employee = employees.at(0);
PhoneTable phones = employee.extra.createSubtable(PhoneTable.class);
phones.add("mobile", "123");
assertEquals(1, phones.size());
// should fail - since we try to get the wrong subtable class
employee.extra.getSubtable(EmployeeTable.class);
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void shouldFailOnOnSubtableRetrtievalFromIncorrectType() {
Employee employee = employees.at(0);
employee.extra.set(123);
// should fail
employee.extra.getSubtable(PhoneTable.class);
}
}
| src/test/java/com/tightdb/lib/MixedSubtableTest.java | package com.tightdb.lib;
import static org.testng.AssertJUnit.*;
import org.testng.annotations.Test;
import com.tightdb.example.generated.Employee;
import com.tightdb.example.generated.EmployeeTable;
import com.tightdb.example.generated.PeopleTable;
import com.tightdb.example.generated.PhoneTable;
public class MixedSubtableTest extends AbstractTableTest {
@Test
public void shouldStoreSubtableInMixedTypeColumn() {
Employee employee = employees.at(0);
PhoneTable phones = employee.extra.createSubtable(PhoneTable.class);
phones.add("mobile", "123");
assertEquals(1, phones.size());
PhoneTable phones2 = employee.extra.getSubtable(PhoneTable.class);
assertEquals(1, phones2.size());
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void shouldFailOnOnWrongSubtableRetrievalFromMixedTypeColumn() {
Employee employee = employees.at(0);
PhoneTable phones = employee.extra.createSubtable(PhoneTable.class);
phones.add("mobile", "123");
assertEquals(1, phones.size());
// should fail - since we try to get the wrong subtable class
employee.extra.getSubtable(EmployeeTable.class);
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void shouldFailOnOnSubtableRetrtievalFromIncorrectType() {
Employee employee = employees.at(0);
employee.extra.set(123);
// should fail
employee.extra.getSubtable(PhoneTable.class);
}
}
| Removed unused import. | src/test/java/com/tightdb/lib/MixedSubtableTest.java | Removed unused import. | <ide><path>rc/test/java/com/tightdb/lib/MixedSubtableTest.java
<ide>
<ide> import com.tightdb.example.generated.Employee;
<ide> import com.tightdb.example.generated.EmployeeTable;
<del>import com.tightdb.example.generated.PeopleTable;
<ide> import com.tightdb.example.generated.PhoneTable;
<ide>
<ide> public class MixedSubtableTest extends AbstractTableTest { |
|
Java | agpl-3.0 | error: pathspec 'splice_machine_test/src/test/java/com/splicemachine/derby/impl/sql/execute/tester/LazyTimestampDataValueDescriptorTest.java' did not match any file(s) known to git
| 167ec449a7607049661c10433323661108e4b82d | 1 | CompilerWorks/spliceengine,splicemachine/spliceengine,splicemachine/spliceengine,CompilerWorks/spliceengine,CompilerWorks/spliceengine,CompilerWorks/spliceengine,splicemachine/spliceengine,CompilerWorks/spliceengine,splicemachine/spliceengine,splicemachine/spliceengine,CompilerWorks/spliceengine,splicemachine/spliceengine,splicemachine/spliceengine | package com.splicemachine.derby.impl.sql.execute.tester;
import org.apache.derby.iapi.types.SQLDouble;
import org.apache.derby.iapi.types.SQLTimestamp;
import org.joda.time.DateTime;
import org.junit.Assert;
import org.junit.Test;
import com.splicemachine.derby.impl.sql.execute.LazyNumberDataValueDescriptor;
import com.splicemachine.derby.impl.sql.execute.LazyTimestampDataValueDescriptor;
/**
* TODO: Should be more tests here for LazyTimestampDataValueDescriptor. Adding this test for verification of fix for DB-2863.
*
* @author Jeff Cunningham
* Date: 2/13/15
*/
public class LazyTimestampDataValueDescriptorTest {
@Test
public void testGetSeconds() throws Exception {
int expected = 32;
LazyTimestampDataValueDescriptor timestamp =
new LazyTimestampDataValueDescriptor(new SQLTimestamp(new DateTime(2012, 2, 14, 12, 12, expected, 0)));
double actual = timestamp.getSeconds(new LazyNumberDataValueDescriptor(new SQLDouble(0.0))).getDouble();
Assert.assertEquals(expected, actual, 0.0);
}
}
| splice_machine_test/src/test/java/com/splicemachine/derby/impl/sql/execute/tester/LazyTimestampDataValueDescriptorTest.java | DB-2863: second(timestamp) function fails.
The problem originated when we added the Lazy*DataValueDescriptor classes.
SQLTimestamp.getSeconds(NumberDataValue source) enforces that the 'source'
is of type SQLDouble. The 'source' type is now LazyTimestampDataValueDescriptor.
The fix was to change the enforcement so that the NumberDataValue checks that
it contains a type double and all went fine. I ran the ITs on 1.0.x and all passed.
Added a simple IT, LazyTimestampDataValueDescriptorTest.
| splice_machine_test/src/test/java/com/splicemachine/derby/impl/sql/execute/tester/LazyTimestampDataValueDescriptorTest.java | DB-2863: second(timestamp) function fails. | <ide><path>plice_machine_test/src/test/java/com/splicemachine/derby/impl/sql/execute/tester/LazyTimestampDataValueDescriptorTest.java
<add>package com.splicemachine.derby.impl.sql.execute.tester;
<add>
<add>import org.apache.derby.iapi.types.SQLDouble;
<add>import org.apache.derby.iapi.types.SQLTimestamp;
<add>import org.joda.time.DateTime;
<add>import org.junit.Assert;
<add>import org.junit.Test;
<add>
<add>import com.splicemachine.derby.impl.sql.execute.LazyNumberDataValueDescriptor;
<add>import com.splicemachine.derby.impl.sql.execute.LazyTimestampDataValueDescriptor;
<add>
<add>/**
<add> * TODO: Should be more tests here for LazyTimestampDataValueDescriptor. Adding this test for verification of fix for DB-2863.
<add> *
<add> * @author Jeff Cunningham
<add> * Date: 2/13/15
<add> */
<add>public class LazyTimestampDataValueDescriptorTest {
<add>
<add> @Test
<add> public void testGetSeconds() throws Exception {
<add> int expected = 32;
<add> LazyTimestampDataValueDescriptor timestamp =
<add> new LazyTimestampDataValueDescriptor(new SQLTimestamp(new DateTime(2012, 2, 14, 12, 12, expected, 0)));
<add> double actual = timestamp.getSeconds(new LazyNumberDataValueDescriptor(new SQLDouble(0.0))).getDouble();
<add> Assert.assertEquals(expected, actual, 0.0);
<add> }
<add>} |
|
JavaScript | bsd-3-clause | b1e99b701e2f0a320c88539465cfcd0d0bb92860 | 0 | expandjs/expandjs,rl189020/expandjs,rl189020/expandjs,expandjs/expandjs,Klaudit/expandjs,Klaudit/expandjs | /*jslint browser: true, devel: true, node: true, ass: true, nomen: true, unparam: true, indent: 4 */
/**
* @license
* Copyright (c) 2015 The ExpandJS authors. All rights reserved.
* This code may only be used under the BSD style license found at https://expandjs.github.io/LICENSE.txt
* The complete set of authors may be found at https://expandjs.github.io/AUTHORS.txt
* The complete set of contributors may be found at https://expandjs.github.io/CONTRIBUTORS.txt
*/
(function () {
"use strict";
// Vars
var assign = require('./object/assign'),
browserify = require('./browser/browserify');
/*********************************************************************/
// Exporting
module.exports = assign({},
require('./array'),
require('./assert'),
require('./browser'),
require('./caster'),
require('./collection'),
require('./constructors'),
require('./dom'),
require('./error'),
require('./function'),
require('./number'),
require('./object'),
require('./operator'),
require('./string'),
require('./tester'));
/*********************************************************************/
// Browserify
browserify(require('lodash'), '_');
}()); | lib/index.js | /*jslint browser: true, devel: true, node: true, ass: true, nomen: true, unparam: true, indent: 4 */
/**
* @license
* Copyright (c) 2015 The ExpandJS authors. All rights reserved.
* This code may only be used under the BSD style license found at https://expandjs.github.io/LICENSE.txt
* The complete set of authors may be found at https://expandjs.github.io/AUTHORS.txt
* The complete set of contributors may be found at https://expandjs.github.io/CONTRIBUTORS.txt
*/
(function () {
"use strict";
// Exporting
module.exports = require('./object/assign')({},
require('./array'),
require('./assert'),
require('./browser'),
require('./caster'),
require('./collection'),
require('./constructors'),
require('./dom'),
require('./error'),
require('./function'),
require('./number'),
require('./object'),
require('./operator'),
require('./string'),
require('./tester'));
}()); | First release
| lib/index.js | First release | <ide><path>ib/index.js
<ide> (function () {
<ide> "use strict";
<ide>
<add> // Vars
<add> var assign = require('./object/assign'),
<add> browserify = require('./browser/browserify');
<add>
<add> /*********************************************************************/
<add>
<ide> // Exporting
<del> module.exports = require('./object/assign')({},
<add> module.exports = assign({},
<ide> require('./array'),
<ide> require('./assert'),
<ide> require('./browser'),
<ide> require('./string'),
<ide> require('./tester'));
<ide>
<add> /*********************************************************************/
<add>
<add> // Browserify
<add> browserify(require('lodash'), '_');
<add>
<ide> }()); |
|
Java | apache-2.0 | 0b089ed2653d8e9229a8c57cf411e5a5a2611403 | 0 | kdwink/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,gnuhub/intellij-community,petteyg/intellij-community,adedayo/intellij-community,ivan-fedorov/intellij-community,apixandru/intellij-community,nicolargo/intellij-community,signed/intellij-community,kdwink/intellij-community,gnuhub/intellij-community,gnuhub/intellij-community,asedunov/intellij-community,signed/intellij-community,slisson/intellij-community,xfournet/intellij-community,tmpgit/intellij-community,alphafoobar/intellij-community,wreckJ/intellij-community,kool79/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,TangHao1987/intellij-community,blademainer/intellij-community,supersven/intellij-community,asedunov/intellij-community,pwoodworth/intellij-community,Lekanich/intellij-community,nicolargo/intellij-community,lucafavatella/intellij-community,gnuhub/intellij-community,retomerz/intellij-community,MER-GROUP/intellij-community,Distrotech/intellij-community,MichaelNedzelsky/intellij-community,akosyakov/intellij-community,samthor/intellij-community,kool79/intellij-community,pwoodworth/intellij-community,nicolargo/intellij-community,adedayo/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,lucafavatella/intellij-community,jagguli/intellij-community,vvv1559/intellij-community,muntasirsyed/intellij-community,Distrotech/intellij-community,fnouama/intellij-community,signed/intellij-community,alphafoobar/intellij-community,jagguli/intellij-community,ryano144/intellij-community,ryano144/intellij-community,salguarnieri/intellij-community,MichaelNedzelsky/intellij-community,slisson/intellij-community,vladmm/intellij-community,hurricup/intellij-community,fengbaicanhe/intellij-community,SerCeMan/intellij-community,ibinti/intellij-community,slisson/intellij-community,ahb0327/intellij-community,MER-GROUP/intellij-community,idea4bsd/idea4bsd,Lekanich/intellij-community,ThiagoGarciaAlves/intellij-community,holmes/intellij-community,hurricup/intellij-community,semonte/intellij-community,TangHao1987/intellij-community,alphafoobar/intellij-community,akosyakov/intellij-community,xfournet/intellij-community,hurricup/intellij-community,MichaelNedzelsky/intellij-community,diorcety/intellij-community,fitermay/intellij-community,pwoodworth/intellij-community,akosyakov/intellij-community,akosyakov/intellij-community,apixandru/intellij-community,allotria/intellij-community,TangHao1987/intellij-community,vladmm/intellij-community,MichaelNedzelsky/intellij-community,FHannes/intellij-community,kool79/intellij-community,holmes/intellij-community,pwoodworth/intellij-community,salguarnieri/intellij-community,dslomov/intellij-community,petteyg/intellij-community,signed/intellij-community,caot/intellij-community,ThiagoGarciaAlves/intellij-community,vladmm/intellij-community,ryano144/intellij-community,jagguli/intellij-community,orekyuu/intellij-community,da1z/intellij-community,amith01994/intellij-community,apixandru/intellij-community,MER-GROUP/intellij-community,gnuhub/intellij-community,pwoodworth/intellij-community,michaelgallacher/intellij-community,Lekanich/intellij-community,wreckJ/intellij-community,fengbaicanhe/intellij-community,alphafoobar/intellij-community,kdwink/intellij-community,ThiagoGarciaAlves/intellij-community,ivan-fedorov/intellij-community,mglukhikh/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,gnuhub/intellij-community,adedayo/intellij-community,signed/intellij-community,ahb0327/intellij-community,orekyuu/intellij-community,Lekanich/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,ahb0327/intellij-community,caot/intellij-community,ftomassetti/intellij-community,fnouama/intellij-community,Distrotech/intellij-community,vvv1559/intellij-community,diorcety/intellij-community,Distrotech/intellij-community,dslomov/intellij-community,caot/intellij-community,semonte/intellij-community,fitermay/intellij-community,ryano144/intellij-community,amith01994/intellij-community,holmes/intellij-community,jagguli/intellij-community,supersven/intellij-community,MER-GROUP/intellij-community,clumsy/intellij-community,samthor/intellij-community,clumsy/intellij-community,dslomov/intellij-community,da1z/intellij-community,vvv1559/intellij-community,petteyg/intellij-community,alphafoobar/intellij-community,tmpgit/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,nicolargo/intellij-community,samthor/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,wreckJ/intellij-community,samthor/intellij-community,retomerz/intellij-community,holmes/intellij-community,robovm/robovm-studio,semonte/intellij-community,jagguli/intellij-community,robovm/robovm-studio,dslomov/intellij-community,Lekanich/intellij-community,lucafavatella/intellij-community,petteyg/intellij-community,ahb0327/intellij-community,kool79/intellij-community,MER-GROUP/intellij-community,slisson/intellij-community,kool79/intellij-community,ivan-fedorov/intellij-community,suncycheng/intellij-community,amith01994/intellij-community,slisson/intellij-community,caot/intellij-community,Lekanich/intellij-community,clumsy/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,ahb0327/intellij-community,diorcety/intellij-community,samthor/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,fengbaicanhe/intellij-community,fitermay/intellij-community,blademainer/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,da1z/intellij-community,orekyuu/intellij-community,blademainer/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,asedunov/intellij-community,blademainer/intellij-community,dslomov/intellij-community,jagguli/intellij-community,samthor/intellij-community,vladmm/intellij-community,apixandru/intellij-community,petteyg/intellij-community,blademainer/intellij-community,adedayo/intellij-community,kdwink/intellij-community,MER-GROUP/intellij-community,ol-loginov/intellij-community,michaelgallacher/intellij-community,izonder/intellij-community,petteyg/intellij-community,ibinti/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,slisson/intellij-community,asedunov/intellij-community,petteyg/intellij-community,muntasirsyed/intellij-community,semonte/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,caot/intellij-community,ivan-fedorov/intellij-community,ryano144/intellij-community,holmes/intellij-community,idea4bsd/idea4bsd,muntasirsyed/intellij-community,MER-GROUP/intellij-community,muntasirsyed/intellij-community,retomerz/intellij-community,kdwink/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,adedayo/intellij-community,michaelgallacher/intellij-community,wreckJ/intellij-community,retomerz/intellij-community,youdonghai/intellij-community,fnouama/intellij-community,orekyuu/intellij-community,Distrotech/intellij-community,izonder/intellij-community,da1z/intellij-community,allotria/intellij-community,fitermay/intellij-community,ibinti/intellij-community,ol-loginov/intellij-community,idea4bsd/idea4bsd,TangHao1987/intellij-community,mglukhikh/intellij-community,robovm/robovm-studio,petteyg/intellij-community,asedunov/intellij-community,jagguli/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,FHannes/intellij-community,tmpgit/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,Lekanich/intellij-community,slisson/intellij-community,youdonghai/intellij-community,pwoodworth/intellij-community,fnouama/intellij-community,supersven/intellij-community,idea4bsd/idea4bsd,jagguli/intellij-community,lucafavatella/intellij-community,fengbaicanhe/intellij-community,retomerz/intellij-community,robovm/robovm-studio,fnouama/intellij-community,ThiagoGarciaAlves/intellij-community,amith01994/intellij-community,muntasirsyed/intellij-community,Lekanich/intellij-community,kool79/intellij-community,fitermay/intellij-community,xfournet/intellij-community,supersven/intellij-community,fitermay/intellij-community,wreckJ/intellij-community,ibinti/intellij-community,ftomassetti/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,clumsy/intellij-community,SerCeMan/intellij-community,fitermay/intellij-community,vladmm/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,fengbaicanhe/intellij-community,Lekanich/intellij-community,pwoodworth/intellij-community,signed/intellij-community,clumsy/intellij-community,pwoodworth/intellij-community,tmpgit/intellij-community,retomerz/intellij-community,retomerz/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,allotria/intellij-community,xfournet/intellij-community,MichaelNedzelsky/intellij-community,fengbaicanhe/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,Distrotech/intellij-community,holmes/intellij-community,ftomassetti/intellij-community,clumsy/intellij-community,SerCeMan/intellij-community,kdwink/intellij-community,holmes/intellij-community,signed/intellij-community,allotria/intellij-community,salguarnieri/intellij-community,blademainer/intellij-community,vvv1559/intellij-community,akosyakov/intellij-community,ryano144/intellij-community,clumsy/intellij-community,xfournet/intellij-community,SerCeMan/intellij-community,kdwink/intellij-community,pwoodworth/intellij-community,akosyakov/intellij-community,pwoodworth/intellij-community,wreckJ/intellij-community,da1z/intellij-community,MichaelNedzelsky/intellij-community,akosyakov/intellij-community,muntasirsyed/intellij-community,tmpgit/intellij-community,fengbaicanhe/intellij-community,michaelgallacher/intellij-community,samthor/intellij-community,vladmm/intellij-community,clumsy/intellij-community,apixandru/intellij-community,kdwink/intellij-community,diorcety/intellij-community,muntasirsyed/intellij-community,MichaelNedzelsky/intellij-community,gnuhub/intellij-community,diorcety/intellij-community,ahb0327/intellij-community,kool79/intellij-community,diorcety/intellij-community,diorcety/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,orekyuu/intellij-community,orekyuu/intellij-community,alphafoobar/intellij-community,tmpgit/intellij-community,TangHao1987/intellij-community,ol-loginov/intellij-community,alphafoobar/intellij-community,ThiagoGarciaAlves/intellij-community,caot/intellij-community,robovm/robovm-studio,fnouama/intellij-community,kool79/intellij-community,holmes/intellij-community,Lekanich/intellij-community,semonte/intellij-community,wreckJ/intellij-community,slisson/intellij-community,xfournet/intellij-community,ol-loginov/intellij-community,robovm/robovm-studio,muntasirsyed/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,kool79/intellij-community,wreckJ/intellij-community,ibinti/intellij-community,allotria/intellij-community,allotria/intellij-community,youdonghai/intellij-community,MER-GROUP/intellij-community,vladmm/intellij-community,izonder/intellij-community,adedayo/intellij-community,TangHao1987/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,samthor/intellij-community,Distrotech/intellij-community,retomerz/intellij-community,TangHao1987/intellij-community,nicolargo/intellij-community,youdonghai/intellij-community,izonder/intellij-community,michaelgallacher/intellij-community,robovm/robovm-studio,michaelgallacher/intellij-community,MER-GROUP/intellij-community,ol-loginov/intellij-community,salguarnieri/intellij-community,TangHao1987/intellij-community,diorcety/intellij-community,hurricup/intellij-community,da1z/intellij-community,alphafoobar/intellij-community,fnouama/intellij-community,holmes/intellij-community,nicolargo/intellij-community,SerCeMan/intellij-community,wreckJ/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,semonte/intellij-community,hurricup/intellij-community,asedunov/intellij-community,jagguli/intellij-community,adedayo/intellij-community,ibinti/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,semonte/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,robovm/robovm-studio,fitermay/intellij-community,kool79/intellij-community,fitermay/intellij-community,nicolargo/intellij-community,mglukhikh/intellij-community,caot/intellij-community,vladmm/intellij-community,orekyuu/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,allotria/intellij-community,supersven/intellij-community,SerCeMan/intellij-community,xfournet/intellij-community,ivan-fedorov/intellij-community,blademainer/intellij-community,fnouama/intellij-community,youdonghai/intellij-community,fnouama/intellij-community,wreckJ/intellij-community,asedunov/intellij-community,apixandru/intellij-community,orekyuu/intellij-community,izonder/intellij-community,Lekanich/intellij-community,kdwink/intellij-community,ahb0327/intellij-community,petteyg/intellij-community,diorcety/intellij-community,ol-loginov/intellij-community,semonte/intellij-community,xfournet/intellij-community,slisson/intellij-community,MER-GROUP/intellij-community,blademainer/intellij-community,michaelgallacher/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,fitermay/intellij-community,signed/intellij-community,MER-GROUP/intellij-community,supersven/intellij-community,MichaelNedzelsky/intellij-community,orekyuu/intellij-community,hurricup/intellij-community,amith01994/intellij-community,ftomassetti/intellij-community,fnouama/intellij-community,wreckJ/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,MER-GROUP/intellij-community,gnuhub/intellij-community,MichaelNedzelsky/intellij-community,slisson/intellij-community,izonder/intellij-community,nicolargo/intellij-community,FHannes/intellij-community,clumsy/intellij-community,FHannes/intellij-community,FHannes/intellij-community,ryano144/intellij-community,xfournet/intellij-community,izonder/intellij-community,muntasirsyed/intellij-community,holmes/intellij-community,samthor/intellij-community,kool79/intellij-community,ahb0327/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,asedunov/intellij-community,blademainer/intellij-community,signed/intellij-community,izonder/intellij-community,allotria/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,samthor/intellij-community,lucafavatella/intellij-community,dslomov/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,signed/intellij-community,Distrotech/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,retomerz/intellij-community,asedunov/intellij-community,xfournet/intellij-community,izonder/intellij-community,ibinti/intellij-community,SerCeMan/intellij-community,da1z/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,ivan-fedorov/intellij-community,gnuhub/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,fengbaicanhe/intellij-community,ibinti/intellij-community,dslomov/intellij-community,ftomassetti/intellij-community,pwoodworth/intellij-community,salguarnieri/intellij-community,SerCeMan/intellij-community,TangHao1987/intellij-community,caot/intellij-community,ol-loginov/intellij-community,amith01994/intellij-community,fitermay/intellij-community,alphafoobar/intellij-community,supersven/intellij-community,idea4bsd/idea4bsd,adedayo/intellij-community,asedunov/intellij-community,blademainer/intellij-community,clumsy/intellij-community,holmes/intellij-community,pwoodworth/intellij-community,izonder/intellij-community,SerCeMan/intellij-community,ahb0327/intellij-community,caot/intellij-community,supersven/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,mglukhikh/intellij-community,ivan-fedorov/intellij-community,ryano144/intellij-community,ol-loginov/intellij-community,petteyg/intellij-community,idea4bsd/idea4bsd,MichaelNedzelsky/intellij-community,amith01994/intellij-community,signed/intellij-community,amith01994/intellij-community,akosyakov/intellij-community,izonder/intellij-community,youdonghai/intellij-community,ftomassetti/intellij-community,muntasirsyed/intellij-community,adedayo/intellij-community,SerCeMan/intellij-community,akosyakov/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,allotria/intellij-community,tmpgit/intellij-community,ryano144/intellij-community,petteyg/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,salguarnieri/intellij-community,ivan-fedorov/intellij-community,michaelgallacher/intellij-community,TangHao1987/intellij-community,mglukhikh/intellij-community,kdwink/intellij-community,tmpgit/intellij-community,suncycheng/intellij-community,ivan-fedorov/intellij-community,FHannes/intellij-community,FHannes/intellij-community,gnuhub/intellij-community,slisson/intellij-community,robovm/robovm-studio,caot/intellij-community,fengbaicanhe/intellij-community,semonte/intellij-community,ryano144/intellij-community,alphafoobar/intellij-community,gnuhub/intellij-community,TangHao1987/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,SerCeMan/intellij-community,ahb0327/intellij-community,nicolargo/intellij-community,supersven/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,kdwink/intellij-community,da1z/intellij-community,ol-loginov/intellij-community,vladmm/intellij-community,akosyakov/intellij-community,retomerz/intellij-community,ivan-fedorov/intellij-community,ol-loginov/intellij-community,orekyuu/intellij-community,ibinti/intellij-community,alphafoobar/intellij-community,amith01994/intellij-community,clumsy/intellij-community,da1z/intellij-community,jagguli/intellij-community,hurricup/intellij-community,robovm/robovm-studio,caot/intellij-community,vladmm/intellij-community,fengbaicanhe/intellij-community,amith01994/intellij-community,orekyuu/intellij-community,retomerz/intellij-community,wreckJ/intellij-community,TangHao1987/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,ftomassetti/intellij-community,kdwink/intellij-community,fengbaicanhe/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,xfournet/intellij-community,ol-loginov/intellij-community,muntasirsyed/intellij-community,jagguli/intellij-community,idea4bsd/idea4bsd,vladmm/intellij-community,ol-loginov/intellij-community,muntasirsyed/intellij-community,idea4bsd/idea4bsd,adedayo/intellij-community,petteyg/intellij-community,FHannes/intellij-community,tmpgit/intellij-community,ftomassetti/intellij-community,Distrotech/intellij-community,blademainer/intellij-community,ftomassetti/intellij-community,amith01994/intellij-community,ivan-fedorov/intellij-community,tmpgit/intellij-community,apixandru/intellij-community,allotria/intellij-community,samthor/intellij-community,dslomov/intellij-community,dslomov/intellij-community,dslomov/intellij-community,suncycheng/intellij-community,nicolargo/intellij-community,asedunov/intellij-community,semonte/intellij-community,fnouama/intellij-community,ftomassetti/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,adedayo/intellij-community,fengbaicanhe/intellij-community,supersven/intellij-community,diorcety/intellij-community,robovm/robovm-studio,jagguli/intellij-community,robovm/robovm-studio,supersven/intellij-community,blademainer/intellij-community,diorcety/intellij-community,orekyuu/intellij-community,ahb0327/intellij-community,samthor/intellij-community,Lekanich/intellij-community,SerCeMan/intellij-community,ryano144/intellij-community,ThiagoGarciaAlves/intellij-community,kool79/intellij-community,ftomassetti/intellij-community,ibinti/intellij-community,fnouama/intellij-community,ahb0327/intellij-community,diorcety/intellij-community,allotria/intellij-community,suncycheng/intellij-community,nicolargo/intellij-community,ivan-fedorov/intellij-community,alphafoobar/intellij-community,supersven/intellij-community,caot/intellij-community,ThiagoGarciaAlves/intellij-community,gnuhub/intellij-community,holmes/intellij-community,clumsy/intellij-community,asedunov/intellij-community,dslomov/intellij-community,vvv1559/intellij-community,Distrotech/intellij-community,akosyakov/intellij-community,MichaelNedzelsky/intellij-community,slisson/intellij-community,lucafavatella/intellij-community,Distrotech/intellij-community,dslomov/intellij-community,izonder/intellij-community,xfournet/intellij-community,tmpgit/intellij-community,vvv1559/intellij-community,vladmm/intellij-community,tmpgit/intellij-community,adedayo/intellij-community,MichaelNedzelsky/intellij-community,ryano144/intellij-community,hurricup/intellij-community,Distrotech/intellij-community,retomerz/intellij-community | /*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.editor.impl;
import com.intellij.openapi.application.Result;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.command.impl.UndoManagerImpl;
import com.intellij.openapi.command.undo.UndoManager;
import com.intellij.openapi.editor.*;
import com.intellij.openapi.editor.event.DocumentAdapter;
import com.intellij.openapi.editor.event.DocumentEvent;
import com.intellij.openapi.editor.ex.DocumentEx;
import com.intellij.openapi.editor.ex.MarkupModelEx;
import com.intellij.openapi.editor.ex.RangeHighlighterEx;
import com.intellij.openapi.editor.ex.RangeMarkerEx;
import com.intellij.openapi.editor.markup.HighlighterTargetArea;
import com.intellij.openapi.editor.markup.MarkupModel;
import com.intellij.openapi.editor.markup.RangeHighlighter;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.ThrowableComputable;
import com.intellij.openapi.util.Trinity;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiFile;
import com.intellij.psi.impl.PsiDocumentManagerImpl;
import com.intellij.psi.impl.PsiToDocumentSynchronizer;
import com.intellij.testFramework.LeakHunter;
import com.intellij.testFramework.LightPlatformTestCase;
import com.intellij.testFramework.PlatformTestUtil;
import com.intellij.testFramework.Timings;
import com.intellij.util.CommonProcessors;
import com.intellij.util.ThrowableRunnable;
import com.intellij.util.containers.WeakList;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import java.util.*;
/**
* @author mike
*/
public class RangeMarkerTest extends LightPlatformTestCase {
private PsiDocumentManagerImpl documentManager;
private PsiToDocumentSynchronizer synchronizer;
private Document document;
private PsiFile psiFile;
@Override
protected void runTest() throws Throwable {
if (getTestName(false).contains("NoVerify")) {
super.runTest();
return;
}
boolean oldVerify = RedBlackTree.VERIFY;
RedBlackTree.VERIFY = !isPerformanceTest();
final Throwable[] ex = {null};
try {
if (getTestName(false).contains("NoCommand")) {
super.runTest();
return;
}
WriteCommandAction.runWriteCommandAction(getProject(), new ThrowableComputable<Void, Throwable>() {
@Override
public Void compute() throws Throwable {
RangeMarkerTest.super.runTest();
return null;
}
});
}
finally {
RedBlackTree.VERIFY = oldVerify;
}
if (ex[0] != null) throw ex[0];
}
@Override
protected void setUp() throws Exception {
super.setUp();
documentManager = (PsiDocumentManagerImpl)PsiDocumentManager.getInstance(getProject());
synchronizer = documentManager.getSynchronizer();
}
public void testCreation() throws Exception {
RangeMarker marker = createMarker("0123456789", 2, 5);
assertEquals(2, marker.getStartOffset());
assertEquals(5, marker.getEndOffset());
assertTrue(marker.isValid());
}
public void testDeleteBeforeStart() throws Exception {
RangeMarker marker = createMarker("01[234]56789");
marker.getDocument().deleteString(0, 1);
assertEquals(1, marker.getStartOffset());
assertEquals(4, marker.getEndOffset());
assertTrue(marker.isValid());
}
public void testInsertIntoRange() throws Exception {
RangeMarker marker = createMarker("0123456789", 2, 5);
marker.getDocument().insertString(4, "xxx");
assertEquals(2, marker.getStartOffset());
assertEquals(8, marker.getEndOffset());
assertTrue(marker.isValid());
}
public void testInsertIntoPoint() throws Exception {
RangeMarker marker = createMarker("0123456789", 2, 2);
marker.getDocument().insertString(2, "xxx");
assertEquals(2, marker.getStartOffset());
assertEquals(2, marker.getEndOffset());
assertTrue(marker.isValid());
}
public void testDeletePoint() throws Exception {
RangeMarker marker = createMarker("0123456789", 2, 2);
marker.getDocument().deleteString(1, 3);
assertFalse(marker.isValid());
}
public void testDeleteRangeInside() throws Exception {
RangeMarker marker = createMarker("0123456789", 1, 7);
marker.getDocument().deleteString(2, 5);
assertTrue(marker.isValid());
}
public void testReplaceRangeToSingleChar() throws Exception {
RangeMarker marker = createMarker("0123456789", 1, 7);
marker.getDocument().replaceString(2, 5, " ");
assertTrue(marker.isValid());
}
public void testReplaceWholeRange() throws Exception {
RangeMarker marker = createMarker("0123456789", 1, 7);
marker.getDocument().replaceString(1, 7, "abc");
assertValidMarker(marker, 1, 4);
}
public void testUpdateInvalid() throws Exception {
RangeMarker marker = createMarker("01[]23456789");
marker.getDocument().deleteString(1, 3);
assertFalse(marker.isValid());
marker.getDocument().insertString(2, "xxx");
assertEquals(2, marker.getStartOffset());
assertEquals(2, marker.getEndOffset());
assertFalse(marker.isValid());
}
public void testInsertAfterEnd() throws Exception {
RangeMarker marker = createMarker("0123456789", 2, 5);
marker.getDocument().insertString(6, "xxx");
assertEquals(2, marker.getStartOffset());
assertEquals(5, marker.getEndOffset());
assertTrue(marker.isValid());
}
public void testDeleteEndPart() throws Exception {
RangeMarker marker = createMarker("0123456789", 2, 5);
marker.getDocument().deleteString(4, 6);
assertValidMarker(marker, 2, 4);
}
public void testDeleteStartPart() throws Exception {
RangeMarker marker = createMarker("0123456789", 2, 5);
marker.getDocument().deleteString(0, 4);
assertValidMarker(marker, 0, 1);
}
public void testReplaceStartPartInvalid() throws Exception {
RangeMarker marker = createMarker("0123456789", 2, 5);
marker.getDocument().replaceString(0, 4, "xxxx");
assertValidMarker(marker, 4, 5);
}
public void testDeleteFirstChar() throws Exception {
RangeMarker marker = createMarker("0123456789", 0, 5);
marker.getDocument().deleteString(0, 1);
assertValidMarker(marker, 0, 4);
}
public void testInsertBeforeStart() throws Exception {
RangeMarker marker = createMarker("0123456789", 2, 5);
marker.getDocument().insertString(0, "xxx");
assertEquals(5, marker.getStartOffset());
assertEquals(8, marker.getEndOffset());
assertTrue(marker.isValid());
}
public void testInsertIntoStart() throws Exception {
RangeMarker marker = createMarker("0123456789", 2, 5);
marker.getDocument().insertString(2, "xxx");
assertValidMarker(marker, 5, 8);
}
public void testInsertIntoStartExpandToLeft() throws Exception {
RangeMarker marker = createMarker("0123456789", 2, 5);
marker.setGreedyToLeft(true);
marker.getDocument().insertString(2, "xxx");
assertEquals(2, marker.getStartOffset());
assertEquals(8, marker.getEndOffset());
assertTrue(marker.isValid());
}
public void testInsertIntoEnd() throws Exception {
RangeMarker marker = createMarker("0123456789", 2, 5);
marker.getDocument().insertString(5, "xxx");
assertEquals(2, marker.getStartOffset());
assertEquals(5, marker.getEndOffset());
assertTrue(marker.isValid());
}
public void testInsertIntoEndExpandRight() throws Exception {
RangeMarker marker = createMarker("0123456789", 2, 5);
marker.setGreedyToRight(true);
marker.getDocument().insertString(5, "xxx");
assertEquals(2, marker.getStartOffset());
assertEquals(8, marker.getEndOffset());
assertTrue(marker.isValid());
}
public void testNoNegative() throws Exception {
RangeMarker marker = createMarker("package safd;\n\n[import javax.swing.JPanel;]\nimport java.util.ArrayList;\n\nclass T{}");
marker.getDocument()
.replaceString(15, 15 + "import javax.swing.JPanel;\nimport java.util.ArrayList;".length(), "import java.util.ArrayList;");
assertEquals(15, marker.getStartOffset());
}
public void testReplaceRightIncludingFirstChar() throws Exception {
String s = "12345\n \n12345";
RangeMarker marker = createMarker(s, 6, 8);
marker.getDocument().replaceString(0, s.length(), s.replaceAll(" ", ""));
assertValidMarker(marker, 6, 7);
}
public void testDeleteRightPart() throws Exception {
RangeMarker marker = createMarker("0123456789", 2, 5);
marker.getDocument().deleteString(4, 6);
assertValidMarker(marker, 2, 4);
}
public void testDeleteRightPart2() throws Exception {
RangeMarker marker = createMarker("0123456789", 2, 5);
marker.getDocument().deleteString(4, 5);
assertValidMarker(marker, 2, 4);
}
public void testReplaceRightPartInvalid() throws Exception {
RangeMarker marker = createMarker("0123456789", 2, 5);
marker.getDocument().replaceString(4, 6, "xxx");
assertValidMarker(marker, 2, 4);
}
public void testDeleteWholeRange() throws Exception {
RangeMarker marker = createMarker("0123456789", 2, 5);
marker.getDocument().deleteString(1, 6);
assertFalse(marker.isValid());
}
public void testDeleteExactRange() throws Exception {
RangeMarker marker = createMarker("0123456789", 2, 5);
marker.getDocument().deleteString(2, 5);
assertValidMarker(marker, 2, 2);
}
public void testDeleteJustBeforeStart() throws Exception {
RangeMarker marker = createMarker("0123456789", 2, 5);
marker.getDocument().deleteString(0, 2);
assertValidMarker(marker, 0, 3);
}
public void testDeleteRightAfterEnd() throws Exception {
RangeMarker marker = createMarker("0123456789", 2, 2);
marker.getDocument().deleteString(2, 5);
assertValidMarker(marker, 2, 2);
}
public void testReplacementWithOldTextOverlap() throws Exception {
RangeMarker marker = createMarker("0123456789", 2, 5);
marker.getDocument().replaceString(0, 10, "0123456789");
assertValidMarker(marker, 2, 5);
}
// Psi -> Document synchronization
public void testPsi2Doc1() throws Exception {
StringBuilder buffer = new StringBuilder("0123456789");
RangeMarker marker = createMarker(buffer.toString(), 2, 5);
synchronizer.startTransaction(getProject(), document, psiFile);
synchronizer.insertString(document, 3, "a");
buffer.insert(3, "a");
synchronizer.commitTransaction(this.document);
assertEquals(buffer.toString(), document.getText());
assertValidMarker(marker, 2, 6);
}
public void testDocSynchronizerPrefersLineBoundaryChanges() throws Exception {
String text = "import java.awt.List;\n" +
"[import java.util.ArrayList;\n]" +
"import java.util.HashMap;\n" +
"import java.util.Map;";
RangeMarker marker = createMarker(text);
synchronizer.startTransaction(getProject(), document, psiFile);
String newText = StringUtil.replaceSubstring(document.getText(), TextRange.create(marker), "");
synchronizer.replaceString(document, 0, document.getTextLength(), newText);
final List<DocumentEvent> events = new ArrayList<DocumentEvent>();
document.addDocumentListener(new DocumentAdapter() {
@Override
public void documentChanged(DocumentEvent e) {
events.add(e);
}
});
synchronizer.commitTransaction(document);
assertEquals(newText, document.getText());
DocumentEvent event = assertOneElement(events);
assertEquals("DocumentEventImpl[myOffset=22, myOldLength=28, myNewLength=0, myOldString='import java.util.ArrayList;\n', myNewString=''].", event.toString());
}
public void testPsi2DocReplaceAfterAdd() throws Exception {
StringBuilder buffer = new StringBuilder("0123456789");
RangeMarker marker = createMarker(buffer.toString(), 2, 5);
synchronizer.startTransaction(getProject(), document, psiFile);
synchronizer.insertString(document, 1, "a");
buffer.insert(1, "a");
synchronizer.replaceString(document, 3, 4, "a");
buffer.replace(3, 4, "a");
synchronizer.commitTransaction(document);
assertEquals(buffer.toString(), document.getText());
assertValidMarker(marker, 3, 6);
}
public void testPsi2DocMergeReplaceAfterAdd() throws Exception {
StringBuilder buffer = new StringBuilder("0123456789");
RangeMarker marker = createMarker(buffer.toString(), 2, 5);
synchronizer.startTransaction(getProject(), document, psiFile);
synchronizer.insertString(document, 1, "a");
buffer.insert(1, "a");
synchronizer.replaceString(document, 3, 4, "a");
buffer.replace(3, 4, "a");
synchronizer.replaceString(document, 3, 5, "bb");
buffer.replace(3, 5, "bb");
final PsiToDocumentSynchronizer.DocumentChangeTransaction transaction = synchronizer.getTransaction(document);
final Set<Pair<PsiToDocumentSynchronizer.MutableTextRange, StringBuffer>> affectedFragments = transaction.getAffectedFragments();
assertEquals(affectedFragments.size(), 2);
synchronizer.commitTransaction(document);
assertEquals(buffer.toString(), document.getText());
assertValidMarker(marker, 3, 6);
}
public void testPsi2DocMergeReplaceWithMultipleAdditions() throws Exception {
StringBuilder buffer = new StringBuilder("0123456789");
RangeMarker marker = createMarker(buffer.toString(), 2, 5);
synchronizer.startTransaction(getProject(), document, psiFile);
synchronizer.replaceString(document, 0, 10, "0");
buffer.replace(0, 10, "0");
for (int i = 1; i < 10; i++) {
synchronizer.insertString(document, i, "" + i);
buffer.insert(i, "" + i);
}
final PsiToDocumentSynchronizer.DocumentChangeTransaction transaction = synchronizer.getTransaction(document);
final Set<Pair<PsiToDocumentSynchronizer.MutableTextRange, StringBuffer>> affectedFragments = transaction.getAffectedFragments();
assertEquals(1, affectedFragments.size());
synchronizer.commitTransaction(document);
assertEquals(buffer.toString(), document.getText());
assertValidMarker(marker, 2, 5);
}
public void testPsi2DocMergeMultipleAdditionsWithReplace() throws Exception {
StringBuilder buffer = new StringBuilder("0123456789");
RangeMarker marker = createMarker(buffer.toString(), 2, 5);
synchronizer.startTransaction(getProject(), document, psiFile);
final PsiToDocumentSynchronizer.DocumentChangeTransaction transaction = synchronizer.getTransaction(document);
final Set<Pair<PsiToDocumentSynchronizer.MutableTextRange, StringBuffer>> affectedFragments = transaction.getAffectedFragments();
for (int i = 0; i < 10; i++) {
synchronizer.insertString(document, i, "" + i);
buffer.insert(i, "" + i);
}
assertEquals(1, affectedFragments.size());
synchronizer.replaceString(document, 0, 20, "0123456789");
buffer.replace(0, 20, "0123456789");
assertEquals(1, affectedFragments.size());
synchronizer.commitTransaction(document);
assertEquals(buffer.toString(), document.getText());
assertValidMarker(marker, 2, 5);
}
public void testPsi2DocSurround() throws Exception {
StringBuilder buffer = new StringBuilder("0123456789");
RangeMarker marker = createMarker(buffer.toString(), 2, 5);
synchronizer.startTransaction(getProject(), document, psiFile);
synchronizer.replaceString(document, 3, 5, "3a4");
buffer.replace(3, 5, "3a4");
synchronizer.insertString(document, 3, "b");
buffer.insert(3, "b");
synchronizer.insertString(document, 7, "d");
buffer.insert(7, "d");
final PsiToDocumentSynchronizer.DocumentChangeTransaction transaction = synchronizer.getTransaction(document);
final Set<Pair<PsiToDocumentSynchronizer.MutableTextRange, StringBuffer>> affectedFragments = transaction.getAffectedFragments();
assertEquals(3, affectedFragments.size());
synchronizer.commitTransaction(document);
assertEquals(buffer.toString(), document.getText());
assertValidMarker(marker, 2, 7);
}
public void testPsi2DocForwardRangesChanges() throws Exception {
StringBuilder buffer = new StringBuilder("0123456789");
RangeMarker marker = createMarker(buffer.toString(), 2, 5);
synchronizer.startTransaction(getProject(), document, psiFile);
synchronizer.replaceString(document, 4, 5, "3a4");
buffer.replace(4, 5, "3a4");
synchronizer.insertString(document, 7, "b");
buffer.insert(7, "b");
synchronizer.insertString(document, 1, "b");
buffer.insert(1, "b");
synchronizer.commitTransaction(document);
assertEquals(buffer.toString(), document.getText());
assertValidMarker(marker, 3, 8);
}
private static void assertValidMarker(@NotNull RangeMarker marker, int start, int end) {
assertTrue(marker.isValid());
assertEquals(start, marker.getStartOffset());
assertEquals(end, marker.getEndOffset());
}
public void testNested() {
RangeMarker marker1 = createMarker("0[12345678]9");
Document document = marker1.getDocument();
RangeMarker marker2 = document.createRangeMarker(2, 5);
RangeMarker marker3 = document.createRangeMarker(3, 4);
document.insertString(0, "x");
assertEquals(2, marker1.getStartOffset());
assertEquals(3, marker2.getStartOffset());
assertEquals(4, marker3.getStartOffset());
}
public void testNestedAfter() {
RangeMarker marker1 = createMarker("0[12345678]90123");
Document document = marker1.getDocument();
RangeMarker marker2 = document.createRangeMarker(2, 5);
RangeMarker marker3 = document.createRangeMarker(3, 4);
document.insertString(10, "x");
assertEquals(1, marker1.getStartOffset());
assertEquals(2, marker2.getStartOffset());
assertEquals(3, marker3.getStartOffset());
}
public void testNested3() {
RangeMarker marker1 = createMarker("01[23]4567890123");
DocumentEx document = (DocumentEx)marker1.getDocument();
RangeMarker marker2 = document.createRangeMarker(9, 11);
RangeMarker marker3 = document.createRangeMarker(1, 12);
marker3.dispose();
document.deleteString(marker1.getEndOffset(), marker2.getStartOffset());
}
public void testBranched() {
RangeMarker marker1 = createMarker("01234567890123456", 0, 1);
DocumentEx document = (DocumentEx)marker1.getDocument();
RangeMarker marker2 = document.createRangeMarker(2, 3);
RangeMarker marker3 = document.createRangeMarker(4, 5);
RangeMarker marker4 = document.createRangeMarker(6, 7);
RangeMarker marker5 = document.createRangeMarker(8, 9);
RangeMarker marker6 = document.createRangeMarker(10, 11);
RangeMarker marker7 = document.createRangeMarker(12, 13);
RangeMarker marker8 = document.createRangeMarker(14, 15);
document.deleteString(1, 2);
}
public void testDevourMarkerWithDeletion() {
RangeMarker marker1 = createMarker("012345[67890123456]7");
DocumentEx document = (DocumentEx)marker1.getDocument();
document.deleteString(1, document.getTextLength());
}
public void testLL() {
RangeMarker marker1 = createMarker("012345678901234567", 5,6);
DocumentEx document = (DocumentEx)marker1.getDocument();
document.createRangeMarker(4, 5);
document.createRangeMarker(6, 7);
document.createRangeMarker(0, 4);
document.deleteString(1, 2);
document.createRangeMarker(0, 7);
document.createRangeMarker(0, 7);
}
public void testSwap() {
RangeMarkerEx marker1 = createMarker("012345678901234567", 5,6);
DocumentEx document = (DocumentEx)marker1.getDocument();
document.createRangeMarker(3, 5);
document.createRangeMarker(6, 7);
document.createRangeMarker(4, 4);
marker1.dispose();
}
public void testX() {
RangeMarkerEx marker1 = createMarker(StringUtil.repeatSymbol(' ', 10), 3,6);
DocumentEx document = (DocumentEx)marker1.getDocument();
document.createRangeMarker(2, 3);
document.createRangeMarker(3, 8);
document.createRangeMarker(7, 9);
RangeMarkerEx r1 = (RangeMarkerEx)document.createRangeMarker(6, 8);
r1.dispose();
marker1.dispose();
}
private static List<RangeMarker> add(DocumentEx document, int... offsets) {
List<RangeMarker> result = new ArrayList<RangeMarker>();
for (int i=0; i<offsets.length; i+=2) {
int start = offsets[i];
int end = offsets[i+1];
RangeMarker m = document.createRangeMarker(start, end);
result.add(m);
}
return result;
}
private static void delete(List<RangeMarker> mm, int... indexes) {
for (int index : indexes) {
RangeMarker m = mm.get(index);
m.dispose();
}
}
public void testX2() {
DocumentEx document = (DocumentEx)EditorFactory.getInstance().createDocument(StringUtil.repeatSymbol(' ', 10));
List<RangeMarker> mm =
add(document, 2,9, 0,0, 7,7
);
delete(mm, 0);
}
public void testX3() {
DocumentEx document = (DocumentEx)EditorFactory.getInstance().createDocument(StringUtil.repeatSymbol(' ', 10));
List<RangeMarker> mm =
add(document, 1,9, 8,8, 8,8, 0,5, 4,5
);
delete(mm, 0);
}
public void _testRandomAddRemove() {
int N = 100;
for (int ti=0; ;ti++) {
if (ti%10000 ==0) System.out.println(ti);
DocumentEx document = (DocumentEx)EditorFactory.getInstance().createDocument(StringUtil.repeatSymbol(' ', N));
Random gen = new Random();
List<Pair<RangeMarker, TextRange>> adds = new ArrayList<Pair<RangeMarker, TextRange>>();
List<Pair<RangeMarker, TextRange>> dels = new ArrayList<Pair<RangeMarker, TextRange>>();
try {
for (int i = 0; i < 30; i++) {
int x = gen.nextInt(N);
int y = x + gen.nextInt(N - x);
if (gen.nextBoolean()) {
x = 0;
y = document.getTextLength();
}
RangeMarkerEx r = (RangeMarkerEx)document.createRangeMarker(x, y);
adds.add(Pair.create((RangeMarker)r, TextRange.create(r)));
}
List<Pair<RangeMarker, TextRange>> candidates = new ArrayList<Pair<RangeMarker, TextRange>>(adds);
while (!candidates.isEmpty()) {
int size = candidates.size();
int x = gen.nextInt(size);
Pair<RangeMarker, TextRange> c = candidates.remove(x);
RangeMarkerEx r = (RangeMarkerEx)c.first;
assertEquals(size-1, candidates.size());
dels.add(c);
r.dispose();
}
}
catch (AssertionError e) {
String s= "adds: ";
for (Pair<RangeMarker, TextRange> c : adds) {
TextRange t = c.second;
s += t.getStartOffset() + "," + t.getEndOffset() + ", ";
}
s += "\ndels: ";
for (Pair<RangeMarker, TextRange> c : dels) {
int index = adds.indexOf(c);
assertSame(c, adds.get(index));
s += index + ", ";
}
System.err.println(s);
throw e;
}
}
}
private static void edit(DocumentEx document, int... offsets) {
for (int i = 0; i < offsets.length; i+=3) {
int offset = offsets[i];
int oldlength = offsets[i+1];
int newlength = offsets[i+2];
document.replaceString(offset, offset + oldlength, StringUtil.repeatSymbol(' ', newlength));
}
}
public void testE1() {
DocumentEx document = (DocumentEx)EditorFactory.getInstance().createDocument(StringUtil.repeatSymbol(' ', 10));
List<RangeMarker> mm =
add(document, 3,5, 0,1, 9,9
);
edit(document, 3,6,0);
delete(mm, 0);
}
public void testE2() {
DocumentEx document = (DocumentEx)EditorFactory.getInstance().createDocument(StringUtil.repeatSymbol(' ', 10));
List<RangeMarker> mm =
add(document, 0,3, 6,9, 8,8
);
edit(document, 0,3,0);
delete(mm, 0);
}
public void testE3() {
DocumentEx document = (DocumentEx)EditorFactory.getInstance().createDocument(StringUtil.repeatSymbol(' ', 10));
List<RangeMarker> mm =
add(document, 4,5, 6,8, 3,4, 4,9, 2,9
);
edit(document, 4,6,0);
delete(mm, 0);
}
public void testE4() {
DocumentEx document = (DocumentEx)EditorFactory.getInstance().createDocument(StringUtil.repeatSymbol(' ', 10));
List<RangeMarker> mm =
add(document, 3,5, 5,6, 4,8, 6,9, 8,9
);
edit(document, 6,0,0, 3,0,2);
delete(mm, 1,0);
}
public void testE5() {
DocumentEx document = (DocumentEx)EditorFactory.getInstance().createDocument(StringUtil.repeatSymbol(' ', 10));
List<RangeMarker> mm =
add(document, 9,9, 4,4, 1,7, 7,7, 4,7
);
edit(document, 1,5,0);
delete(mm, 3);
}
public void testE6() {
DocumentEx document = (DocumentEx)EditorFactory.getInstance().createDocument(StringUtil.repeatSymbol(' ', 10));
List<RangeMarker> mm =
add(document, 4,8, 4,4, 4,9, 0,2, 6,8
);
edit(document, 3,2,0);
}
public void testE7() {
DocumentEx document = (DocumentEx)EditorFactory.getInstance().createDocument(StringUtil.repeatSymbol(' ', 10));
List<RangeMarker> mm =
add(document, 6,7, 0,3, 3,6, 5,9, 2,9
);
edit(document, 5,2,0);
}
public void testE8() {
DocumentEx document = (DocumentEx)EditorFactory.getInstance().createDocument(StringUtil.repeatSymbol(' ', 10));
List<RangeMarker> mm =
add(document, 5,5, 8,8, 1,3, 3,9
);
edit(document, 4,3,0);
}
public void testE9() {
DocumentEx document = (DocumentEx)EditorFactory.getInstance().createDocument(StringUtil.repeatSymbol(' ', 10));
List<RangeMarker> mm =
add(document, 4,5, 9,9, 1,2, 0,3
);
edit(document, 0,3,0);
}
public void testE10() {
DocumentEx document = (DocumentEx)EditorFactory.getInstance().createDocument(StringUtil.repeatSymbol(' ', 10));
List<RangeMarker> mm =
add(document, 9,9, 6,8, 8,8, 5,9
);
edit(document, 2,6,0, 2,0,4);
}
public void testE11() {
DocumentEx document = (DocumentEx)EditorFactory.getInstance().createDocument(StringUtil.repeatSymbol(' ', 10));
List<RangeMarker> mm =
add(document, 9,9, 7,7, 1,6, 3,7
);
//edit(document, 0,0,0);
delete(mm, 1);
}
public void testE12() {
DocumentEx document = (DocumentEx)EditorFactory.getInstance().createDocument(StringUtil.repeatSymbol(' ', 10));
List<RangeMarker> mm =
add(document, 3,3, 8,8, 5,5, 5,6
);
edit(document, 2,0,2);
delete(mm, 2);
}
public void testE13() {
DocumentEx document = (DocumentEx)EditorFactory.getInstance().createDocument(StringUtil.repeatSymbol(' ', 10));
List<RangeMarker> mm = add(document, 5,9, 9,9, 7,7, 6,8);
edit(document, 2,1,0);
delete(mm, 0, 2);
}
public void testE14() {
DocumentEx document = (DocumentEx)EditorFactory.getInstance().createDocument(StringUtil.repeatSymbol(' ', 100));
List<RangeMarker> mm = add(document, 6,11, 2,13, 17,17, 13,19, 2,3, 9,10, 10,11, 14,14, 1,3, 4,12, 14,15, 3,10, 14,14, 4,4, 4,8, 6,14, 8,16, 2,12, 11,19, 10,13
);
edit(document, 19,0,0, 7,3,0, 16,0,3);
}
public void testE15() {
DocumentEx document = (DocumentEx)EditorFactory.getInstance().createDocument(StringUtil.repeatSymbol(' ', 100));
List<RangeMarker> mm = add(document, 90,93, 0,9, 44,79, 4,48, 44,99, 53,64, 59,82, 12,99, 81,86, 8,40, 24,55, 32,50, 74,79, 14,94, 7,14
);
edit(document, 34,0,4, 99,0,3);
}
public void testE16() {
DocumentEx document = (DocumentEx)EditorFactory.getInstance().createDocument(StringUtil.repeatSymbol(' ', 100));
List<RangeMarker> mm = add(document, 29,63, 47,52, 72,86, 19,86, 13,55, 18,57, 92,95, 83,99, 41,80, 53,85, 10,30, 28,44, 23,32, 70,95, 14,28
);
edit(document, 67,5,0, 1,0,4);
delete(mm, 11);
}
public void testE17() {
DocumentEx document = (DocumentEx)EditorFactory.getInstance().createDocument(StringUtil.repeatSymbol(' ', 100));
List<RangeMarker> mm = add(document, 15,85, 79,88, 90,94, 43,67, 54,89, 81,98, 1,34, 58,93, 22,23, 44,45, 63,84, 45,76, 58,87, 40,59, 5,81, 95,95, 12,61, 52,65, 80,95, 6,16, 7,67, 59,63, 91,96, 99,99, 50,96, 72,78, 78,78, 85,85, 5,51, 90,91
);
edit(document, 20,26,0, 15,0,4, 64,4,0);
}
public void testRandomEdit_NoCommand() {
final int N = 100;
final Random gen = new Random();
int N_TRIES = Timings.adjustAccordingToMySpeed(7000, false);
System.out.println("N_TRIES = " + N_TRIES);
DocumentEx document = null;
for (int tryn=0; tryn < N_TRIES;tryn++) {
((UndoManagerImpl)UndoManager.getInstance(getProject())).flushCurrentCommandMerger();
((UndoManagerImpl)UndoManager.getGlobalInstance()).flushCurrentCommandMerger();
if (document != null) {
((UndoManagerImpl)UndoManager.getInstance(getProject())).clearUndoRedoQueueInTests(document);
((UndoManagerImpl)UndoManager.getGlobalInstance()).clearUndoRedoQueueInTests(document);
}
if (tryn % 10000 == 0) {
System.out.println(tryn);
}
document = (DocumentEx)EditorFactory.getInstance().createDocument(StringUtil.repeatSymbol(' ', N));
final DocumentEx finalDocument = document;
new WriteCommandAction(getProject()) {
@Override
protected void run(Result result) throws Exception {
List<Pair<RangeMarker, TextRange>> adds = new ArrayList<Pair<RangeMarker, TextRange>>();
List<Pair<RangeMarker, TextRange>> dels = new ArrayList<Pair<RangeMarker, TextRange>>();
List<Trinity<Integer, Integer, Integer>> edits = new ArrayList<Trinity<Integer, Integer, Integer>>();
try {
for (int i = 0; i < 30; i++) {
int x = gen.nextInt(N);
int y = x + gen.nextInt(N - x);
RangeMarkerEx r = (RangeMarkerEx)finalDocument.createRangeMarker(x, y);
adds.add(Pair.create((RangeMarker)r, TextRange.create(r)));
}
for (int i = 0; i < 10; i++) {
int offset = gen.nextInt(finalDocument.getTextLength());
if (gen.nextBoolean()) {
int length = gen.nextInt(5);
edits.add(Trinity.create(offset, 0, length));
finalDocument.insertString(offset, StringUtil.repeatSymbol(' ', length));
}
else {
int length = gen.nextInt(finalDocument.getTextLength() - offset);
edits.add(Trinity.create(offset, length, 0));
finalDocument.deleteString(offset, offset + length);
}
}
List<Pair<RangeMarker, TextRange>> candidates = new ArrayList<Pair<RangeMarker, TextRange>>(adds);
while (!candidates.isEmpty()) {
int size = candidates.size();
int x = gen.nextInt(size);
Pair<RangeMarker, TextRange> c = candidates.remove(x);
RangeMarkerEx r = (RangeMarkerEx)c.first;
assertEquals(size - 1, candidates.size());
dels.add(c);
r.dispose();
}
}
catch (AssertionError e) {
String s = "adds: ";
for (Pair<RangeMarker, TextRange> c : adds) {
TextRange t = c.second;
s += t.getStartOffset() + "," + t.getEndOffset() + ", ";
}
s += "\nedits: ";
for (Trinity<Integer, Integer, Integer> edit : edits) {
s += edit.first + "," + edit.second + "," + edit.third + ", ";
}
s += "\ndels: ";
for (Pair<RangeMarker, TextRange> c : dels) {
int index = adds.indexOf(c);
assertSame(c, adds.get(index));
s += index + ", ";
}
System.err.println(s);
throw e;
}
}
}.execute();
}
}
private RangeMarkerEx createMarker(String text, final int start, final int end) {
psiFile = createFile("x.txt", text);
return createMarker(psiFile, start, end);
}
private RangeMarkerEx createMarker(PsiFile psiFile, final int start, final int end) {
document = documentManager.getDocument(psiFile);
return (RangeMarkerEx)document.createRangeMarker(start, end);
}
private RangeMarkerEx createMarker(@NonNls String string) {
int start = string.indexOf('[');
assertTrue(start != -1);
string = string.replace("[", "");
int end = string.indexOf(']');
assertTrue(end != -1);
string = string.replace("]", "");
return createMarker(string, start, end);
}
public void testRangeMarkersAreWeakReferenced_NoVerify() throws Exception {
final Document document = EditorFactory.getInstance().createDocument("[xxxxxxxxxxxxxx]");
for (int i = 0; i < 10; i++) {
document.createRangeMarker(0, document.getTextLength());
}
LeakHunter.checkLeak(document, RangeMarker.class);
}
public void testRangeMarkersAreLazyCreated() throws Exception {
final Document document = EditorFactory.getInstance().createDocument("[xxxxxxxxxxxxxx]");
RangeMarker m1 = document.createRangeMarker(2, 4);
RangeMarker m2 = document.createRangeMarker(2, 4);
assertEquals(2, ((DocumentImpl)document).getRangeMarkersSize());
assertEquals(1, ((DocumentImpl)document).getRangeMarkersNodeSize());
RangeMarker m3 = document.createRangeMarker(2, 5);
assertEquals(2, ((DocumentImpl)document).getRangeMarkersNodeSize());
document.deleteString(4,5);
assertTrue(m1.isValid());
assertTrue(m2.isValid());
assertTrue(m3.isValid());
assertEquals(1, ((DocumentImpl)document).getRangeMarkersNodeSize());
m1.setGreedyToLeft(true);
assertTrue(m1.isValid());
assertEquals(3, ((DocumentImpl)document).getRangeMarkersSize());
assertEquals(2, ((DocumentImpl)document).getRangeMarkersNodeSize());
m3.dispose();
assertTrue(m1.isValid());
assertTrue(m2.isValid());
assertFalse(m3.isValid());
assertEquals(2, ((DocumentImpl)document).getRangeMarkersSize());
assertEquals(2, ((DocumentImpl)document).getRangeMarkersNodeSize());
}
public void testRangeHighlightersRecreateBug() throws Exception {
Document document = EditorFactory.getInstance().createDocument("[xxxxxxxxxxxxxx]");
MarkupModel markupModel = DocumentMarkupModel.forDocument(document, ourProject, true);
for (int i=0; i<2; i++) {
RangeMarker m = markupModel.addRangeHighlighter(1, 6, 0, null, HighlighterTargetArea.EXACT_RANGE);
RangeMarker m2 = markupModel.addRangeHighlighter(2, 7, 0, null, HighlighterTargetArea.EXACT_RANGE);
RangeMarker m3 = markupModel.addRangeHighlighter(1, 6, 0, null, HighlighterTargetArea.EXACT_RANGE);
markupModel.removeAllHighlighters();
}
}
public void testValidationBug() throws Exception {
Document document = EditorFactory.getInstance().createDocument("[xxxxxxxxxxxxxx]");
final Editor editor = EditorFactory.getInstance().createEditor(document);
try {
final FoldRegion[] fold = new FoldRegion[1];
editor.getFoldingModel().runBatchFoldingOperation(new Runnable() {
@Override
public void run() {
fold[0] = editor.getFoldingModel().addFoldRegion(0, 2, "");
}
});
RangeMarker marker = document.createRangeMarker(0, 2);
document.deleteString(1,2);
assertTrue(marker.isValid());
//assertFalse(fold[0].isValid());
}
finally {
EditorFactory.getInstance().releaseEditor(editor);
}
}
public void testPersistent() throws Exception {
String text = "xxx\nzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz";
Document document = EditorFactory.getInstance().createDocument(text);
int startOffset = text.indexOf('z');
int endOffset = text.lastIndexOf('z');
RangeMarker marker = document.createRangeMarker(startOffset, endOffset, true);
document.replaceString(startOffset+1, endOffset-1, "ccc");
assertTrue(marker.isValid());
}
public void testPersistentMarkerDoesntImpactNormalMarkers() {
Document doc = new DocumentImpl("text");
RangeMarker normal = doc.createRangeMarker(1, 3);
RangeMarker persistent = doc.createRangeMarker(1, 3, true);
doc.replaceString(0, 4, "before\ntext\nafter");
assertTrue(persistent.isValid());
assertFalse(normal.isValid());
}
public void testMoveTextRetargetsMarkers() throws Exception {
RangeMarkerEx marker1 = createMarker("01234567890", 1, 3);
DocumentEx document = (DocumentEx)marker1.getDocument();
RangeMarker marker2 = document.createRangeMarker(2, 4);
document.moveText(0, 5, 8);
assertEquals("56701234890", document.getText());
assertValidMarker(marker1, 4, 6);
assertValidMarker(marker2, 5, 7);
}
public void testMoveTextToTheBeginningRetargetsMarkers() throws Exception {
RangeMarkerEx marker1 = createMarker("01234567890", 5, 5);
DocumentEx document = (DocumentEx)marker1.getDocument();
RangeMarker marker2 = document.createRangeMarker(5, 7);
document.moveText(4, 7, 1);
assertEquals("04561237890", document.getText());
assertValidMarker(marker1, 2, 2);
assertValidMarker(marker2, 2, 4);
}
public void testRangeHighlighterDisposeVsRemoveAllConflict() throws Exception {
Document document = EditorFactory.getInstance().createDocument("[xxxxxxxxxxxxxx]");
MarkupModel markupModel = DocumentMarkupModel.forDocument(document, ourProject, true);
RangeMarker m = markupModel.addRangeHighlighter(1, 6, 0, null, HighlighterTargetArea.EXACT_RANGE);
assertTrue(m.isValid());
markupModel.removeAllHighlighters();
assertFalse(m.isValid());
assertEmpty(markupModel.getAllHighlighters());
m.dispose();
assertFalse(m.isValid());
}
public void testRangeHighlighterLinesInRangeForLongLinePerformance() throws Exception {
final int N = 50000;
Document document = EditorFactory.getInstance().createDocument(StringUtil.repeatSymbol('x', 2 * N));
final MarkupModelEx markupModel = (MarkupModelEx)DocumentMarkupModel.forDocument(document, ourProject, true);
for (int i=0; i<N-1;i++) {
markupModel.addRangeHighlighter(2*i, 2*i+1, 0, null, HighlighterTargetArea.EXACT_RANGE);
}
markupModel.addRangeHighlighter(N / 2, N / 2 + 1, 0, null, HighlighterTargetArea.LINES_IN_RANGE);
PlatformTestUtil.startPerformanceTest("slow highlighters lookup", (int)(N*Math.log(N)/1000), new ThrowableRunnable() {
@Override
public void run() {
List<RangeHighlighterEx> list = new ArrayList<RangeHighlighterEx>();
CommonProcessors.CollectProcessor<RangeHighlighterEx> coll = new CommonProcessors.CollectProcessor<RangeHighlighterEx>(list);
for (int i=0; i<N-1;i++) {
list.clear();
markupModel.processRangeHighlightersOverlappingWith(2*i, 2*i+1, coll);
assertEquals(2, list.size()); // 1 line plus one exact range marker
}
}
}).assertTiming();
}
public void testRangeHighlighterIteratorOrder() throws Exception {
Document document = EditorFactory.getInstance().createDocument("1234567890");
final MarkupModelEx markupModel = (MarkupModelEx)DocumentMarkupModel.forDocument(document, ourProject, true);
RangeHighlighter exact = markupModel.addRangeHighlighter(3, 6, 0, null, HighlighterTargetArea.EXACT_RANGE);
RangeHighlighter line = markupModel.addRangeHighlighter(4, 5, 0, null, HighlighterTargetArea.LINES_IN_RANGE);
List<RangeHighlighter> list = new ArrayList<RangeHighlighter>();
markupModel.processRangeHighlightersOverlappingWith(2, 9, new CommonProcessors.CollectProcessor<RangeHighlighter>(list));
assertEquals(Arrays.asList(line, exact), list);
}
public void testLazyRangeMarkers() {
psiFile = createFile("x.txt", "xxx");
LazyRangeMarkerFactoryImpl factory = (LazyRangeMarkerFactoryImpl)LazyRangeMarkerFactory.getInstance(getProject());
VirtualFile virtualFile = psiFile.getVirtualFile();
LazyRangeMarkerFactoryImpl.LazyMarker marker = (LazyRangeMarkerFactoryImpl.LazyMarker)factory.createRangeMarker(virtualFile, 0);
WeakList<LazyRangeMarkerFactoryImpl.LazyMarker> markers = LazyRangeMarkerFactoryImpl.getMarkers(virtualFile);
assertSame(marker, assertOneElement(markers));
assertFalse(marker.isDelegated());
assertTrue(marker.isValid());
assertEquals(0, marker.getStartOffset());
assertFalse(marker.isDelegated());
marker.dispose();
assertFalse(marker.isValid());
assertEmpty(LazyRangeMarkerFactoryImpl.getMarkers(virtualFile));
marker = (LazyRangeMarkerFactoryImpl.LazyMarker)factory.createRangeMarker(virtualFile, 0);
assertFalse(marker.isDelegated());
assertTrue(marker.isValid());
assertEquals(0, marker.getStartOffset());
assertFalse(marker.isDelegated());
Document document = marker.getDocument();
document.insertString(2, "yyy");
assertTrue(marker.isDelegated());
assertTrue(marker.isValid());
assertEquals(0, marker.getStartOffset());
assertEmpty(LazyRangeMarkerFactoryImpl.getMarkers(virtualFile));
marker.dispose();
assertEmpty(LazyRangeMarkerFactoryImpl.getMarkers(virtualFile));
}
}
| platform/platform-tests/testSrc/com/intellij/openapi/editor/impl/RangeMarkerTest.java | /*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.editor.impl;
import com.intellij.openapi.application.Result;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.command.impl.UndoManagerImpl;
import com.intellij.openapi.command.undo.UndoManager;
import com.intellij.openapi.editor.*;
import com.intellij.openapi.editor.event.DocumentAdapter;
import com.intellij.openapi.editor.event.DocumentEvent;
import com.intellij.openapi.editor.ex.DocumentEx;
import com.intellij.openapi.editor.ex.MarkupModelEx;
import com.intellij.openapi.editor.ex.RangeHighlighterEx;
import com.intellij.openapi.editor.ex.RangeMarkerEx;
import com.intellij.openapi.editor.markup.HighlighterTargetArea;
import com.intellij.openapi.editor.markup.MarkupModel;
import com.intellij.openapi.editor.markup.RangeHighlighter;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.ThrowableComputable;
import com.intellij.openapi.util.Trinity;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiFile;
import com.intellij.psi.impl.PsiDocumentManagerImpl;
import com.intellij.psi.impl.PsiToDocumentSynchronizer;
import com.intellij.testFramework.LeakHunter;
import com.intellij.testFramework.LightPlatformTestCase;
import com.intellij.testFramework.PlatformTestUtil;
import com.intellij.testFramework.Timings;
import com.intellij.util.CommonProcessors;
import com.intellij.util.ThrowableRunnable;
import com.intellij.util.containers.WeakList;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import java.util.*;
/**
* @author mike
*/
public class RangeMarkerTest extends LightPlatformTestCase {
private PsiDocumentManagerImpl documentManager;
private PsiToDocumentSynchronizer synchronizer;
private Document document;
private PsiFile psiFile;
@Override
protected void runTest() throws Throwable {
if (getTestName(false).contains("NoVerify")) {
super.runTest();
return;
}
boolean oldVerify = RedBlackTree.VERIFY;
RedBlackTree.VERIFY = !isPerformanceTest();
final Throwable[] ex = {null};
try {
if (getTestName(false).contains("NoCommand")) {
super.runTest();
return;
}
WriteCommandAction.runWriteCommandAction(getProject(), new ThrowableComputable<Void, Throwable>() {
@Override
public Void compute() throws Throwable {
RangeMarkerTest.super.runTest();
return null;
}
});
}
finally {
RedBlackTree.VERIFY = oldVerify;
}
if (ex[0] != null) throw ex[0];
}
@Override
protected void setUp() throws Exception {
super.setUp();
documentManager = (PsiDocumentManagerImpl)PsiDocumentManager.getInstance(getProject());
synchronizer = documentManager.getSynchronizer();
}
public void testCreation() throws Exception {
RangeMarker marker = createMarker("0123456789", 2, 5);
assertEquals(2, marker.getStartOffset());
assertEquals(5, marker.getEndOffset());
assertTrue(marker.isValid());
}
public void testDeleteBeforeStart() throws Exception {
RangeMarker marker = createMarker("01[234]56789");
marker.getDocument().deleteString(0, 1);
assertEquals(1, marker.getStartOffset());
assertEquals(4, marker.getEndOffset());
assertTrue(marker.isValid());
}
public void testInsertIntoRange() throws Exception {
RangeMarker marker = createMarker("0123456789", 2, 5);
marker.getDocument().insertString(4, "xxx");
assertEquals(2, marker.getStartOffset());
assertEquals(8, marker.getEndOffset());
assertTrue(marker.isValid());
}
public void testInsertIntoPoint() throws Exception {
RangeMarker marker = createMarker("0123456789", 2, 2);
marker.getDocument().insertString(2, "xxx");
assertEquals(2, marker.getStartOffset());
assertEquals(2, marker.getEndOffset());
assertTrue(marker.isValid());
}
public void testDeletePoint() throws Exception {
RangeMarker marker = createMarker("0123456789", 2, 2);
marker.getDocument().deleteString(1, 3);
assertFalse(marker.isValid());
}
public void testDeleteRangeInside() throws Exception {
RangeMarker marker = createMarker("0123456789", 1, 7);
marker.getDocument().deleteString(2, 5);
assertTrue(marker.isValid());
}
public void testReplaceRangeToSingleChar() throws Exception {
RangeMarker marker = createMarker("0123456789", 1, 7);
marker.getDocument().replaceString(2, 5, " ");
assertTrue(marker.isValid());
}
public void testReplaceWholeRange() throws Exception {
RangeMarker marker = createMarker("0123456789", 1, 7);
marker.getDocument().replaceString(1, 7, "abc");
assertValidMarker(marker, 1, 4);
}
public void testUpdateInvalid() throws Exception {
RangeMarker marker = createMarker("01[]23456789");
marker.getDocument().deleteString(1, 3);
assertFalse(marker.isValid());
marker.getDocument().insertString(2, "xxx");
assertEquals(2, marker.getStartOffset());
assertEquals(2, marker.getEndOffset());
assertFalse(marker.isValid());
}
public void testInsertAfterEnd() throws Exception {
RangeMarker marker = createMarker("0123456789", 2, 5);
marker.getDocument().insertString(6, "xxx");
assertEquals(2, marker.getStartOffset());
assertEquals(5, marker.getEndOffset());
assertTrue(marker.isValid());
}
public void testDeleteEndPart() throws Exception {
RangeMarker marker = createMarker("0123456789", 2, 5);
marker.getDocument().deleteString(4, 6);
assertValidMarker(marker, 2, 4);
}
public void testDeleteStartPart() throws Exception {
RangeMarker marker = createMarker("0123456789", 2, 5);
marker.getDocument().deleteString(0, 4);
assertValidMarker(marker, 0, 1);
}
public void testReplaceStartPartInvalid() throws Exception {
RangeMarker marker = createMarker("0123456789", 2, 5);
marker.getDocument().replaceString(0, 4, "xxxx");
assertValidMarker(marker, 4, 5);
}
public void testDeleteFirstChar() throws Exception {
RangeMarker marker = createMarker("0123456789", 0, 5);
marker.getDocument().deleteString(0, 1);
assertValidMarker(marker, 0, 4);
}
public void testInsertBeforeStart() throws Exception {
RangeMarker marker = createMarker("0123456789", 2, 5);
marker.getDocument().insertString(0, "xxx");
assertEquals(5, marker.getStartOffset());
assertEquals(8, marker.getEndOffset());
assertTrue(marker.isValid());
}
public void testInsertIntoStart() throws Exception {
RangeMarker marker = createMarker("0123456789", 2, 5);
marker.getDocument().insertString(2, "xxx");
assertValidMarker(marker, 5, 8);
}
public void testInsertIntoStartExpandToLeft() throws Exception {
RangeMarker marker = createMarker("0123456789", 2, 5);
marker.setGreedyToLeft(true);
marker.getDocument().insertString(2, "xxx");
assertEquals(2, marker.getStartOffset());
assertEquals(8, marker.getEndOffset());
assertTrue(marker.isValid());
}
public void testInsertIntoEnd() throws Exception {
RangeMarker marker = createMarker("0123456789", 2, 5);
marker.getDocument().insertString(5, "xxx");
assertEquals(2, marker.getStartOffset());
assertEquals(5, marker.getEndOffset());
assertTrue(marker.isValid());
}
public void testInsertIntoEndExpandRight() throws Exception {
RangeMarker marker = createMarker("0123456789", 2, 5);
marker.setGreedyToRight(true);
marker.getDocument().insertString(5, "xxx");
assertEquals(2, marker.getStartOffset());
assertEquals(8, marker.getEndOffset());
assertTrue(marker.isValid());
}
public void testNoNegative() throws Exception {
RangeMarker marker = createMarker("package safd;\n\n[import javax.swing.JPanel;]\nimport java.util.ArrayList;\n\nclass T{}");
marker.getDocument()
.replaceString(15, 15 + "import javax.swing.JPanel;\nimport java.util.ArrayList;".length(), "import java.util.ArrayList;");
assertEquals(15, marker.getStartOffset());
}
public void testReplaceRightIncludingFirstChar() throws Exception {
String s = "12345\n \n12345";
RangeMarker marker = createMarker(s, 6, 8);
marker.getDocument().replaceString(0, s.length(), s.replaceAll(" ", ""));
assertValidMarker(marker, 6, 7);
}
public void testDeleteRightPart() throws Exception {
RangeMarker marker = createMarker("0123456789", 2, 5);
marker.getDocument().deleteString(4, 6);
assertValidMarker(marker, 2, 4);
}
public void testDeleteRightPart2() throws Exception {
RangeMarker marker = createMarker("0123456789", 2, 5);
marker.getDocument().deleteString(4, 5);
assertValidMarker(marker, 2, 4);
}
public void testReplaceRightPartInvalid() throws Exception {
RangeMarker marker = createMarker("0123456789", 2, 5);
marker.getDocument().replaceString(4, 6, "xxx");
assertValidMarker(marker, 2, 4);
}
public void testDeleteWholeRange() throws Exception {
RangeMarker marker = createMarker("0123456789", 2, 5);
marker.getDocument().deleteString(1, 6);
assertFalse(marker.isValid());
}
public void testDeleteExactRange() throws Exception {
RangeMarker marker = createMarker("0123456789", 2, 5);
marker.getDocument().deleteString(2, 5);
assertValidMarker(marker, 2, 2);
}
public void testDeleteJustBeforeStart() throws Exception {
RangeMarker marker = createMarker("0123456789", 2, 5);
marker.getDocument().deleteString(0, 2);
assertValidMarker(marker, 0, 3);
}
public void testDeleteRightAfterEnd() throws Exception {
RangeMarker marker = createMarker("0123456789", 2, 2);
marker.getDocument().deleteString(2, 5);
assertValidMarker(marker, 2, 2);
}
public void testReplacementWithOldTextOverlap() throws Exception {
RangeMarker marker = createMarker("0123456789", 2, 5);
marker.getDocument().replaceString(0, 10, "0123456789");
assertValidMarker(marker, 2, 5);
}
// Psi -> Document synchronization
public void testPsi2Doc1() throws Exception {
StringBuilder buffer = new StringBuilder("0123456789");
RangeMarker marker = createMarker(buffer.toString(), 2, 5);
synchronizer.startTransaction(getProject(), document, psiFile);
synchronizer.insertString(document, 3, "a");
buffer.insert(3, "a");
synchronizer.commitTransaction(this.document);
assertEquals(buffer.toString(), document.getText());
assertValidMarker(marker, 2, 6);
}
public void testDocSynchronizerPrefersLineBoundaryChanges() throws Exception {
String text = "import java.awt.List;\n" +
"[import java.util.ArrayList;\n]" +
"import java.util.HashMap;\n" +
"import java.util.Map;";
RangeMarker marker = createMarker(text);
synchronizer.startTransaction(getProject(), document, psiFile);
String newText = StringUtil.replaceSubstring(document.getText(), TextRange.create(marker), "");
synchronizer.replaceString(document, 0, document.getTextLength(), newText);
final List<DocumentEvent> events = new ArrayList<DocumentEvent>();
document.addDocumentListener(new DocumentAdapter() {
@Override
public void documentChanged(DocumentEvent e) {
events.add(e);
}
});
synchronizer.commitTransaction(document);
assertEquals(newText, document.getText());
DocumentEvent event = assertOneElement(events);
assertEquals("DocumentEventImpl[myOffset=22, myOldLength=28, myNewLength=0, myOldString='import java.util.ArrayList;\n', myNewString=''].", event.toString());
}
public void testPsi2DocReplaceAfterAdd() throws Exception {
StringBuilder buffer = new StringBuilder("0123456789");
RangeMarker marker = createMarker(buffer.toString(), 2, 5);
synchronizer.startTransaction(getProject(), document, psiFile);
synchronizer.insertString(document, 1, "a");
buffer.insert(1, "a");
synchronizer.replaceString(document, 3, 4, "a");
buffer.replace(3, 4, "a");
synchronizer.commitTransaction(document);
assertEquals(buffer.toString(), document.getText());
assertValidMarker(marker, 3, 6);
}
public void testPsi2DocMergeReplaceAfterAdd() throws Exception {
StringBuilder buffer = new StringBuilder("0123456789");
RangeMarker marker = createMarker(buffer.toString(), 2, 5);
synchronizer.startTransaction(getProject(), document, psiFile);
synchronizer.insertString(document, 1, "a");
buffer.insert(1, "a");
synchronizer.replaceString(document, 3, 4, "a");
buffer.replace(3, 4, "a");
synchronizer.replaceString(document, 3, 5, "bb");
buffer.replace(3, 5, "bb");
final PsiToDocumentSynchronizer.DocumentChangeTransaction transaction = synchronizer.getTransaction(document);
final Set<Pair<PsiToDocumentSynchronizer.MutableTextRange, StringBuffer>> affectedFragments = transaction.getAffectedFragments();
assertEquals(affectedFragments.size(), 2);
synchronizer.commitTransaction(document);
assertEquals(buffer.toString(), document.getText());
assertValidMarker(marker, 3, 6);
}
public void testPsi2DocMergeReplaceWithMultipleAdditions() throws Exception {
StringBuilder buffer = new StringBuilder("0123456789");
RangeMarker marker = createMarker(buffer.toString(), 2, 5);
synchronizer.startTransaction(getProject(), document, psiFile);
synchronizer.replaceString(document, 0, 10, "0");
buffer.replace(0, 10, "0");
for (int i = 1; i < 10; i++) {
synchronizer.insertString(document, i, "" + i);
buffer.insert(i, "" + i);
}
final PsiToDocumentSynchronizer.DocumentChangeTransaction transaction = synchronizer.getTransaction(document);
final Set<Pair<PsiToDocumentSynchronizer.MutableTextRange, StringBuffer>> affectedFragments = transaction.getAffectedFragments();
assertEquals(1, affectedFragments.size());
synchronizer.commitTransaction(document);
assertEquals(buffer.toString(), document.getText());
assertValidMarker(marker, 2, 5);
}
public void testPsi2DocMergeMultipleAdditionsWithReplace() throws Exception {
StringBuilder buffer = new StringBuilder("0123456789");
RangeMarker marker = createMarker(buffer.toString(), 2, 5);
synchronizer.startTransaction(getProject(), document, psiFile);
final PsiToDocumentSynchronizer.DocumentChangeTransaction transaction = synchronizer.getTransaction(document);
final Set<Pair<PsiToDocumentSynchronizer.MutableTextRange, StringBuffer>> affectedFragments = transaction.getAffectedFragments();
for (int i = 0; i < 10; i++) {
synchronizer.insertString(document, i, "" + i);
buffer.insert(i, "" + i);
}
assertEquals(1, affectedFragments.size());
synchronizer.replaceString(document, 0, 20, "0123456789");
buffer.replace(0, 20, "0123456789");
assertEquals(1, affectedFragments.size());
synchronizer.commitTransaction(document);
assertEquals(buffer.toString(), document.getText());
assertValidMarker(marker, 2, 5);
}
public void testPsi2DocSurround() throws Exception {
StringBuilder buffer = new StringBuilder("0123456789");
RangeMarker marker = createMarker(buffer.toString(), 2, 5);
synchronizer.startTransaction(getProject(), document, psiFile);
synchronizer.replaceString(document, 3, 5, "3a4");
buffer.replace(3, 5, "3a4");
synchronizer.insertString(document, 3, "b");
buffer.insert(3, "b");
synchronizer.insertString(document, 7, "d");
buffer.insert(7, "d");
final PsiToDocumentSynchronizer.DocumentChangeTransaction transaction = synchronizer.getTransaction(document);
final Set<Pair<PsiToDocumentSynchronizer.MutableTextRange, StringBuffer>> affectedFragments = transaction.getAffectedFragments();
assertEquals(3, affectedFragments.size());
synchronizer.commitTransaction(document);
assertEquals(buffer.toString(), document.getText());
assertValidMarker(marker, 2, 7);
}
public void testPsi2DocForwardRangesChanges() throws Exception {
StringBuilder buffer = new StringBuilder("0123456789");
RangeMarker marker = createMarker(buffer.toString(), 2, 5);
synchronizer.startTransaction(getProject(), document, psiFile);
synchronizer.replaceString(document, 4, 5, "3a4");
buffer.replace(4, 5, "3a4");
synchronizer.insertString(document, 7, "b");
buffer.insert(7, "b");
synchronizer.insertString(document, 1, "b");
buffer.insert(1, "b");
synchronizer.commitTransaction(document);
assertEquals(buffer.toString(), document.getText());
assertValidMarker(marker, 3, 8);
}
private static void assertValidMarker(@NotNull RangeMarker marker, int start, int end) {
assertTrue(marker.isValid());
assertEquals(start, marker.getStartOffset());
assertEquals(end, marker.getEndOffset());
}
public void testNested() {
RangeMarker marker1 = createMarker("0[12345678]9");
Document document = marker1.getDocument();
RangeMarker marker2 = document.createRangeMarker(2, 5);
RangeMarker marker3 = document.createRangeMarker(3, 4);
document.insertString(0, "x");
assertEquals(2, marker1.getStartOffset());
assertEquals(3, marker2.getStartOffset());
assertEquals(4, marker3.getStartOffset());
}
public void testNestedAfter() {
RangeMarker marker1 = createMarker("0[12345678]90123");
Document document = marker1.getDocument();
RangeMarker marker2 = document.createRangeMarker(2, 5);
RangeMarker marker3 = document.createRangeMarker(3, 4);
document.insertString(10, "x");
assertEquals(1, marker1.getStartOffset());
assertEquals(2, marker2.getStartOffset());
assertEquals(3, marker3.getStartOffset());
}
public void testNested3() {
RangeMarker marker1 = createMarker("01[23]4567890123");
DocumentEx document = (DocumentEx)marker1.getDocument();
RangeMarker marker2 = document.createRangeMarker(9, 11);
RangeMarker marker3 = document.createRangeMarker(1, 12);
marker3.dispose();
document.deleteString(marker1.getEndOffset(), marker2.getStartOffset());
}
public void testBranched() {
RangeMarker marker1 = createMarker("01234567890123456", 0, 1);
DocumentEx document = (DocumentEx)marker1.getDocument();
RangeMarker marker2 = document.createRangeMarker(2, 3);
RangeMarker marker3 = document.createRangeMarker(4, 5);
RangeMarker marker4 = document.createRangeMarker(6, 7);
RangeMarker marker5 = document.createRangeMarker(8, 9);
RangeMarker marker6 = document.createRangeMarker(10, 11);
RangeMarker marker7 = document.createRangeMarker(12, 13);
RangeMarker marker8 = document.createRangeMarker(14, 15);
document.deleteString(1, 2);
}
public void testDevourMarkerWithDeletion() {
RangeMarker marker1 = createMarker("012345[67890123456]7");
DocumentEx document = (DocumentEx)marker1.getDocument();
document.deleteString(1, document.getTextLength());
}
public void testLL() {
RangeMarker marker1 = createMarker("012345678901234567", 5,6);
DocumentEx document = (DocumentEx)marker1.getDocument();
document.createRangeMarker(4, 5);
document.createRangeMarker(6, 7);
document.createRangeMarker(0, 4);
document.deleteString(1, 2);
document.createRangeMarker(0, 7);
document.createRangeMarker(0, 7);
}
public void testSwap() {
RangeMarkerEx marker1 = createMarker("012345678901234567", 5,6);
DocumentEx document = (DocumentEx)marker1.getDocument();
document.createRangeMarker(3, 5);
document.createRangeMarker(6, 7);
document.createRangeMarker(4, 4);
marker1.dispose();
}
public void testX() {
RangeMarkerEx marker1 = createMarker(StringUtil.repeatSymbol(' ', 10), 3,6);
DocumentEx document = (DocumentEx)marker1.getDocument();
document.createRangeMarker(2, 3);
document.createRangeMarker(3, 8);
document.createRangeMarker(7, 9);
RangeMarkerEx r1 = (RangeMarkerEx)document.createRangeMarker(6, 8);
r1.dispose();
marker1.dispose();
}
private static List<RangeMarker> add(DocumentEx document, int... offsets) {
List<RangeMarker> result = new ArrayList<RangeMarker>();
for (int i=0; i<offsets.length; i+=2) {
int start = offsets[i];
int end = offsets[i+1];
RangeMarker m = document.createRangeMarker(start, end);
result.add(m);
}
return result;
}
private static void delete(List<RangeMarker> mm, int... indexes) {
for (int index : indexes) {
RangeMarker m = mm.get(index);
m.dispose();
}
}
public void testX2() {
DocumentEx document = (DocumentEx)EditorFactory.getInstance().createDocument(StringUtil.repeatSymbol(' ', 10));
List<RangeMarker> mm =
add(document, 2,9, 0,0, 7,7
);
delete(mm, 0);
}
public void testX3() {
DocumentEx document = (DocumentEx)EditorFactory.getInstance().createDocument(StringUtil.repeatSymbol(' ', 10));
List<RangeMarker> mm =
add(document, 1,9, 8,8, 8,8, 0,5, 4,5
);
delete(mm, 0);
}
public void _testRandomAddRemove() {
int N = 100;
for (int ti=0; ;ti++) {
if (ti%10000 ==0) System.out.println(ti);
DocumentEx document = (DocumentEx)EditorFactory.getInstance().createDocument(StringUtil.repeatSymbol(' ', N));
Random gen = new Random();
List<Pair<RangeMarker, TextRange>> adds = new ArrayList<Pair<RangeMarker, TextRange>>();
List<Pair<RangeMarker, TextRange>> dels = new ArrayList<Pair<RangeMarker, TextRange>>();
try {
for (int i = 0; i < 30; i++) {
int x = gen.nextInt(N);
int y = x + gen.nextInt(N - x);
if (gen.nextBoolean()) {
x = 0;
y = document.getTextLength();
}
RangeMarkerEx r = (RangeMarkerEx)document.createRangeMarker(x, y);
adds.add(Pair.create((RangeMarker)r, TextRange.create(r)));
}
List<Pair<RangeMarker, TextRange>> candidates = new ArrayList<Pair<RangeMarker, TextRange>>(adds);
while (!candidates.isEmpty()) {
int size = candidates.size();
int x = gen.nextInt(size);
Pair<RangeMarker, TextRange> c = candidates.remove(x);
RangeMarkerEx r = (RangeMarkerEx)c.first;
assertEquals(size-1, candidates.size());
dels.add(c);
r.dispose();
}
}
catch (AssertionError e) {
String s= "adds: ";
for (Pair<RangeMarker, TextRange> c : adds) {
TextRange t = c.second;
s += t.getStartOffset() + "," + t.getEndOffset() + ", ";
}
s += "\ndels: ";
for (Pair<RangeMarker, TextRange> c : dels) {
int index = adds.indexOf(c);
assertSame(c, adds.get(index));
s += index + ", ";
}
System.err.println(s);
throw e;
}
}
}
private static void edit(DocumentEx document, int... offsets) {
for (int i = 0; i < offsets.length; i+=3) {
int offset = offsets[i];
int oldlength = offsets[i+1];
int newlength = offsets[i+2];
document.replaceString(offset, offset + oldlength, StringUtil.repeatSymbol(' ', newlength));
}
}
public void testE1() {
DocumentEx document = (DocumentEx)EditorFactory.getInstance().createDocument(StringUtil.repeatSymbol(' ', 10));
List<RangeMarker> mm =
add(document, 3,5, 0,1, 9,9
);
edit(document, 3,6,0);
delete(mm, 0);
}
public void testE2() {
DocumentEx document = (DocumentEx)EditorFactory.getInstance().createDocument(StringUtil.repeatSymbol(' ', 10));
List<RangeMarker> mm =
add(document, 0,3, 6,9, 8,8
);
edit(document, 0,3,0);
delete(mm, 0);
}
public void testE3() {
DocumentEx document = (DocumentEx)EditorFactory.getInstance().createDocument(StringUtil.repeatSymbol(' ', 10));
List<RangeMarker> mm =
add(document, 4,5, 6,8, 3,4, 4,9, 2,9
);
edit(document, 4,6,0);
delete(mm, 0);
}
public void testE4() {
DocumentEx document = (DocumentEx)EditorFactory.getInstance().createDocument(StringUtil.repeatSymbol(' ', 10));
List<RangeMarker> mm =
add(document, 3,5, 5,6, 4,8, 6,9, 8,9
);
edit(document, 6,0,0, 3,0,2);
delete(mm, 1,0);
}
public void testE5() {
DocumentEx document = (DocumentEx)EditorFactory.getInstance().createDocument(StringUtil.repeatSymbol(' ', 10));
List<RangeMarker> mm =
add(document, 9,9, 4,4, 1,7, 7,7, 4,7
);
edit(document, 1,5,0);
delete(mm, 3);
}
public void testE6() {
DocumentEx document = (DocumentEx)EditorFactory.getInstance().createDocument(StringUtil.repeatSymbol(' ', 10));
List<RangeMarker> mm =
add(document, 4,8, 4,4, 4,9, 0,2, 6,8
);
edit(document, 3,2,0);
}
public void testE7() {
DocumentEx document = (DocumentEx)EditorFactory.getInstance().createDocument(StringUtil.repeatSymbol(' ', 10));
List<RangeMarker> mm =
add(document, 6,7, 0,3, 3,6, 5,9, 2,9
);
edit(document, 5,2,0);
}
public void testE8() {
DocumentEx document = (DocumentEx)EditorFactory.getInstance().createDocument(StringUtil.repeatSymbol(' ', 10));
List<RangeMarker> mm =
add(document, 5,5, 8,8, 1,3, 3,9
);
edit(document, 4,3,0);
}
public void testE9() {
DocumentEx document = (DocumentEx)EditorFactory.getInstance().createDocument(StringUtil.repeatSymbol(' ', 10));
List<RangeMarker> mm =
add(document, 4,5, 9,9, 1,2, 0,3
);
edit(document, 0,3,0);
}
public void testE10() {
DocumentEx document = (DocumentEx)EditorFactory.getInstance().createDocument(StringUtil.repeatSymbol(' ', 10));
List<RangeMarker> mm =
add(document, 9,9, 6,8, 8,8, 5,9
);
edit(document, 2,6,0, 2,0,4);
}
public void testE11() {
DocumentEx document = (DocumentEx)EditorFactory.getInstance().createDocument(StringUtil.repeatSymbol(' ', 10));
List<RangeMarker> mm =
add(document, 9,9, 7,7, 1,6, 3,7
);
//edit(document, 0,0,0);
delete(mm, 1);
}
public void testE12() {
DocumentEx document = (DocumentEx)EditorFactory.getInstance().createDocument(StringUtil.repeatSymbol(' ', 10));
List<RangeMarker> mm =
add(document, 3,3, 8,8, 5,5, 5,6
);
edit(document, 2,0,2);
delete(mm, 2);
}
public void testE13() {
DocumentEx document = (DocumentEx)EditorFactory.getInstance().createDocument(StringUtil.repeatSymbol(' ', 10));
List<RangeMarker> mm = add(document, 5,9, 9,9, 7,7, 6,8);
edit(document, 2,1,0);
delete(mm, 0, 2);
}
public void testE14() {
DocumentEx document = (DocumentEx)EditorFactory.getInstance().createDocument(StringUtil.repeatSymbol(' ', 100));
List<RangeMarker> mm = add(document, 6,11, 2,13, 17,17, 13,19, 2,3, 9,10, 10,11, 14,14, 1,3, 4,12, 14,15, 3,10, 14,14, 4,4, 4,8, 6,14, 8,16, 2,12, 11,19, 10,13
);
edit(document, 19,0,0, 7,3,0, 16,0,3);
}
public void testE15() {
DocumentEx document = (DocumentEx)EditorFactory.getInstance().createDocument(StringUtil.repeatSymbol(' ', 100));
List<RangeMarker> mm = add(document, 90,93, 0,9, 44,79, 4,48, 44,99, 53,64, 59,82, 12,99, 81,86, 8,40, 24,55, 32,50, 74,79, 14,94, 7,14
);
edit(document, 34,0,4, 99,0,3);
}
public void testE16() {
DocumentEx document = (DocumentEx)EditorFactory.getInstance().createDocument(StringUtil.repeatSymbol(' ', 100));
List<RangeMarker> mm = add(document, 29,63, 47,52, 72,86, 19,86, 13,55, 18,57, 92,95, 83,99, 41,80, 53,85, 10,30, 28,44, 23,32, 70,95, 14,28
);
edit(document, 67,5,0, 1,0,4);
delete(mm, 11);
}
public void testE17() {
DocumentEx document = (DocumentEx)EditorFactory.getInstance().createDocument(StringUtil.repeatSymbol(' ', 100));
List<RangeMarker> mm = add(document, 15,85, 79,88, 90,94, 43,67, 54,89, 81,98, 1,34, 58,93, 22,23, 44,45, 63,84, 45,76, 58,87, 40,59, 5,81, 95,95, 12,61, 52,65, 80,95, 6,16, 7,67, 59,63, 91,96, 99,99, 50,96, 72,78, 78,78, 85,85, 5,51, 90,91
);
edit(document, 20,26,0, 15,0,4, 64,4,0);
}
public void testRandomEdit_NoCommand() {
final int N = 100;
final Random gen = new Random();
int N_TRIES = Timings.adjustAccordingToMySpeed(7000, false);
System.out.println("N_TRIES = " + N_TRIES);
DocumentEx document = null;
for (int tryn=0; tryn < N_TRIES;tryn++) {
((UndoManagerImpl)UndoManager.getInstance(getProject())).flushCurrentCommandMerger();
((UndoManagerImpl)UndoManager.getGlobalInstance()).flushCurrentCommandMerger();
if (document != null) {
((UndoManagerImpl)UndoManager.getInstance(getProject())).clearUndoRedoQueueInTests(document);
((UndoManagerImpl)UndoManager.getGlobalInstance()).clearUndoRedoQueueInTests(document);
}
if (tryn % 10000 == 0) {
System.out.println(tryn);
}
document = (DocumentEx)EditorFactory.getInstance().createDocument(StringUtil.repeatSymbol(' ', N));
final DocumentEx finalDocument = document;
new WriteCommandAction(getProject()) {
@Override
protected void run(Result result) throws Exception {
List<Pair<RangeMarker, TextRange>> adds = new ArrayList<Pair<RangeMarker, TextRange>>();
List<Pair<RangeMarker, TextRange>> dels = new ArrayList<Pair<RangeMarker, TextRange>>();
List<Trinity<Integer, Integer, Integer>> edits = new ArrayList<Trinity<Integer, Integer, Integer>>();
try {
for (int i = 0; i < 30; i++) {
int x = gen.nextInt(N);
int y = x + gen.nextInt(N - x);
RangeMarkerEx r = (RangeMarkerEx)finalDocument.createRangeMarker(x, y);
adds.add(Pair.create((RangeMarker)r, TextRange.create(r)));
}
for (int i = 0; i < 10; i++) {
int offset = gen.nextInt(finalDocument.getTextLength());
if (gen.nextBoolean()) {
int length = gen.nextInt(5);
edits.add(Trinity.create(offset, 0, length));
finalDocument.insertString(offset, StringUtil.repeatSymbol(' ', length));
}
else {
int length = gen.nextInt(finalDocument.getTextLength() - offset);
edits.add(Trinity.create(offset, length, 0));
finalDocument.deleteString(offset, offset + length);
}
}
List<Pair<RangeMarker, TextRange>> candidates = new ArrayList<Pair<RangeMarker, TextRange>>(adds);
while (!candidates.isEmpty()) {
int size = candidates.size();
int x = gen.nextInt(size);
Pair<RangeMarker, TextRange> c = candidates.remove(x);
RangeMarkerEx r = (RangeMarkerEx)c.first;
assertEquals(size - 1, candidates.size());
dels.add(c);
r.dispose();
}
}
catch (AssertionError e) {
String s = "adds: ";
for (Pair<RangeMarker, TextRange> c : adds) {
TextRange t = c.second;
s += t.getStartOffset() + "," + t.getEndOffset() + ", ";
}
s += "\nedits: ";
for (Trinity<Integer, Integer, Integer> edit : edits) {
s += edit.first + "," + edit.second + "," + edit.third + ", ";
}
s += "\ndels: ";
for (Pair<RangeMarker, TextRange> c : dels) {
int index = adds.indexOf(c);
assertSame(c, adds.get(index));
s += index + ", ";
}
System.err.println(s);
throw e;
}
}
}.execute();
}
}
private RangeMarkerEx createMarker(String text, final int start, final int end) {
psiFile = createFile("x.txt", text);
return createMarker(psiFile, start, end);
}
private RangeMarkerEx createMarker(PsiFile psiFile, final int start, final int end) {
document = documentManager.getDocument(psiFile);
return (RangeMarkerEx)document.createRangeMarker(start, end);
}
private RangeMarkerEx createMarker(@NonNls String string) {
int start = string.indexOf('[');
assertTrue(start != -1);
string = string.replace("[", "");
int end = string.indexOf(']');
assertTrue(end != -1);
string = string.replace("]", "");
return createMarker(string, start, end);
}
public void testRangeMarkersAreWeakReferenced_NoVerify() throws Exception {
final Document document = EditorFactory.getInstance().createDocument("[xxxxxxxxxxxxxx]");
for (int i = 0; i < 10; i++) {
document.createRangeMarker(0, document.getTextLength());
}
LeakHunter.checkLeak(document, RangeMarker.class);
}
public void testRangeMarkersAreLazyCreated() throws Exception {
final Document document = EditorFactory.getInstance().createDocument("[xxxxxxxxxxxxxx]");
RangeMarker m1 = document.createRangeMarker(2, 4);
RangeMarker m2 = document.createRangeMarker(2, 4);
assertEquals(2, ((DocumentImpl)document).getRangeMarkersSize());
assertEquals(1, ((DocumentImpl)document).getRangeMarkersNodeSize());
RangeMarker m3 = document.createRangeMarker(2, 5);
assertEquals(2, ((DocumentImpl)document).getRangeMarkersNodeSize());
document.deleteString(4,5);
assertTrue(m1.isValid());
assertTrue(m2.isValid());
assertTrue(m3.isValid());
assertEquals(1, ((DocumentImpl)document).getRangeMarkersNodeSize());
m1.setGreedyToLeft(true);
assertTrue(m1.isValid());
assertEquals(3, ((DocumentImpl)document).getRangeMarkersSize());
assertEquals(2, ((DocumentImpl)document).getRangeMarkersNodeSize());
m3.dispose();
assertTrue(m1.isValid());
assertTrue(m2.isValid());
assertFalse(m3.isValid());
assertEquals(2, ((DocumentImpl)document).getRangeMarkersSize());
assertEquals(2, ((DocumentImpl)document).getRangeMarkersNodeSize());
}
public void testRangeHighlightersRecreateBug() throws Exception {
Document document = EditorFactory.getInstance().createDocument("[xxxxxxxxxxxxxx]");
MarkupModel markupModel = DocumentMarkupModel.forDocument(document, ourProject, true);
for (int i=0; i<2; i++) {
RangeMarker m = markupModel.addRangeHighlighter(1, 6, 0, null, HighlighterTargetArea.EXACT_RANGE);
RangeMarker m2 = markupModel.addRangeHighlighter(2, 7, 0, null, HighlighterTargetArea.EXACT_RANGE);
RangeMarker m3 = markupModel.addRangeHighlighter(1, 6, 0, null, HighlighterTargetArea.EXACT_RANGE);
markupModel.removeAllHighlighters();
}
}
public void testValidationBug() throws Exception {
Document document = EditorFactory.getInstance().createDocument("[xxxxxxxxxxxxxx]");
final Editor editor = EditorFactory.getInstance().createEditor(document);
try {
final FoldRegion[] fold = new FoldRegion[1];
editor.getFoldingModel().runBatchFoldingOperation(new Runnable() {
@Override
public void run() {
fold[0] = editor.getFoldingModel().addFoldRegion(0, 2, "");
}
});
RangeMarker marker = document.createRangeMarker(0, 2);
document.deleteString(1,2);
assertTrue(marker.isValid());
//assertFalse(fold[0].isValid());
}
finally {
EditorFactory.getInstance().releaseEditor(editor);
}
}
public void testPersistent() throws Exception {
String text = "xxx\nzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz";
Document document = EditorFactory.getInstance().createDocument(text);
int startOffset = text.indexOf('z');
int endOffset = text.lastIndexOf('z');
RangeMarker marker = document.createRangeMarker(startOffset, endOffset, true);
document.replaceString(startOffset+1, endOffset-1, "ccc");
assertTrue(marker.isValid());
}
public void testMoveTextRetargetsMarkers() throws Exception {
RangeMarkerEx marker1 = createMarker("01234567890", 1, 3);
DocumentEx document = (DocumentEx)marker1.getDocument();
RangeMarker marker2 = document.createRangeMarker(2, 4);
document.moveText(0, 5, 8);
assertEquals("56701234890", document.getText());
assertValidMarker(marker1, 4, 6);
assertValidMarker(marker2, 5, 7);
}
public void testMoveTextToTheBeginningRetargetsMarkers() throws Exception {
RangeMarkerEx marker1 = createMarker("01234567890", 5, 5);
DocumentEx document = (DocumentEx)marker1.getDocument();
RangeMarker marker2 = document.createRangeMarker(5, 7);
document.moveText(4, 7, 1);
assertEquals("04561237890", document.getText());
assertValidMarker(marker1, 2, 2);
assertValidMarker(marker2, 2, 4);
}
public void testRangeHighlighterDisposeVsRemoveAllConflict() throws Exception {
Document document = EditorFactory.getInstance().createDocument("[xxxxxxxxxxxxxx]");
MarkupModel markupModel = DocumentMarkupModel.forDocument(document, ourProject, true);
RangeMarker m = markupModel.addRangeHighlighter(1, 6, 0, null, HighlighterTargetArea.EXACT_RANGE);
assertTrue(m.isValid());
markupModel.removeAllHighlighters();
assertFalse(m.isValid());
assertEmpty(markupModel.getAllHighlighters());
m.dispose();
assertFalse(m.isValid());
}
public void testRangeHighlighterLinesInRangeForLongLinePerformance() throws Exception {
final int N = 50000;
Document document = EditorFactory.getInstance().createDocument(StringUtil.repeatSymbol('x', 2 * N));
final MarkupModelEx markupModel = (MarkupModelEx)DocumentMarkupModel.forDocument(document, ourProject, true);
for (int i=0; i<N-1;i++) {
markupModel.addRangeHighlighter(2*i, 2*i+1, 0, null, HighlighterTargetArea.EXACT_RANGE);
}
markupModel.addRangeHighlighter(N / 2, N / 2 + 1, 0, null, HighlighterTargetArea.LINES_IN_RANGE);
PlatformTestUtil.startPerformanceTest("slow highlighters lookup", (int)(N*Math.log(N)/1000), new ThrowableRunnable() {
@Override
public void run() {
List<RangeHighlighterEx> list = new ArrayList<RangeHighlighterEx>();
CommonProcessors.CollectProcessor<RangeHighlighterEx> coll = new CommonProcessors.CollectProcessor<RangeHighlighterEx>(list);
for (int i=0; i<N-1;i++) {
list.clear();
markupModel.processRangeHighlightersOverlappingWith(2*i, 2*i+1, coll);
assertEquals(2, list.size()); // 1 line plus one exact range marker
}
}
}).assertTiming();
}
public void testRangeHighlighterIteratorOrder() throws Exception {
Document document = EditorFactory.getInstance().createDocument("1234567890");
final MarkupModelEx markupModel = (MarkupModelEx)DocumentMarkupModel.forDocument(document, ourProject, true);
RangeHighlighter exact = markupModel.addRangeHighlighter(3, 6, 0, null, HighlighterTargetArea.EXACT_RANGE);
RangeHighlighter line = markupModel.addRangeHighlighter(4, 5, 0, null, HighlighterTargetArea.LINES_IN_RANGE);
List<RangeHighlighter> list = new ArrayList<RangeHighlighter>();
markupModel.processRangeHighlightersOverlappingWith(2, 9, new CommonProcessors.CollectProcessor<RangeHighlighter>(list));
assertEquals(Arrays.asList(line, exact), list);
}
public void testLazyRangeMarkers() {
psiFile = createFile("x.txt", "xxx");
LazyRangeMarkerFactoryImpl factory = (LazyRangeMarkerFactoryImpl)LazyRangeMarkerFactory.getInstance(getProject());
VirtualFile virtualFile = psiFile.getVirtualFile();
LazyRangeMarkerFactoryImpl.LazyMarker marker = (LazyRangeMarkerFactoryImpl.LazyMarker)factory.createRangeMarker(virtualFile, 0);
WeakList<LazyRangeMarkerFactoryImpl.LazyMarker> markers = LazyRangeMarkerFactoryImpl.getMarkers(virtualFile);
assertSame(marker, assertOneElement(markers));
assertFalse(marker.isDelegated());
assertTrue(marker.isValid());
assertEquals(0, marker.getStartOffset());
assertFalse(marker.isDelegated());
marker.dispose();
assertFalse(marker.isValid());
assertEmpty(LazyRangeMarkerFactoryImpl.getMarkers(virtualFile));
marker = (LazyRangeMarkerFactoryImpl.LazyMarker)factory.createRangeMarker(virtualFile, 0);
assertFalse(marker.isDelegated());
assertTrue(marker.isValid());
assertEquals(0, marker.getStartOffset());
assertFalse(marker.isDelegated());
Document document = marker.getDocument();
document.insertString(2, "yyy");
assertTrue(marker.isDelegated());
assertTrue(marker.isValid());
assertEquals(0, marker.getStartOffset());
assertEmpty(LazyRangeMarkerFactoryImpl.getMarkers(virtualFile));
marker.dispose();
assertEmpty(LazyRangeMarkerFactoryImpl.getMarkers(virtualFile));
}
}
| a test case for range marker invalidation failure
| platform/platform-tests/testSrc/com/intellij/openapi/editor/impl/RangeMarkerTest.java | a test case for range marker invalidation failure | <ide><path>latform/platform-tests/testSrc/com/intellij/openapi/editor/impl/RangeMarkerTest.java
<ide> assertTrue(marker.isValid());
<ide> }
<ide>
<add> public void testPersistentMarkerDoesntImpactNormalMarkers() {
<add> Document doc = new DocumentImpl("text");
<add> RangeMarker normal = doc.createRangeMarker(1, 3);
<add> RangeMarker persistent = doc.createRangeMarker(1, 3, true);
<add>
<add> doc.replaceString(0, 4, "before\ntext\nafter");
<add>
<add> assertTrue(persistent.isValid());
<add> assertFalse(normal.isValid());
<add> }
<add>
<ide> public void testMoveTextRetargetsMarkers() throws Exception {
<ide> RangeMarkerEx marker1 = createMarker("01234567890", 1, 3);
<ide> DocumentEx document = (DocumentEx)marker1.getDocument(); |
|
JavaScript | mit | 33ea92f9263332d266b0664c2d8a421a925f9752 | 0 | florianajir/theplacetube,florianajir/theplacetube | 'use strict';
const google = require('googleapis');
const youtube = google.youtube('v3');
const nconf = require('nconf');
nconf
.argv()
.env()
.file({file: '../config.json'});
/**
* QUOTA IMPACT: 100
*
* @param params
* @param callback
*/
exports.searchList = function(params, callback) {
youtube.search.list(
Object.assign(
{
auth: nconf.get('google_api_key'),
fields: 'items(id/videoId),nextPageToken,pageInfo',
maxResults: '50',
order: 'viewCount',
part: 'snippet',
type: 'video',
safeSearch: 'none',
videoEmbeddable: true
},
params
),
callback
);
};
/**
* QUOTA IMPACT: 5
* @param id
* @param callback
*/
exports.videosList = function(id, callback) {
youtube.videos.list(
{
auth: nconf.get('google_api_key'),
part: 'recordingDetails,snippet',
id: id
},
callback
);
}; | lib/services/youtube-search.js | 'use strict';
const google = require('googleapis');
const youtube = google.youtube('v3');
const nconf = require('nconf');
nconf
.argv()
.env()
.file({file: '../config.json'});
/**
* QUOTA IMPACT: 100
*
* @param params
* @param callback
*/
exports.searchList = function(params, callback) {
youtube.search.list(
Object.assign(
{
auth: nconf.get('google_api_key'),
fields: 'items(id/videoId),nextPageToken,pageInfo',
maxResults: '50',
order: 'rating',
part: 'snippet',
type: 'video',
safeSearch: 'none',
videoEmbeddable: true
},
params
),
callback
);
};
/**
* QUOTA IMPACT: 5
* @param id
* @param callback
*/
exports.videosList = function(id, callback) {
youtube.videos.list(
{
auth: nconf.get('google_api_key'),
part: 'recordingDetails,snippet',
id: id
},
callback
);
}; | change default order to viewCount
| lib/services/youtube-search.js | change default order to viewCount | <ide><path>ib/services/youtube-search.js
<ide> auth: nconf.get('google_api_key'),
<ide> fields: 'items(id/videoId),nextPageToken,pageInfo',
<ide> maxResults: '50',
<del> order: 'rating',
<add> order: 'viewCount',
<ide> part: 'snippet',
<ide> type: 'video',
<ide> safeSearch: 'none', |
|
Java | mit | 133c337dc171d0dccea02051e70515010d5c513c | 0 | The-Dream-Team/Tardis,The-Dream-Team/Tardis | package me.dreamteam.tardis;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Toolkit;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferStrategy;
import java.net.URL;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import org.lwjgl.Sys;
import me.dreamteam.tardis.Entity;
import me.dreamteam.tardis.ShipEntity;
import me.dreamteam.tardis.EnemyEntity;
import me.dreamteam.tardis.Utils;
import me.dreamteam.tardis.UtilsHTML;
/**
Main Class
*/
public class Game extends Canvas {
private BufferStrategy strategy;
// This provides hardware acceleration
private boolean isRunning = true;
private boolean gameStart = false;
long lastLoopTime;
private Entity ship;
private int shipS = 0;
private ArrayList entities = new ArrayList();
private ArrayList enemies = new ArrayList();
private double moveSpeed = 180;
private boolean leftPressed = false;
private boolean rightPressed = false;
private boolean logicRequiredThisLoop = false;
private boolean advanceLevel = false;
private int level = 1;
long lastFrame;
long finalTime = 0;
private String timeDisplay = "";
private String livesDisplay = "";
public int gameTime = 0;
public int gameLives = 3;
int timeMil;
long lastTime;
int SpriteLoc;
int SpriteLoc2;
int SpriteLoc3;
int tWait = 0;
int CurSprite = 1;
double curY = 0;
ImageIcon blankIcon = new ImageIcon();
Random rSpriteLoc = new Random();
public Game() {
JFrame container = new JFrame(Utils.gameName + "- " + Utils.build + Utils.version);
JPanel panel = (JPanel) container.getContentPane();
panel.setPreferredSize(new Dimension(500,650));
panel.setLayout(null);
setBounds(0,0,500,650);
panel.add(this);
setIgnoreRepaint(true);
container.setResizable(false);
container.pack();
// Window setup
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
int w = container.getSize().width;
int h = container.getSize().height;
int x = (dim.width-w)/2;
int y = (dim.height-h)/2;
container.setLocation(x, y);
container.setBackground(Color.black);
container.setVisible(true);
//What to do when user choose to close
container.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
Utils.quitGame();
}
});
ImageIcon icon = new ImageIcon(Utils.iconURL);
container.setIconImage(icon.getImage());
// Init keys
addKeyListener(new KeyInputHandler());
// create the buffering strategy for graphics
createBufferStrategy(2);
strategy = getBufferStrategy();
requestFocus();
initEntities();
titleScreen();
}
public void updateLogic() {
logicRequiredThisLoop = true;
}
/**
* Create our ship
*/
private void initEntities() {
if (shipS == 0) {
ship = new ShipEntity(this,"sprites/ship.png",220,568);
entities.add(ship);
}
if (shipS == 1) {
ship = new ShipEntity(this,"sprites/ship2.png",220,568);
entities.add(ship);
}
if (shipS == 2) {
ship = new ShipEntity(this,"sprites/ship3.png",220,568);
entities.add(ship);
}
}
private void updateEnt(){
moveSpeed = 180+(tWait*0.7);
SpriteLoc = rSpriteLoc.nextInt(200);
SpriteLoc2 = 200+rSpriteLoc.nextInt(250);
if(SpriteLoc2 < SpriteLoc+56){
if(SpriteLoc2 > SpriteLoc-56){
SpriteLoc2 = SpriteLoc-56;
if (SpriteLoc2 > 450)
SpriteLoc2 = SpriteLoc-56;
}
}
if(tWait != gameTime){
int FinalLoc;
if(gameTime >= tWait+2 && advanceLevel == false){
tWait = gameTime;
for(int i = 0; i<2; i++){
if(i==0){
FinalLoc = SpriteLoc;
}else{
FinalLoc = SpriteLoc2;
}
Entity Enemies = new EnemyEntity(this,"sprites/enemies/0"+CurSprite+".png",FinalLoc,-50);
entities.add(Enemies);
CurSprite += 1;
if (CurSprite>5)
CurSprite=1;
}
}else if (advanceLevel == true){
if(gameTime>= tWait && level ==2){
tWait = gameTime;
for(int i = 0; i<2; i++){
if(i==0){
FinalLoc = SpriteLoc;
}else{
FinalLoc = SpriteLoc2;
}
Entity Enemies = new EnemyEntity(this,"sprites/enemies/0"+CurSprite+".png",FinalLoc,-50, (tWait+(100*0.45)-30));
entities.add(Enemies);
CurSprite += 1;
if (CurSprite>5)
CurSprite=1;
}
}else if(gameTime>= tWait && level >2){
tWait = gameTime;
for(int i = 0; i<2; i++){
if(i==0){
FinalLoc = SpriteLoc;
}else{
FinalLoc = SpriteLoc2;
}
Entity Enemies = new EnemyEntity(this,"sprites/enemies/0"+CurSprite+".png",FinalLoc,-50, (tWait+(100*0.45)-30));
entities.add(Enemies);
CurSprite += 1;
if (CurSprite>5)
CurSprite=1;
}
}
}
}
}
private void startGame() {
entities.clear();
initEntities();
// reset key presses
leftPressed = false;
rightPressed = false;
//reset time
timeMil = 0;
//reset lives
gameLives = 3;
level = 1;
gameStart = true;
tWait = 0;
gameTime = 0;
finalTime = 0;
lastLoopTime = System.currentTimeMillis();
}
public void characterSelect() {
ImageIcon ship1 = new ImageIcon(Utils.ship1URL);
ImageIcon ship2 = new ImageIcon(Utils.ship2URL);
ImageIcon ship3 = new ImageIcon(Utils.ship3URL);
Utils.systemLF();
Object[] coptions = {UtilsHTML.bpcsStart + ship1 + UtilsHTML.bpcsMiddle + Utils.ship1Name + UtilsHTML.bpcsEnd,
UtilsHTML.bpcsStart + ship2 + UtilsHTML.bpcsMiddle + Utils.ship2Name + UtilsHTML.bpcsEnd,
UtilsHTML.bpcsStart + ship3 + UtilsHTML.bpcsMiddle + Utils.ship3Name + UtilsHTML.bpcsEnd};
int characterS = JOptionPane.showOptionDialog(null,
UtilsHTML.csDialog, Utils.csDialogTitle, JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.INFORMATION_MESSAGE,
blankIcon,
coptions,
coptions[0]);
if (characterS != 2 && characterS != 1 && characterS != 0) {
titleScreen();
}
if (characterS == 2) {
shipS = 2;
startGame();
}
if (characterS == 1) {
shipS = 1;
startGame();
}
if (characterS == 0) {
shipS = 0;
startGame();
}
}
public void titleScreen() {
ImageIcon icon = new ImageIcon(Utils.iconURL);
Utils.systemLF();
Object[] options = {Utils.bPlay, Utils.bQuit};
int startG = JOptionPane.showOptionDialog(null,
Utils.txtTS, Utils.tsDialogTitle,
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE,
icon,
options,
options[0]);
if (startG != 0 && startG != 1) {
Utils.quitGame();
}
if (startG == 1) {
System.exit(0);
}
if (startG == 0) {
characterSelect();
}
}
public void pauseGame() {
ImageIcon icon = new ImageIcon(Utils.iconURL);
Utils.systemLF();
gameStart = false;
long LoopTempTime = System.currentTimeMillis();
Object[] options = {Utils.bReturn, Utils.bRestart, Utils.bQuit};
int pauseG = JOptionPane.showOptionDialog(null,
Utils.txtPS, Utils.tsDialogTitle,
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE,
icon,
options,
options[0]);
double[] entCurYLoc = new double[entities.size()];
for (int i=0;i<entities.size();i++) {
Entity entity = (Entity) entities.get(i);
entCurYLoc[i] = entity.getVerticalMovement();
entity.setVerticalMovement(0);
}
if (pauseG != 1 && pauseG != 2) {
for (int i=0;i<entities.size();i++) {
Entity entity = (Entity) entities.get(i);
entity.setVerticalMovement(entCurYLoc[i]);
}
finalTime = System.currentTimeMillis() - LoopTempTime;
gameStart = true;
}
if (pauseG == 2) {
System.exit(0);
}
if (pauseG == 1) {
gameTime = 0;
characterSelect();
}
}
public void gameLoop() {
lastLoopTime = System.currentTimeMillis();
while (isRunning) {
if(gameStart == true){
long delta = (System.currentTimeMillis()-finalTime) - lastLoopTime;
finalTime = 0;
lastLoopTime = System.currentTimeMillis();
lastTime = getTime();
updateTime();
// Colour in background
Graphics2D g = (Graphics2D) strategy.getDrawGraphics();
g.setColor(Color.black);
g.fillRect(0,0,500,650);
for (int i=0;i<entities.size();i++) {
Entity entity = (Entity) entities.get(i);
entity.move(delta);
}
if (logicRequiredThisLoop) {
for (int i=0;i<entities.size();i++) {
Entity entity = (Entity) entities.get(i);
entity.doLogic();
}
logicRequiredThisLoop = false;
}
for (int i=0;i<entities.size();i++) {
Entity entity = (Entity) entities.get(i);
entity.draw(g);
}
if(gameTime >90){
advanceLevel = true;
if(gameTime > 200){
level = 3;
}else{
level = 2;
}
}
/*
* Game Text
*/
g.setColor(Color.red);
g.setFont(new Font("Century Gothic", Font.BOLD, Utils.levelFS));
g.drawString(Utils.txtLevel + level,(500-g.getFontMetrics().stringWidth(Utils.txtLevel + level))/2,18);
// Timer
g.setColor(Color.white);
g.setFont(new Font("Lucida Console", Font.BOLD, Utils.timeFS));
g.drawString(timeDisplay,(70-g.getFontMetrics().stringWidth(timeDisplay))/2,18);
g.drawString(Utils.txtTime,(70-g.getFontMetrics().stringWidth(Utils.txtTime))/2,18);
if (timeMil > 99){
gameTime = timeMil/100;
}
String convtime = String.valueOf(gameTime);
g.setColor(Color.white);
g.setFont(new Font("Lucida Console", Font.ITALIC, Utils.timeIFS));
g.drawString(timeDisplay,(175-g.getFontMetrics().stringWidth(timeDisplay))/2,18);
g.drawString(convtime,(175-g.getFontMetrics().stringWidth(convtime))/2,18);
//Lives
g.setColor(Color.white);
g.setFont(new Font("Lucida Console", Font.BOLD, Utils.livesFS));
g.drawString(livesDisplay,(875-g.getFontMetrics().stringWidth(livesDisplay))/2,18);
g.drawString(Utils.txtLives,(875-g.getFontMetrics().stringWidth(Utils.txtLives))/2,18);
String convlives = String.valueOf(gameLives);
g.setColor(Color.white);
g.setFont(new Font("Lucida Console", Font.ITALIC, Utils.livesIFS));
g.drawString(timeDisplay,(965-g.getFontMetrics().stringWidth(timeDisplay))/2,18);
g.drawString(convlives,(965-g.getFontMetrics().stringWidth(convlives))/2,18);
// Clear Graphics
g.dispose();
strategy.show();
updateEnt();
ship.setHorizontalMovement(0);
// Ship movement
if ((leftPressed) && (!rightPressed)) {
ship.setHorizontalMovement(-moveSpeed);
} else if ((rightPressed) && (!leftPressed)) {
ship.setHorizontalMovement(moveSpeed);
}
//testing for collision of player and enemy
for (int p=0;p<entities.size();p++) {
for (int s=p+1;s<entities.size();s++) {
Entity me = (Entity) entities.get(p);
Entity him = (Entity) entities.get(s);
if (me.collidesWith(him)) {
me.collidedWith(him);
him.collidedWith(me);
}
}
}
try { Thread.sleep(10); } catch (Exception e) {}
}else{
try { Thread.sleep(10); } catch (Exception e) {}
}
}
}
/**
* Update the game time
*/
public void updateTime() {
if (getTime() - lastTime > 1000) {
timeMil = 0; //reset the FPS counter
lastTime += 1000; //add one second
}
timeMil++;
}
public long getTime() {
return (Sys.getTime() * 1000) / Sys.getTimerResolution();
}
public int getDelta() {
long time = getTime();
int delta = (int) (time - lastFrame);
lastFrame = time;
return delta;
}
private class KeyInputHandler extends KeyAdapter {
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_LEFT || e.getKeyCode() == KeyEvent.VK_A) {
leftPressed = true;
}
if (e.getKeyCode() == KeyEvent.VK_RIGHT || e.getKeyCode() == KeyEvent.VK_D) {
rightPressed = true;
}
if (e.getKeyChar() == 27 || e.getKeyCode() == KeyEvent.VK_PAUSE || e.getKeyCode() == KeyEvent.VK_P) {
pauseGame();
}
}
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_LEFT || e.getKeyCode() == KeyEvent.VK_A) {
leftPressed = false;
}
if (e.getKeyCode() == KeyEvent.VK_RIGHT || e.getKeyCode() == KeyEvent.VK_D) {
rightPressed = false;
}
}
}
public static void main(String argv[]) {
Game g =new Game();
// Start the main game loop
g.gameLoop();
}
}
| src/me/dreamteam/tardis/Game.java | package me.dreamteam.tardis;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Toolkit;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferStrategy;
import java.net.URL;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import org.lwjgl.Sys;
import me.dreamteam.tardis.Entity;
import me.dreamteam.tardis.ShipEntity;
import me.dreamteam.tardis.EnemyEntity;
import me.dreamteam.tardis.Utils;
import me.dreamteam.tardis.UtilsHTML;
/**
Main Class
*/
public class Game extends Canvas {
private BufferStrategy strategy;
// This provides hardware acceleration
private boolean isRunning = true;
private boolean gameStart = false;
private Entity ship;
private int shipS = 0;
double curY = 0;
long lastLoopTime;
private ArrayList entities = new ArrayList();
private ArrayList enemies = new ArrayList();
private double moveSpeed = 180;
private boolean leftPressed = false;
private boolean rightPressed = false;
private boolean logicRequiredThisLoop = false;
private boolean advanceLevel = false;
long lastFrame;
long finalTime = 0;
private String timeDisplay = "";
private String livesDisplay = "";
int timeMil;
public int gameTime = 0;
public int gameLives = 3;
int SpriteLoc;
int SpriteLoc2;
int SpriteLoc3;
int twait = 0;
int CurSprite = 1;
ImageIcon blankIcon = new ImageIcon();
Random rSpriteLoc = new Random();
long lastTime;
private int level = 1;
public Game() {
JFrame container = new JFrame(Utils.gameName + "- " + Utils.build + Utils.version);
JPanel panel = (JPanel) container.getContentPane();
panel.setPreferredSize(new Dimension(500,650));
panel.setLayout(null);
setBounds(0,0,500,650);
panel.add(this);
setIgnoreRepaint(true);
container.setResizable(false);
container.pack();
// Window setup
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
int w = container.getSize().width;
int h = container.getSize().height;
int x = (dim.width-w)/2;
int y = (dim.height-h)/2;
container.setLocation(x, y);
container.setBackground(Color.black);
container.setVisible(true);
//What to do when user choose to close
container.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
Utils.quitGame();
}
});
ImageIcon icon = new ImageIcon(Utils.iconURL);
container.setIconImage(icon.getImage());
// Init keys
addKeyListener(new KeyInputHandler());
// create the buffering strategy for graphics
createBufferStrategy(2);
strategy = getBufferStrategy();
requestFocus();
initEntities();
titleScreen();
}
public void updateLogic() {
logicRequiredThisLoop = true;
}
/**
* Create our ship
*/
private void initEntities() {
if (shipS == 0) {
ship = new ShipEntity(this,"sprites/ship.png",220,568);
entities.add(ship);
}
if (shipS == 1) {
ship = new ShipEntity(this,"sprites/ship2.png",220,568);
entities.add(ship);
}
if (shipS == 2) {
ship = new ShipEntity(this,"sprites/ship3.png",220,568);
entities.add(ship);
}
}
private void updateEnt(){
moveSpeed = 180+(twait*0.7);
SpriteLoc = rSpriteLoc.nextInt(200);
SpriteLoc2 = 200+rSpriteLoc.nextInt(250);
if(SpriteLoc2 < SpriteLoc+56){
if(SpriteLoc2 > SpriteLoc-56){
SpriteLoc2 = SpriteLoc-56;
if (SpriteLoc2 > 450)
SpriteLoc2 = SpriteLoc-56;
}
}
if(twait != gameTime){
int FinalLoc;
if(gameTime >= twait+2 && advanceLevel == false){
twait = gameTime;
for(int i = 0; i<2; i++){
if(i==0){
FinalLoc = SpriteLoc;
}else{
FinalLoc = SpriteLoc2;
}
Entity Enemies = new EnemyEntity(this,"sprites/enemies/0"+CurSprite+".png",FinalLoc,-50);
entities.add(Enemies);
CurSprite += 1;
if (CurSprite>5)
CurSprite=1;
}
}else if (advanceLevel == true){
if(gameTime>= twait && level ==2){
twait = gameTime;
for(int i = 0; i<2; i++){
if(i==0){
FinalLoc = SpriteLoc;
}else{
FinalLoc = SpriteLoc2;
}
Entity Enemies = new EnemyEntity(this,"sprites/enemies/0"+CurSprite+".png",FinalLoc,-50, (twait+(100*0.45)-30));
entities.add(Enemies);
CurSprite += 1;
if (CurSprite>5)
CurSprite=1;
}
}else if(gameTime>= twait && level >2){
twait = gameTime;
for(int i = 0; i<2; i++){
if(i==0){
FinalLoc = SpriteLoc;
}else{
FinalLoc = SpriteLoc2;
}
Entity Enemies = new EnemyEntity(this,"sprites/enemies/0"+CurSprite+".png",FinalLoc,-50, (twait+(100*0.45)-30));
entities.add(Enemies);
CurSprite += 1;
if (CurSprite>5)
CurSprite=1;
}
}
}
}
}
private void startGame() {
entities.clear();
initEntities();
// reset key presses
leftPressed = false;
rightPressed = false;
//reset time
timeMil = 0;
//reset lives
gameLives = 3;
level = 1;
gameStart = true;
twait = 0;
gameTime = 0;
finalTime = 0;
lastLoopTime = System.currentTimeMillis();
}
public void characterSelect() {
ImageIcon ship1 = new ImageIcon(Utils.ship1URL);
ImageIcon ship2 = new ImageIcon(Utils.ship2URL);
ImageIcon ship3 = new ImageIcon(Utils.ship3URL);
Utils.systemLF();
Object[] coptions = {UtilsHTML.bpcsStart + ship1 + UtilsHTML.bpcsMiddle + Utils.ship1Name + UtilsHTML.bpcsEnd,
UtilsHTML.bpcsStart + ship2 + UtilsHTML.bpcsMiddle + Utils.ship2Name + UtilsHTML.bpcsEnd,
UtilsHTML.bpcsStart + ship3 + UtilsHTML.bpcsMiddle + Utils.ship3Name + UtilsHTML.bpcsEnd};
int characterS = JOptionPane.showOptionDialog(null,
UtilsHTML.csDialog, Utils.csDialogTitle, JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.INFORMATION_MESSAGE,
blankIcon,
coptions,
coptions[0]);
if (characterS != 2 && characterS != 1 && characterS != 0) {
titleScreen();
}
if (characterS == 2) {
shipS = 2;
startGame();
}
if (characterS == 1) {
shipS = 1;
startGame();
}
if (characterS == 0) {
shipS = 0;
startGame();
}
}
public void titleScreen() {
ImageIcon icon = new ImageIcon(Utils.iconURL);
Utils.systemLF();
Object[] options = {Utils.bPlay, Utils.bQuit};
int startG = JOptionPane.showOptionDialog(null,
Utils.txtTS, Utils.tsDialogTitle,
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE,
icon,
options,
options[0]);
if (startG != 0 && startG != 1) {
Utils.quitGame();
}
if (startG == 1) {
System.exit(0);
}
if (startG == 0) {
characterSelect();
}
}
public void pauseGame() {
ImageIcon icon = new ImageIcon(Utils.iconURL);
Utils.systemLF();
gameStart = false;
long LoopTempTime = System.currentTimeMillis();
Object[] options = {Utils.bReturn, Utils.bRestart, Utils.bQuit};
int pauseG = JOptionPane.showOptionDialog(null,
Utils.txtPS, Utils.tsDialogTitle,
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE,
icon,
options,
options[0]);
double[] entCurYLoc = new double[entities.size()];
for (int i=0;i<entities.size();i++) {
Entity entity = (Entity) entities.get(i);
entCurYLoc[i] = entity.getVerticalMovement();
entity.setVerticalMovement(0);
}
if (pauseG != 1 && pauseG != 2) {
for (int i=0;i<entities.size();i++) {
Entity entity = (Entity) entities.get(i);
entity.setVerticalMovement(entCurYLoc[i]);
}
finalTime = System.currentTimeMillis() - LoopTempTime;
gameStart = true;
}
if (pauseG == 2) {
System.exit(0);
}
if (pauseG == 1) {
gameTime = 0;
characterSelect();
}
}
public void gameLoop() {
lastLoopTime = System.currentTimeMillis();
while (isRunning) {
if(gameStart == true){
long delta = (System.currentTimeMillis()-finalTime) - lastLoopTime;
finalTime = 0;
lastLoopTime = System.currentTimeMillis();
lastTime = getTime();
updateTime();
// Colour in background
Graphics2D g = (Graphics2D) strategy.getDrawGraphics();
g.setColor(Color.black);
g.fillRect(0,0,500,650);
for (int i=0;i<entities.size();i++) {
Entity entity = (Entity) entities.get(i);
entity.move(delta);
}
if (logicRequiredThisLoop) {
for (int i=0;i<entities.size();i++) {
Entity entity = (Entity) entities.get(i);
entity.doLogic();
}
logicRequiredThisLoop = false;
}
for (int i=0;i<entities.size();i++) {
Entity entity = (Entity) entities.get(i);
entity.draw(g);
}
if(gameTime >90){
advanceLevel = true;
if(gameTime > 200){
level = 3;
}else{
level = 2;
}
}
/*
* Game Text
*/
g.setColor(Color.red);
g.setFont(new Font("Century Gothic", Font.BOLD, Utils.levelFS));
g.drawString(Utils.txtLevel + level,(500-g.getFontMetrics().stringWidth(Utils.txtLevel + level))/2,18);
// Timer
g.setColor(Color.white);
g.setFont(new Font("Lucida Console", Font.BOLD, Utils.timeFS));
g.drawString(timeDisplay,(70-g.getFontMetrics().stringWidth(timeDisplay))/2,18);
g.drawString(Utils.txtTime,(70-g.getFontMetrics().stringWidth(Utils.txtTime))/2,18);
if (timeMil > 99){
gameTime = timeMil/100;
}
String convtime = String.valueOf(gameTime);
g.setColor(Color.white);
g.setFont(new Font("Lucida Console", Font.ITALIC, Utils.timeIFS));
g.drawString(timeDisplay,(175-g.getFontMetrics().stringWidth(timeDisplay))/2,18);
g.drawString(convtime,(175-g.getFontMetrics().stringWidth(convtime))/2,18);
//Lives
g.setColor(Color.white);
g.setFont(new Font("Lucida Console", Font.BOLD, Utils.livesFS));
g.drawString(livesDisplay,(875-g.getFontMetrics().stringWidth(livesDisplay))/2,18);
g.drawString(Utils.txtLives,(875-g.getFontMetrics().stringWidth(Utils.txtLives))/2,18);
String convlives = String.valueOf(gameLives);
g.setColor(Color.white);
g.setFont(new Font("Lucida Console", Font.ITALIC, Utils.livesIFS));
g.drawString(timeDisplay,(965-g.getFontMetrics().stringWidth(timeDisplay))/2,18);
g.drawString(convlives,(965-g.getFontMetrics().stringWidth(convlives))/2,18);
// Clear Graphics
g.dispose();
strategy.show();
updateEnt();
ship.setHorizontalMovement(0);
// Ship movement
if ((leftPressed) && (!rightPressed)) {
ship.setHorizontalMovement(-moveSpeed);
} else if ((rightPressed) && (!leftPressed)) {
ship.setHorizontalMovement(moveSpeed);
}
//testing for collision of player and enemy
for (int p=0;p<entities.size();p++) {
for (int s=p+1;s<entities.size();s++) {
Entity me = (Entity) entities.get(p);
Entity him = (Entity) entities.get(s);
if (me.collidesWith(him)) {
me.collidedWith(him);
him.collidedWith(me);
}
}
}
try { Thread.sleep(10); } catch (Exception e) {}
}else{
try { Thread.sleep(10); } catch (Exception e) {}
}
}
}
/**
* Update the game time
*/
public void updateTime() {
if (getTime() - lastTime > 1000) {
timeMil = 0; //reset the FPS counter
lastTime += 1000; //add one second
}
timeMil++;
}
public long getTime() {
return (Sys.getTime() * 1000) / Sys.getTimerResolution();
}
public int getDelta() {
long time = getTime();
int delta = (int) (time - lastFrame);
lastFrame = time;
return delta;
}
private class KeyInputHandler extends KeyAdapter {
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_LEFT || e.getKeyCode() == KeyEvent.VK_A) {
leftPressed = true;
}
if (e.getKeyCode() == KeyEvent.VK_RIGHT || e.getKeyCode() == KeyEvent.VK_D) {
rightPressed = true;
}
if (e.getKeyChar() == 27 || e.getKeyCode() == KeyEvent.VK_PAUSE || e.getKeyCode() == KeyEvent.VK_P) {
pauseGame();
}
}
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_LEFT || e.getKeyCode() == KeyEvent.VK_A) {
leftPressed = false;
}
if (e.getKeyCode() == KeyEvent.VK_RIGHT || e.getKeyCode() == KeyEvent.VK_D) {
rightPressed = false;
}
}
}
public static void main(String argv[]) {
Game g =new Game();
// Start the main game loop
g.gameLoop();
}
}
| Code Cleanup
| src/me/dreamteam/tardis/Game.java | Code Cleanup | <ide><path>rc/me/dreamteam/tardis/Game.java
<ide>
<ide> private boolean isRunning = true;
<ide> private boolean gameStart = false;
<add> long lastLoopTime;
<ide>
<ide> private Entity ship;
<ide> private int shipS = 0;
<del> double curY = 0;
<del> long lastLoopTime;
<add>
<ide> private ArrayList entities = new ArrayList();
<ide> private ArrayList enemies = new ArrayList();
<ide>
<del>
<ide> private double moveSpeed = 180;
<del> private boolean leftPressed = false;
<add>
<add> private boolean leftPressed = false;
<ide> private boolean rightPressed = false;
<add>
<ide> private boolean logicRequiredThisLoop = false;
<ide> private boolean advanceLevel = false;
<add> private int level = 1;
<ide> long lastFrame;
<ide> long finalTime = 0;
<ide> private String timeDisplay = "";
<ide> private String livesDisplay = "";
<del> int timeMil;
<ide> public int gameTime = 0;
<ide> public int gameLives = 3;
<add> int timeMil;
<add> long lastTime;
<add>
<ide> int SpriteLoc;
<ide> int SpriteLoc2;
<ide> int SpriteLoc3;
<del> int twait = 0;
<add>
<add> int tWait = 0;
<ide> int CurSprite = 1;
<add> double curY = 0;
<add>
<ide> ImageIcon blankIcon = new ImageIcon();
<ide> Random rSpriteLoc = new Random();
<del>
<del> long lastTime;
<del>
<del> private int level = 1;
<ide>
<ide> public Game() {
<ide>
<ide> }
<ide>
<ide> private void updateEnt(){
<del> moveSpeed = 180+(twait*0.7);
<add> moveSpeed = 180+(tWait*0.7);
<ide> SpriteLoc = rSpriteLoc.nextInt(200);
<ide> SpriteLoc2 = 200+rSpriteLoc.nextInt(250);
<ide> if(SpriteLoc2 < SpriteLoc+56){
<ide> SpriteLoc2 = SpriteLoc-56;
<ide> }
<ide> }
<del> if(twait != gameTime){
<add> if(tWait != gameTime){
<ide> int FinalLoc;
<del> if(gameTime >= twait+2 && advanceLevel == false){
<del> twait = gameTime;
<add> if(gameTime >= tWait+2 && advanceLevel == false){
<add> tWait = gameTime;
<ide>
<ide> for(int i = 0; i<2; i++){
<ide> if(i==0){
<ide> CurSprite=1;
<ide> }
<ide> }else if (advanceLevel == true){
<del> if(gameTime>= twait && level ==2){
<del> twait = gameTime;
<add> if(gameTime>= tWait && level ==2){
<add> tWait = gameTime;
<ide> for(int i = 0; i<2; i++){
<ide> if(i==0){
<ide> FinalLoc = SpriteLoc;
<ide> }else{
<ide> FinalLoc = SpriteLoc2;
<ide> }
<del> Entity Enemies = new EnemyEntity(this,"sprites/enemies/0"+CurSprite+".png",FinalLoc,-50, (twait+(100*0.45)-30));
<add> Entity Enemies = new EnemyEntity(this,"sprites/enemies/0"+CurSprite+".png",FinalLoc,-50, (tWait+(100*0.45)-30));
<ide> entities.add(Enemies);
<ide> CurSprite += 1;
<ide> if (CurSprite>5)
<ide> CurSprite=1;
<ide> }
<del> }else if(gameTime>= twait && level >2){
<del> twait = gameTime;
<add> }else if(gameTime>= tWait && level >2){
<add> tWait = gameTime;
<ide> for(int i = 0; i<2; i++){
<ide> if(i==0){
<ide> FinalLoc = SpriteLoc;
<ide> }else{
<ide> FinalLoc = SpriteLoc2;
<ide> }
<del> Entity Enemies = new EnemyEntity(this,"sprites/enemies/0"+CurSprite+".png",FinalLoc,-50, (twait+(100*0.45)-30));
<add> Entity Enemies = new EnemyEntity(this,"sprites/enemies/0"+CurSprite+".png",FinalLoc,-50, (tWait+(100*0.45)-30));
<ide> entities.add(Enemies);
<ide> CurSprite += 1;
<ide> if (CurSprite>5)
<ide>
<ide> entities.clear();
<ide> initEntities();
<del>
<ide>
<ide> // reset key presses
<ide> leftPressed = false;
<ide> gameLives = 3;
<ide> level = 1;
<ide> gameStart = true;
<del> twait = 0;
<add> tWait = 0;
<ide> gameTime = 0;
<ide> finalTime = 0;
<ide> lastLoopTime = System.currentTimeMillis(); |
|
Java | apache-2.0 | 53413b7dcd7364b6f888f7b9bbd26f94cbf9a0b5 | 0 | lydhr/tango-examples-c,lydhr/tango-examples-c,AdamRLukaitis/tango-examples-c,vamsirajendra/tango-examples-c,googlearchive/tango-examples-c,hamidb/tango-examples-c,vamsirajendra/tango-examples-c,brinkmwj/Fairies-Why-Did-It-Have-To-Be-Fairies,AdamRLukaitis/tango-examples-c,LorenzMeier/tango-examples-c,brinkmwj/Fairies-Why-Did-It-Have-To-Be-Fairies,LorenzMeier/tango-examples-c,googlearchive/tango-examples-c,hamidb/tango-examples-c | /*
* Copyright 2014 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.tango.tangojnimotiontracking;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewGroup.LayoutParams;
import android.widget.TextView;
public class MotionTrackingActivity extends Activity {
MotionTrackingView motionTrackingView;
TextView tangoPoseStatusText;
String[] poseStatuses = { "Initializing", "Valid", "Invalid", "Unknown" };
int[] statusCount = { 0, 0, 0 };
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
motionTrackingView = new MotionTrackingView(this);
tangoPoseStatusText = new TextView(this);
setContentView(motionTrackingView);
addContentView(tangoPoseStatusText, new LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
TangoJNINative.OnCreate();
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(10);
final byte statusIndex = TangoJNINative.UpdateStatus();
final String tangoPoseStatusString = poseStatuses[statusIndex];
if (statusIndex < 3)
statusCount[statusIndex]++;
final String tangoPoseString = TangoJNINative
.PoseToString();
runOnUiThread(new Runnable() {
@Override
public void run() {
try {
tangoPoseStatusText.setText("Pose Status: "
+ tangoPoseStatusString + "\n"
+ "StatusCount: Initializing--"
+ statusCount[0] + " Valid--"
+ statusCount[1] + " Invalid--"
+ statusCount[2] + "\n"
+ tangoPoseString);
} catch (Exception e) {
e.printStackTrace();
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}
}).start();
}
@Override
protected void onResume() {
super.onResume();
motionTrackingView.onResume();
TangoJNINative.OnResume();
}
@Override
protected void onPause() {
super.onPause();
motionTrackingView.onPause();
TangoJNINative.OnPause();
}
protected void onDestroy() {
super.onDestroy();
TangoJNINative.OnDestroy();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.motion_tracking, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_first_camera:
TangoJNINative.SetCamera(0);
return true;
case R.id.action_third_camera:
TangoJNINative.SetCamera(1);
return true;
case R.id.action_top_camera:
TangoJNINative.SetCamera(2);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
| motion-tracking-jni-example/src/com/google/tango/tangojnimotiontracking/MotionTrackingActivity.java | /*
* Copyright 2014 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.tango.tangojnimotiontracking;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewGroup.LayoutParams;
import android.widget.TextView;
public class MotionTrackingActivity extends Activity {
MotionTrackingView motionTrackingView;
TextView tangoPoseStatusText;
String[] poseStatuses = {"Initializing", "Valid", "Invalid", "Unknown"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
motionTrackingView = new MotionTrackingView(this);
tangoPoseStatusText = new TextView(this);
setContentView(motionTrackingView);
addContentView(tangoPoseStatusText, new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
TangoJNINative.OnCreate();
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(10);
final byte statusIndex = TangoJNINative
.UpdateStatus();
final String tangoPoseStatusString = poseStatuses[statusIndex];
final String tangoPoseString = TangoJNINative.PoseToString();
runOnUiThread(new Runnable() {
@Override
public void run() {
try {
tangoPoseStatusText.setText("Pose Status: "+tangoPoseStatusString+"\n"+tangoPoseString);
} catch (Exception e) {
e.printStackTrace();
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}
}).start();
}
@Override
protected void onResume() {
super.onResume();
motionTrackingView.onResume();
TangoJNINative.OnResume();
}
@Override
protected void onPause() {
super.onPause();
motionTrackingView.onPause();
TangoJNINative.OnPause();
}
protected void onDestroy() {
super.onDestroy();
TangoJNINative.OnDestroy();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.motion_tracking, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_first_camera:
TangoJNINative.SetCamera(0);
return true;
case R.id.action_third_camera:
TangoJNINative.SetCamera(1);
return true;
case R.id.action_top_camera:
TangoJNINative.SetCamera(2);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
| Add Pose status count on the screen to verify the Pose life cycle.
| motion-tracking-jni-example/src/com/google/tango/tangojnimotiontracking/MotionTrackingActivity.java | Add Pose status count on the screen to verify the Pose life cycle. | <ide><path>otion-tracking-jni-example/src/com/google/tango/tangojnimotiontracking/MotionTrackingActivity.java
<ide>
<ide> MotionTrackingView motionTrackingView;
<ide> TextView tangoPoseStatusText;
<del> String[] poseStatuses = {"Initializing", "Valid", "Invalid", "Unknown"};
<add> String[] poseStatuses = { "Initializing", "Valid", "Invalid", "Unknown" };
<add> int[] statusCount = { 0, 0, 0 };
<ide>
<ide> @Override
<ide> protected void onCreate(Bundle savedInstanceState) {
<ide> tangoPoseStatusText = new TextView(this);
<ide>
<ide> setContentView(motionTrackingView);
<del> addContentView(tangoPoseStatusText, new LayoutParams(LayoutParams.WRAP_CONTENT,
<del> LayoutParams.WRAP_CONTENT));
<add> addContentView(tangoPoseStatusText, new LayoutParams(
<add> LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
<ide> TangoJNINative.OnCreate();
<ide>
<ide> new Thread(new Runnable() {
<ide> while (true) {
<ide> try {
<ide> Thread.sleep(10);
<del> final byte statusIndex = TangoJNINative
<del> .UpdateStatus();
<add> final byte statusIndex = TangoJNINative.UpdateStatus();
<ide> final String tangoPoseStatusString = poseStatuses[statusIndex];
<del> final String tangoPoseString = TangoJNINative.PoseToString();
<add> if (statusIndex < 3)
<add> statusCount[statusIndex]++;
<add> final String tangoPoseString = TangoJNINative
<add> .PoseToString();
<ide> runOnUiThread(new Runnable() {
<ide> @Override
<ide> public void run() {
<ide> try {
<del> tangoPoseStatusText.setText("Pose Status: "+tangoPoseStatusString+"\n"+tangoPoseString);
<add> tangoPoseStatusText.setText("Pose Status: "
<add> + tangoPoseStatusString + "\n"
<add> + "StatusCount: Initializing--"
<add> + statusCount[0] + " Valid--"
<add> + statusCount[1] + " Invalid--"
<add> + statusCount[2] + "\n"
<add> + tangoPoseString);
<ide> } catch (Exception e) {
<ide> e.printStackTrace();
<ide> }
<ide> }
<ide> });
<del>
<add>
<ide> } catch (Exception e) {
<ide> e.printStackTrace();
<ide> } |
|
JavaScript | mit | 361cdcc5470017b8d797adc993506c33ba6502c5 | 0 | treyhunner/Parsley.js,noikiy/Parsley.js,prashen/Parsley.js,j-hernandez/Parsley.js,j-hernandez/Parsley.js,sharq88/Parsley.js,guillaumepotier/Parsley.js,imshibaji/Parsley.js,noikiy/Parsley.js,donghanee/Parsley.js,Rashid-Asif/Parsley.js,LoveMondays/Parsley.js,Jeremy017/Parsley.js,garylgh/Parsley.js,giscloud/Parsley.js,zaoli/Parsley.js,houv123/Parsley.js,sharq88/Parsley.js,Rashid-Asif/Parsley.js,tsioukas/Parsley.js,uclaros/Parsley.js,xiwc/Parsley.js,konder/Parsley.js,m-jch/Parsley.js,xiwc/Parsley.js,rockmandew/Parsley.js,m-jch/Parsley.js,david84/Parsley.js,treyhunner/Parsley.js,LoveMondays/Parsley.js,wizardbab/Parsley.js,ozanmuyes/Parsley.js,bolster/Parsley.js,konder/Parsley.js,wizardbab/Parsley.js,jpalomar/Parsley.js,bolster/Parsley.js,payssion/Parsley.js,garylgh/Parsley.js,rockmandew/Parsley.js,houv123/Parsley.js,Jeremy017/Parsley.js,uclaros/Parsley.js,imshibaji/Parsley.js,jpalomar/Parsley.js,prashen/Parsley.js,giscloud/Parsley.js,tsioukas/Parsley.js,payssion/Parsley.js,david84/Parsley.js,ozanmuyes/Parsley.js,zaoli/Parsley.js,donghanee/Parsley.js,guillaumepotier/Parsley.js | // ParsleyConfig definition if not already set
window.ParsleyConfig = window.ParsleyConfig || {};
window.ParsleyConfig.i18n = window.ParsleyConfig.i18n || {};
// Define then the messages
window.ParsleyConfig.i18n.da = $.extend(window.ParsleyConfig.i18n.da || {}, {
defaultMessage: "Indtast venligst en korrekt værdi.",
type: {
email: "Indtast venligst en korrekt email.",
url: "Indtast venligst en korrekt internetadresse.",
number: "Indtast venligst et korrekt nummer.",
integer: "Indtast venligst et korrekt tal.",
digits: "Dette felt må kun bestå af tal.",
alphanum: "Dette felt skal indeholde både tal og bogstaver."
},
notblank: "Dette felt må ikke være tomt.",
required: "Dette felt er påkrævet.",
pattern: "Ugyldig indtastning.",
min: "Dette felt skal indeholde mindst %s tegn.",
max: "Dette felt kan højest indeholde %s tegn.",
range: "Dette felt skal være mellem %s og %s tegn.",
minlength: "Indtast venligst mindst %s tegn.",
maxlength: "Dette felt kan kun indeholde %s tegn.",
length: "This value length is invalid. It should be between %s and %s characters long.",
mincheck: "Vælg mindst %s muligheder.",
maxcheck: "Vælg op til %s muligheder.",
check: "Vælg mellem %s og %s muligheder.",
equalto: "De to felter er ikke ens."
});
// If file is loaded after Parsley main file, auto-load locale
if ('undefined' !== typeof window.ParsleyValidator)
window.ParsleyValidator.addCatalog('da', window.ParsleyConfig.i18n.da, true);
| src/i18n/da.js | // ParsleyConfig definition if not already set
window.ParsleyConfig = window.ParsleyConfig || {};
window.ParsleyConfig.i18n = window.ParsleyConfig.i18n || {};
// Define then the messages
window.ParsleyConfig.i18n.da = $.extend(window.ParsleyConfig.i18n.da || {}, {
defaultMessage: "Indtast venligst en korrekt værdi.",
type: {
email: "Indtast venligst en korrekt email.",
url: "Indtast venligst en korrekt internetadresse.",
number: "Indtast venligst et korrekt nummer.",
integer: "Indtast venligst et korrekt tal.",
digits: "Dette felt må kun bestå af tal.",
alphanum: "Dette felt skal indeholde både tal og bogstaver."
},
notblank: "Dette felt må ikke være tomt.",
required: "Dette felt er påkrævet.",
pattern: "Ugyldig indtastning.",
min: "Dette felt skal indeholde mindst %s tegn.",
max: "Dette felt kan højest indeholde %s tegn.",
range: "Dette felt skal være mellem %s og %s tegn.",
minlength: "Indtast venligst mindst %s tegn.",
maxlength: "Dette felt kan kun indeholde %s tegn.",
length: "This value length is invalid. It should be between %s and %s characters long.",
mincheck: "Vælg mindst %s muligheder.",
maxcheck: "Vælg op til %s muligheder.",
check: "Vælg mellem %s og %s muligheder.",
equalto: "De to felter er ikke ens."
});
// If file is loaded after Parsley main file, auto-load locale
if ('undefined' !== typeof window.ParsleyValidator)
window.ParsleyValidator.addCatalog('en', window.ParsleyConfig.i18n.da, true);
| Update da.js
forgot to specify 'da' in bottom | src/i18n/da.js | Update da.js | <ide><path>rc/i18n/da.js
<ide>
<ide> // If file is loaded after Parsley main file, auto-load locale
<ide> if ('undefined' !== typeof window.ParsleyValidator)
<del> window.ParsleyValidator.addCatalog('en', window.ParsleyConfig.i18n.da, true);
<add> window.ParsleyValidator.addCatalog('da', window.ParsleyConfig.i18n.da, true); |
|
Java | mit | c8f929877219746ea5999d47c94915203a6bdd5a | 0 | backuporg/Witchworks,Um-Mitternacht/Wiccan_Arts,Um-Mitternacht/Witchworks | package com.wiccanarts.common.item;
import com.wiccanarts.common.crafting.VanillaCrafting;
import com.wiccanarts.common.lib.LibItemName;
import com.wiccanarts.common.lib.LibMod;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraftforge.oredict.OreDictionary;
import static net.minecraftforge.fml.common.registry.GameRegistry.ObjectHolder;
/**
* This class was created by <Arekkuusu> on 26/02/2017.
* It's distributed as part of Wiccan Arts under
* the MIT license.
*/
@ObjectHolder(LibMod.MOD_ID)
public final class ModItems {
//Gemstones
@ObjectHolder(LibItemName.GARNET)
public static final Item GARNET = new Item();
@ObjectHolder(LibItemName.MOLDAVITE)
public static final Item MOLDAVITE = new Item();
@ObjectHolder(LibItemName.NUUMMITE)
public static final Item NUUMMITE = new Item();
@ObjectHolder(LibItemName.PETOSKEY_STONE)
public static final Item PETOSKEY_STONE = new Item();
@ObjectHolder(LibItemName.SERPENTINE)
public static final Item SERPENTINE = new Item();
@ObjectHolder(LibItemName.TIGERS_EYE)
public static final Item TIGERS_EYE = new Item();
@ObjectHolder(LibItemName.TOURMALINE)
public static final Item TOURMALINE = new Item();
@ObjectHolder(LibItemName.BLOODSTONE)
public static final Item BLOODSTONE = new Item();
@ObjectHolder(LibItemName.JASPER)
public static final Item JASPER = new Item();
@ObjectHolder(LibItemName.MALACHITE)
public static final Item MALACHITE = new Item();
@ObjectHolder(LibItemName.AMETHYST)
public static final Item AMETHYST = new Item();
@ObjectHolder(LibItemName.ALEXANDRITE)
public static final Item ALEXANDRITE = new Item();
@ObjectHolder(LibItemName.QUARTZ)
public static final Item QUARTZ = new Item();
//Metals
@ObjectHolder(LibItemName.SILVER_INGOT)
public static final Item SILVER_INGOT = new Item();
@ObjectHolder(LibItemName.SILVER_POWDER)
public static final Item SILVER_POWDER = new Item();
@ObjectHolder(LibItemName.SILVER_NUGGET)
public static final Item SILVER_NUGGET = new Item();
//Food Items
@ObjectHolder(LibItemName.HONEY)
public static final Item HONEY = new Item();
@ObjectHolder(LibItemName.LAVENDER_SPRIG)
public static final Item LAVENDER_SPRIG = new Item();
//Materials
@ObjectHolder(LibItemName.WAX)
public static final Item WAX = new Item();
@ObjectHolder(LibItemName.SALT)
public static final Item SALT = new Item();
@ObjectHolder(LibItemName.HONEYCOMB)
public static final Item HONEYCOMB = new Item();
//Misc
@ObjectHolder(LibItemName.BEE)
public static final Item BEE = new Item();
public static void init() {
VanillaCrafting.items();
}
public static void initOreDictionary() {
OreDictionary.registerOre("gemBloodstone", new ItemStack(ModItems.BLOODSTONE));
OreDictionary.registerOre("gemMoldavite", new ItemStack(ModItems.MOLDAVITE));
OreDictionary.registerOre("gemNuummite", new ItemStack(ModItems.NUUMMITE));
OreDictionary.registerOre("gemGarnet", new ItemStack(ModItems.GARNET));
OreDictionary.registerOre("gemTourmaline", new ItemStack(ModItems.TOURMALINE));
OreDictionary.registerOre("gemTigersEye", new ItemStack(ModItems.TIGERS_EYE));
OreDictionary.registerOre("gemPetoskeyStone", new ItemStack(ModItems.PETOSKEY_STONE));
OreDictionary.registerOre("gemJasper", new ItemStack(ModItems.JASPER));
OreDictionary.registerOre("gemMalachite", new ItemStack(ModItems.MALACHITE));
OreDictionary.registerOre("gemAmethyst", new ItemStack(ModItems.AMETHYST));
OreDictionary.registerOre("gemAlexandrite", new ItemStack(ModItems.ALEXANDRITE));
OreDictionary.registerOre("gemQuartz", new ItemStack(ModItems.QUARTZ));
OreDictionary.registerOre("nuggetSilver", new ItemStack(ModItems.SILVER_NUGGET));
OreDictionary.registerOre("ingotSilver", new ItemStack(ModItems.SILVER_INGOT));
OreDictionary.registerOre("powderSilver", new ItemStack(ModItems.SILVER_POWDER));
OreDictionary.registerOre("honeyDrop", new ItemStack(ModItems.HONEY));
OreDictionary.registerOre("dropHoney", new ItemStack(ModItems.HONEY));
OreDictionary.registerOre("listAllsugar", new ItemStack(ModItems.HONEY));
OreDictionary.registerOre("materialWax", new ItemStack(ModItems.WAX));
OreDictionary.registerOre("materialBeeswax", new ItemStack(ModItems.WAX));
OreDictionary.registerOre("materialPressedWax", new ItemStack(ModItems.WAX));
OreDictionary.registerOre("itemBeeswax", new ItemStack(ModItems.WAX));
OreDictionary.registerOre("cropLavender", new ItemStack(ModItems.LAVENDER_SPRIG));
OreDictionary.registerOre("listAllherb", new ItemStack(ModItems.LAVENDER_SPRIG));
OreDictionary.registerOre("foodSalt", new ItemStack(ModItems.SALT));
OreDictionary.registerOre("dustSalt", new ItemStack(ModItems.SALT));
OreDictionary.registerOre("materialSalt", new ItemStack(ModItems.SALT));
OreDictionary.registerOre("lumpSalt", new ItemStack(ModItems.SALT));
}
}
| src/main/java/com/wiccanarts/common/item/ModItems.java | package com.wiccanarts.common.item;
import com.wiccanarts.common.crafting.VanillaCrafting;
import com.wiccanarts.common.lib.LibItemName;
import com.wiccanarts.common.lib.LibMod;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraftforge.oredict.OreDictionary;
import static net.minecraftforge.fml.common.registry.GameRegistry.ObjectHolder;
/**
* This class was created by <Arekkuusu> on 26/02/2017.
* It's distributed as part of Wiccan Arts under
* the MIT license.
*/
@ObjectHolder(LibMod.MOD_ID)
public final class ModItems {
//Gemstones
@ObjectHolder(LibItemName.GARNET)
public static final Item GARNET = new Item();
@ObjectHolder(LibItemName.MOLDAVITE)
public static final Item MOLDAVITE = new Item();
@ObjectHolder(LibItemName.NUUMMITE)
public static final Item NUUMMITE = new Item();
@ObjectHolder(LibItemName.PETOSKEY_STONE)
public static final Item PETOSKEY_STONE = new Item();
@ObjectHolder(LibItemName.SERPENTINE)
public static final Item SERPENTINE = new Item();
@ObjectHolder(LibItemName.TIGERS_EYE)
public static final Item TIGERS_EYE = new Item();
@ObjectHolder(LibItemName.TOURMALINE)
public static final Item TOURMALINE = new Item();
@ObjectHolder(LibItemName.BLOODSTONE)
public static final Item BLOODSTONE = new Item();
@ObjectHolder(LibItemName.JASPER)
public static final Item JASPER = new Item();
@ObjectHolder(LibItemName.MALACHITE)
public static final Item MALACHITE = new Item();
@ObjectHolder(LibItemName.AMETHYST)
public static final Item AMETHYST = new Item();
@ObjectHolder(LibItemName.ALEXANDRITE)
public static final Item ALEXANDRITE = new Item();
@ObjectHolder(LibItemName.QUARTZ)
public static final Item QUARTZ = new Item();
//Metals
@ObjectHolder(LibItemName.SILVER_INGOT)
public static final Item SILVER_INGOT = new Item();
@ObjectHolder(LibItemName.SILVER_POWDER)
public static final Item SILVER_POWDER = new Item();
@ObjectHolder(LibItemName.SILVER_NUGGET)
public static final Item SILVER_NUGGET = new Item();
//Food Items
@ObjectHolder(LibItemName.HONEY)
public static final Item HONEY = new Item();
@ObjectHolder(LibItemName.LAVENDER_SPRIG)
public static final Item LAVENDER_SPRIG = new Item();
//Materials
@ObjectHolder(LibItemName.WAX)
public static final Item WAX = new Item();
@ObjectHolder(LibItemName.SALT)
public static final Item SALT = new Item();
@ObjectHolder(LibItemName.HONEYCOMB)
public static final Item HONEYCOMB = new Item();
//Misc
@ObjectHolder(LibItemName.BEE)
public static final Item BEE = new Item();
@ObjectHolder(LibItemName.BEEQUEEN)
public static final Item BEEQUEEN = new Item();
@ObjectHolder(LibItemName.BEEGRUB)
public static final Item BEEGRUB = new Item();
public static void init() {
VanillaCrafting.items();
}
public static void initOreDictionary() {
OreDictionary.registerOre("gemBloodstone", new ItemStack(ModItems.BLOODSTONE));
OreDictionary.registerOre("gemMoldavite", new ItemStack(ModItems.MOLDAVITE));
OreDictionary.registerOre("gemNuummite", new ItemStack(ModItems.NUUMMITE));
OreDictionary.registerOre("gemGarnet", new ItemStack(ModItems.GARNET));
OreDictionary.registerOre("gemTourmaline", new ItemStack(ModItems.TOURMALINE));
OreDictionary.registerOre("gemTigersEye", new ItemStack(ModItems.TIGERS_EYE));
OreDictionary.registerOre("gemPetoskeyStone", new ItemStack(ModItems.PETOSKEY_STONE));
OreDictionary.registerOre("gemJasper", new ItemStack(ModItems.JASPER));
OreDictionary.registerOre("gemMalachite", new ItemStack(ModItems.MALACHITE));
OreDictionary.registerOre("gemAmethyst", new ItemStack(ModItems.AMETHYST));
OreDictionary.registerOre("gemAlexandrite", new ItemStack(ModItems.ALEXANDRITE));
OreDictionary.registerOre("gemQuartz", new ItemStack(ModItems.QUARTZ));
OreDictionary.registerOre("nuggetSilver", new ItemStack(ModItems.SILVER_NUGGET));
OreDictionary.registerOre("ingotSilver", new ItemStack(ModItems.SILVER_INGOT));
OreDictionary.registerOre("powderSilver", new ItemStack(ModItems.SILVER_POWDER));
OreDictionary.registerOre("honeyDrop", new ItemStack(ModItems.HONEY));
OreDictionary.registerOre("dropHoney", new ItemStack(ModItems.HONEY));
OreDictionary.registerOre("listAllsugar", new ItemStack(ModItems.HONEY));
OreDictionary.registerOre("materialWax", new ItemStack(ModItems.WAX));
OreDictionary.registerOre("materialBeeswax", new ItemStack(ModItems.WAX));
OreDictionary.registerOre("materialPressedWax", new ItemStack(ModItems.WAX));
OreDictionary.registerOre("itemBeeswax", new ItemStack(ModItems.WAX));
OreDictionary.registerOre("cropLavender", new ItemStack(ModItems.LAVENDER_SPRIG));
OreDictionary.registerOre("listAllherb", new ItemStack(ModItems.LAVENDER_SPRIG));
OreDictionary.registerOre("foodSalt", new ItemStack(ModItems.SALT));
OreDictionary.registerOre("dustSalt", new ItemStack(ModItems.SALT));
OreDictionary.registerOre("materialSalt", new ItemStack(ModItems.SALT));
OreDictionary.registerOre("lumpSalt", new ItemStack(ModItems.SALT));
}
}
| whoops
| src/main/java/com/wiccanarts/common/item/ModItems.java | whoops | <ide><path>rc/main/java/com/wiccanarts/common/item/ModItems.java
<ide> //Misc
<ide> @ObjectHolder(LibItemName.BEE)
<ide> public static final Item BEE = new Item();
<del> @ObjectHolder(LibItemName.BEEQUEEN)
<del> public static final Item BEEQUEEN = new Item();
<del> @ObjectHolder(LibItemName.BEEGRUB)
<del> public static final Item BEEGRUB = new Item();
<ide>
<ide> public static void init() {
<ide> VanillaCrafting.items(); |
|
Java | apache-2.0 | c72f029eb0b4aebed262fd61e72763b966880f38 | 0 | radargun/radargun,rmacor/radargun,vjuranek/radargun,radargun/radargun,rmacor/radargun,rmacor/radargun,radargun/radargun,vjuranek/radargun,vjuranek/radargun,vjuranek/radargun,rmacor/radargun,radargun/radargun | package org.radargun;
import java.io.IOException;
import java.util.Map;
import org.radargun.config.Cluster;
import org.radargun.config.Configuration;
import org.radargun.config.InitHelper;
import org.radargun.config.PropertyHelper;
import org.radargun.config.Scenario;
import org.radargun.logging.Log;
import org.radargun.logging.LogFactory;
import org.radargun.reporting.Timeline;
import org.radargun.stages.ScenarioCleanupStage;
import org.radargun.state.SlaveState;
import org.radargun.traits.TraitHelper;
import org.radargun.utils.TimeService;
/**
* Base class for both standalone slave and slave integrated in master node (local cluster).
*
* @author Radim Vansa <[email protected]>
*/
public abstract class SlaveBase {
protected final Log log = LogFactory.getLog(getClass());
protected SlaveState state = new SlaveState();
protected Configuration configuration;
protected Cluster cluster;
protected Scenario scenario;
protected void scenarioLoop() throws IOException {
Cluster.Group group = cluster.getGroup(state.getSlaveIndex());
Configuration.Setup setup = configuration.getSetup(group.name);
state.setCluster(cluster);
state.setPlugin(setup.plugin);
state.setService(setup.service);
state.setTimeline(new Timeline(state.getSlaveIndex()));
Map<String, String> extras = getCurrentExtras(configuration, cluster);
ServiceHelper.setServiceContext(setup.plugin, configuration.name, state.getSlaveIndex());
Object service = ServiceHelper.createService(setup.plugin, setup.service, setup.getProperties(), extras);
Map<Class<?>, Object> traits = null;
try {
log.info("Service is " + service.getClass().getSimpleName() + PropertyHelper.toString(service));
traits = TraitHelper.retrieve(service);
state.setTraits(traits);
for (;;) {
int stageId = getNextStageId();
Map<String, Object> masterData = getNextMasterData();
for (Map.Entry<String, Object> entry : masterData.entrySet()) {
state.put(entry.getKey(), entry.getValue());
}
log.trace("Received stage ID " + stageId);
DistStage stage = (DistStage) scenario.getStage(stageId, state, extras, null);
if (stage instanceof ScenarioCleanupStage) {
// this is always the last stage and is ran in main thread (not sc-main)
break;
}
TraitHelper.InjectResult result = null;
DistStageAck response;
Exception initException = null;
try {
result = TraitHelper.inject(stage, traits);
InitHelper.init(stage);
stage.initOnSlave(state);
} catch (Exception e) {
log.error("Stage '" + stage.getName() + "' initialization has failed", e);
initException = e;
}
if (initException != null) {
response = new DistStageAck(state).error("Stage '" + stage.getName() + "' initialization has failed",
initException);
} else if (!stage.shouldExecute()) {
log.info("Stage '" + stage.getName() + "' should not be executed");
response = new DistStageAck(state);
} else if (result == TraitHelper.InjectResult.SKIP) {
log.info("Stage '" + stage.getName() + "' was skipped because it was missing some traits");
response = new DistStageAck(state);
} else if (result == TraitHelper.InjectResult.FAILURE) {
String message = "The stage '" + stage.getName()
+ "' was not executed because it missed some mandatory traits.";
log.error(message);
response = new DistStageAck(state).error(message, null);
} else {
String stageName = stage.getName();
log.info("Starting stage " + (log.isDebugEnabled() ? stage.toString() : stageName));
long start = TimeService.currentTimeMillis();
long end;
try {
response = stage.executeOnSlave();
end = TimeService.currentTimeMillis();
if (response == null) {
response = new DistStageAck(state).error("Stage returned null response", null);
}
log.info("Finished stage " + stageName);
response.setDuration(end - start);
} catch (Exception e) {
end = TimeService.currentTimeMillis();
log.error("Stage execution has failed", e);
response = new DistStageAck(state).error("Stage execution has failed", e);
} finally {
InitHelper.destroy(stage);
}
state.getTimeline().addEvent(Stage.STAGE, new Timeline.IntervalEvent(start, stageName, end - start));
}
sendResponse(response);
}
} finally {
if (traits != null) {
for (Object trait : traits.values()) {
InitHelper.destroy(trait);
}
}
InitHelper.destroy(service);
}
}
protected abstract int getNextStageId() throws IOException;
protected abstract Map<String, Object> getNextMasterData() throws IOException;
protected abstract void sendResponse(DistStageAck response) throws IOException;
protected void runCleanup() throws IOException {
DistStageAck response = null;
try {
Map<String, String> extras = getCurrentExtras(configuration, cluster);
ScenarioCleanupStage stage = (ScenarioCleanupStage) scenario.getStage(scenario.getStageCount() - 1, state,
extras, null);
InitHelper.init(stage);
stage.initOnSlave(state);
log.info("Starting stage " + (log.isDebugEnabled() ? stage.toString() : stage.getName()));
response = stage.executeOnSlave();
} catch (Exception e) {
log.error("Stage execution has failed", e);
response = new DistStageAck(state).error("Stage execution has failed", e);
} finally {
if (response == null) {
response = new DistStageAck(state).error("Stage returned null response", null);
}
sendResponse(response);
}
}
protected abstract Map<String, String> getCurrentExtras(Configuration configuration, Cluster cluster);
// In RadarGun 2.0, we had to run each service in new thread in order to prevent
// classloader leaking through thread locals. This is not necessary anymore,
// but we still do checks in ScenarioCleanupStage
protected class ScenarioRunner extends Thread {
protected ScenarioRunner() {
super("sc-main");
}
@Override
public void run() {
try {
scenarioLoop();
} catch (IOException e) {
log.error("Communication with master failed", e);
e.printStackTrace();
ShutDownHook.exit(127);
} catch (Throwable t) {
log.error("Unexpected error in scenario", t);
t.printStackTrace();
ShutDownHook.exit(127);
}
}
}
}
| core/src/main/java/org/radargun/SlaveBase.java | package org.radargun;
import java.io.IOException;
import java.util.Map;
import org.radargun.config.Cluster;
import org.radargun.config.Configuration;
import org.radargun.config.InitHelper;
import org.radargun.config.PropertyHelper;
import org.radargun.config.Scenario;
import org.radargun.logging.Log;
import org.radargun.logging.LogFactory;
import org.radargun.reporting.Timeline;
import org.radargun.stages.ScenarioCleanupStage;
import org.radargun.state.SlaveState;
import org.radargun.traits.TraitHelper;
import org.radargun.utils.TimeService;
/**
* Base class for both standalone slave and slave integrated in master node (local cluster).
*
* @author Radim Vansa <[email protected]>
*/
public abstract class SlaveBase {
protected final Log log = LogFactory.getLog(getClass());
protected SlaveState state = new SlaveState();
protected Configuration configuration;
protected Cluster cluster;
protected Scenario scenario;
protected void scenarioLoop() throws IOException {
Cluster.Group group = cluster.getGroup(state.getSlaveIndex());
Configuration.Setup setup = configuration.getSetup(group.name);
state.setCluster(cluster);
state.setPlugin(setup.plugin);
state.setService(setup.service);
state.setTimeline(new Timeline(state.getSlaveIndex()));
Map<String, String> extras = getCurrentExtras(configuration, cluster);
ServiceHelper.setServiceContext(setup.plugin, configuration.name, state.getSlaveIndex());
Object service = ServiceHelper.createService(setup.plugin, setup.service, setup.getProperties(), extras);
Map<Class<?>, Object> traits = null;
try {
log.info("Service is " + service.getClass().getSimpleName() + PropertyHelper.toString(service));
traits = TraitHelper.retrieve(service);
state.setTraits(traits);
for (; ; ) {
int stageId = getNextStageId();
Map<String, Object> masterData = getNextMasterData();
for (Map.Entry<String, Object> entry : masterData.entrySet()) {
state.put(entry.getKey(), entry.getValue());
}
log.trace("Received stage ID " + stageId);
DistStage stage = (DistStage) scenario.getStage(stageId, state, extras, null);
if (stage instanceof ScenarioCleanupStage) {
// this is always the last stage and is ran in main thread (not sc-main)
break;
}
TraitHelper.InjectResult result = null;
DistStageAck response;
Exception initException = null;
try {
result = TraitHelper.inject(stage, traits);
InitHelper.init(stage);
stage.initOnSlave(state);
} catch (Exception e) {
log.error("Stage initialization has failed", e);
initException = e;
}
if (initException != null) {
response = new DistStageAck(state).error("Stage initialization has failed", initException);
} else if (!stage.shouldExecute()) {
log.info("Stage should not be executed");
response = new DistStageAck(state);
} else if (result == TraitHelper.InjectResult.SKIP) {
log.info("Stage was skipped because it was missing some traits");
response = new DistStageAck(state);
} else if (result == TraitHelper.InjectResult.FAILURE) {
String message = "The stage was not executed because it missed some mandatory traits.";
log.error(message);
response = new DistStageAck(state).error(message, null);
} else {
String stageName = stage.getName();
log.info("Starting stage " + (log.isDebugEnabled() ? stage.toString() : stageName));
long start = TimeService.currentTimeMillis();
long end;
try {
response = stage.executeOnSlave();
end = TimeService.currentTimeMillis();
if (response == null) {
response = new DistStageAck(state).error("Stage returned null response", null);
}
log.info("Finished stage " + stageName);
response.setDuration(end - start);
} catch (Exception e) {
end = TimeService.currentTimeMillis();
log.error("Stage execution has failed", e);
response = new DistStageAck(state).error("Stage execution has failed", e);
} finally {
InitHelper.destroy(stage);
}
state.getTimeline().addEvent(Stage.STAGE, new Timeline.IntervalEvent(start, stageName, end - start));
}
sendResponse(response);
}
} finally {
if (traits != null) {
for (Object trait : traits.values()) {
InitHelper.destroy(trait);
}
}
InitHelper.destroy(service);
}
}
protected abstract int getNextStageId() throws IOException;
protected abstract Map<String, Object> getNextMasterData() throws IOException;
protected abstract void sendResponse(DistStageAck response) throws IOException;
protected void runCleanup() throws IOException {
DistStageAck response = null;
try {
Map<String, String> extras = getCurrentExtras(configuration, cluster);
ScenarioCleanupStage stage = (ScenarioCleanupStage) scenario.getStage(scenario.getStageCount() - 1, state, extras, null);
InitHelper.init(stage);
stage.initOnSlave(state);
log.info("Starting stage " + (log.isDebugEnabled() ? stage.toString() : stage.getName()));
response = stage.executeOnSlave();
} catch (Exception e) {
log.error("Stage execution has failed", e);
response = new DistStageAck(state).error("Stage execution has failed", e);
} finally {
if (response == null) {
response = new DistStageAck(state).error("Stage returned null response", null);
}
sendResponse(response);
}
}
protected abstract Map<String, String> getCurrentExtras(Configuration configuration, Cluster cluster);
// In RadarGun 2.0, we had to run each service in new thread in order to prevent
// classloader leaking through thread locals. This is not necessary anymore,
// but we still do checks in ScenarioCleanupStage
protected class ScenarioRunner extends Thread {
protected ScenarioRunner() {
super("sc-main");
}
@Override
public void run() {
try {
scenarioLoop();
} catch (IOException e) {
log.error("Communication with master failed", e);
e.printStackTrace();
ShutDownHook.exit(127);
} catch (Throwable t) {
log.error("Unexpected error in scenario", t);
t.printStackTrace();
ShutDownHook.exit(127);
}
}
}
}
| Add stage name to failure messages to ease debugging
| core/src/main/java/org/radargun/SlaveBase.java | Add stage name to failure messages to ease debugging | <ide><path>ore/src/main/java/org/radargun/SlaveBase.java
<ide> log.info("Service is " + service.getClass().getSimpleName() + PropertyHelper.toString(service));
<ide> traits = TraitHelper.retrieve(service);
<ide> state.setTraits(traits);
<del> for (; ; ) {
<add> for (;;) {
<ide> int stageId = getNextStageId();
<ide> Map<String, Object> masterData = getNextMasterData();
<ide> for (Map.Entry<String, Object> entry : masterData.entrySet()) {
<ide> InitHelper.init(stage);
<ide> stage.initOnSlave(state);
<ide> } catch (Exception e) {
<del> log.error("Stage initialization has failed", e);
<add> log.error("Stage '" + stage.getName() + "' initialization has failed", e);
<ide> initException = e;
<ide> }
<ide> if (initException != null) {
<del> response = new DistStageAck(state).error("Stage initialization has failed", initException);
<add> response = new DistStageAck(state).error("Stage '" + stage.getName() + "' initialization has failed",
<add> initException);
<ide> } else if (!stage.shouldExecute()) {
<del> log.info("Stage should not be executed");
<add> log.info("Stage '" + stage.getName() + "' should not be executed");
<ide> response = new DistStageAck(state);
<ide> } else if (result == TraitHelper.InjectResult.SKIP) {
<del> log.info("Stage was skipped because it was missing some traits");
<add> log.info("Stage '" + stage.getName() + "' was skipped because it was missing some traits");
<ide> response = new DistStageAck(state);
<ide> } else if (result == TraitHelper.InjectResult.FAILURE) {
<del> String message = "The stage was not executed because it missed some mandatory traits.";
<add> String message = "The stage '" + stage.getName()
<add> + "' was not executed because it missed some mandatory traits.";
<ide> log.error(message);
<ide> response = new DistStageAck(state).error(message, null);
<ide> } else {
<ide> DistStageAck response = null;
<ide> try {
<ide> Map<String, String> extras = getCurrentExtras(configuration, cluster);
<del> ScenarioCleanupStage stage = (ScenarioCleanupStage) scenario.getStage(scenario.getStageCount() - 1, state, extras, null);
<add> ScenarioCleanupStage stage = (ScenarioCleanupStage) scenario.getStage(scenario.getStageCount() - 1, state,
<add> extras, null);
<ide> InitHelper.init(stage);
<ide> stage.initOnSlave(state);
<ide> log.info("Starting stage " + (log.isDebugEnabled() ? stage.toString() : stage.getName())); |
|
Java | bsd-3-clause | 6296b9f2b9234df9f7cf2faed945423511cc1aad | 0 | TheGreenMachine/Zeke-Java,srujun/Zeke-Java |
package com.edinarobotics.zeke;
import com.edinarobotics.utils.gamepad.FilteredGamepad;
import com.edinarobotics.utils.gamepad.Gamepad;
import com.edinarobotics.utils.gamepad.gamepadfilters.*;
import java.util.Vector;
/**
* Controls handles creating the {@link Gamepad} objects used to control the
* robot as well as binding the proper Commands to button actions.
*/
public class Controls {
private static Controls instance;
public final Gamepad gamepad1;
private Controls() {
Vector driveGamepadFilters = new Vector();
driveGamepadFilters.addElement(new GamepadDeadzoneFilter(0.1));
driveGamepadFilters.addElement(new GamepadPowerFilter(2));
GamepadFilterSet driveGamepadFilterSet = new GamepadFilterSet(driveGamepadFilters);
gamepad1 = new FilteredGamepad(1, driveGamepadFilterSet);
}
/**
* Returns the proper instance of Controls. This method creates a new
* Controls object the first time it is called and returns that object for
* each subsequent call.
*
* @return The current instance of Controls.
*/
public static Controls getInstance() {
if (instance == null) {
instance = new Controls();
}
return instance;
}
}
| src/com/edinarobotics/zeke/Controls.java |
package com.edinarobotics.zeke;
/**
* Controls handles creating the {@link Gamepad} objects used to control the
* robot as well as binding the proper Commands to button actions.
*/
public class Controls {
private static Controls instance;
private Controls() {
}
/**
* Returns the proper instance of Controls. This method creates a new
* Controls object the first time it is called and returns that object for
* each subsequent call.
*
* @return The current instance of Controls.
*/
public static Controls getInstance() {
if (instance == null) {
instance = new Controls();
}
return instance;
}
}
| Added drive Gamepad to Controls.
Added drive FilteredGamepad with a GamepadDeadzoneFilter and
GamepadPowerFilter.
| src/com/edinarobotics/zeke/Controls.java | Added drive Gamepad to Controls. | <ide><path>rc/com/edinarobotics/zeke/Controls.java
<ide>
<ide> package com.edinarobotics.zeke;
<ide>
<add>import com.edinarobotics.utils.gamepad.FilteredGamepad;
<add>import com.edinarobotics.utils.gamepad.Gamepad;
<add>import com.edinarobotics.utils.gamepad.gamepadfilters.*;
<add>import java.util.Vector;
<ide> /**
<ide> * Controls handles creating the {@link Gamepad} objects used to control the
<ide> * robot as well as binding the proper Commands to button actions.
<ide> public class Controls {
<ide>
<ide> private static Controls instance;
<add> public final Gamepad gamepad1;
<ide>
<ide> private Controls() {
<add> Vector driveGamepadFilters = new Vector();
<add> driveGamepadFilters.addElement(new GamepadDeadzoneFilter(0.1));
<add> driveGamepadFilters.addElement(new GamepadPowerFilter(2));
<add> GamepadFilterSet driveGamepadFilterSet = new GamepadFilterSet(driveGamepadFilters);
<add> gamepad1 = new FilteredGamepad(1, driveGamepadFilterSet);
<ide>
<ide> }
<ide> |
|
Java | mit | f366b3811e6949a651da9fb0ef091e06a2ab246a | 0 | Jpoliachik/react-native-navigation,wix/react-native-navigation,Jpoliachik/react-native-navigation,guyca/react-native-navigation,thanhzusu/react-native-navigation,guyca/react-native-navigation,ceyhuno/react-native-navigation,thanhzusu/react-native-navigation,pqkluan/react-native-navigation,ceyhuno/react-native-navigation,3sidedcube/react-native-navigation,wix/react-native-navigation,pqkluan/react-native-navigation,thanhzusu/react-native-navigation,Jpoliachik/react-native-navigation,wix/react-native-navigation,3sidedcube/react-native-navigation,wix/react-native-navigation,Jpoliachik/react-native-navigation,pqkluan/react-native-navigation,ceyhuno/react-native-navigation,thanhzusu/react-native-navigation,ceyhuno/react-native-navigation,chicojasl/react-native-navigation,guyca/react-native-navigation,3sidedcube/react-native-navigation,Jpoliachik/react-native-navigation,thanhzusu/react-native-navigation,chicojasl/react-native-navigation,ceyhuno/react-native-navigation,chicojasl/react-native-navigation,ceyhuno/react-native-navigation,chicojasl/react-native-navigation,wix/react-native-navigation,pqkluan/react-native-navigation,chicojasl/react-native-navigation,guyca/react-native-navigation,thanhzusu/react-native-navigation,wix/react-native-navigation,chicojasl/react-native-navigation,3sidedcube/react-native-navigation,Jpoliachik/react-native-navigation | package com.reactnativenavigation.params.parsers;
import android.os.Bundle;
import com.reactnativenavigation.params.ActivityParams;
import com.reactnativenavigation.params.AppStyle;
import com.reactnativenavigation.params.SideMenuParams;
import com.reactnativenavigation.views.SideMenu;
public class ActivityParamsParser extends Parser {
public static ActivityParams parse(Bundle params) {
ActivityParams result = new ActivityParams();
AppStyle.setAppStyle(params);
if (hasKey(params, "screen")) {
result.type = ActivityParams.Type.SingleScreen;
result.screenParams = ScreenParamsParser.parse(params.getBundle("screen"));
}
if (hasKey(params, "tabs")) {
result.type = ActivityParams.Type.TabBased;
result.tabParams = new ScreenParamsParser().parseTabs(params.getBundle("tabs"));
if (result.tabParams.size() == 0) {
throw new RuntimeException("Tried to start tab based app with zero tabs");
}
}
if (hasKey(params, "sideMenu")) {
SideMenuParams[] sideMenus = SideMenuParamsParser.parse(params.getBundle("sideMenu"));
result.leftSideMenuParams = sideMenus[SideMenu.Side.Left.ordinal()];
result.rightSideMenuParams = sideMenus[SideMenu.Side.Right.ordinal()];
}
result.animateShow = params.getBoolean("animateShow", true);
return result;
}
}
| android/app/src/main/java/com/reactnativenavigation/params/parsers/ActivityParamsParser.java | package com.reactnativenavigation.params.parsers;
import android.os.Bundle;
import com.reactnativenavigation.params.ActivityParams;
import com.reactnativenavigation.params.AppStyle;
import com.reactnativenavigation.params.SideMenuParams;
import com.reactnativenavigation.views.SideMenu;
public class ActivityParamsParser extends Parser {
public static ActivityParams parse(Bundle params) {
ActivityParams result = new ActivityParams();
AppStyle.setAppStyle(params);
if (hasKey(params, "screen")) {
result.type = ActivityParams.Type.SingleScreen;
result.screenParams = ScreenParamsParser.parse(params.getBundle("screen"));
}
if (hasKey(params, "tabs")) {
result.type = ActivityParams.Type.TabBased;
result.tabParams = new ScreenParamsParser().parseTabs(params.getBundle("tabs"));
}
if (hasKey(params, "sideMenu")) {
SideMenuParams[] sideMenus = SideMenuParamsParser.parse(params.getBundle("sideMenu"));
result.leftSideMenuParams = sideMenus[SideMenu.Side.Left.ordinal()];
result.rightSideMenuParams = sideMenus[SideMenu.Side.Right.ordinal()];
}
result.animateShow = params.getBoolean("animateShow", true);
return result;
}
}
| Throw exception when calling startTabBasedApp with zero tabs
| android/app/src/main/java/com/reactnativenavigation/params/parsers/ActivityParamsParser.java | Throw exception when calling startTabBasedApp with zero tabs | <ide><path>ndroid/app/src/main/java/com/reactnativenavigation/params/parsers/ActivityParamsParser.java
<ide> if (hasKey(params, "tabs")) {
<ide> result.type = ActivityParams.Type.TabBased;
<ide> result.tabParams = new ScreenParamsParser().parseTabs(params.getBundle("tabs"));
<add> if (result.tabParams.size() == 0) {
<add> throw new RuntimeException("Tried to start tab based app with zero tabs");
<add> }
<ide> }
<ide>
<ide> if (hasKey(params, "sideMenu")) { |
|
Java | apache-2.0 | e8a197eaceee5ac1f08f720275bdcc6225b704fe | 0 | Donnerbart/hazelcast,lmjacksoniii/hazelcast,mdogan/hazelcast,dsukhoroslov/hazelcast,tufangorel/hazelcast,tufangorel/hazelcast,juanavelez/hazelcast,Donnerbart/hazelcast,emrahkocaman/hazelcast,dbrimley/hazelcast,emrahkocaman/hazelcast,dbrimley/hazelcast,tombujok/hazelcast,dsukhoroslov/hazelcast,lmjacksoniii/hazelcast,mdogan/hazelcast,tkountis/hazelcast,tkountis/hazelcast,emre-aydin/hazelcast,mdogan/hazelcast,emre-aydin/hazelcast,juanavelez/hazelcast,mesutcelik/hazelcast,Donnerbart/hazelcast,emre-aydin/hazelcast,tkountis/hazelcast,dbrimley/hazelcast,tombujok/hazelcast,mesutcelik/hazelcast,tufangorel/hazelcast,mesutcelik/hazelcast | /*
* Copyright (c) 2008-2013, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.client;
import com.hazelcast.client.config.ClientConfig;
import com.hazelcast.client.nearcache.ClientNearCache;
import com.hazelcast.config.InMemoryFormat;
import com.hazelcast.config.MapConfig;
import com.hazelcast.config.NearCacheConfig;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.HazelcastTest;
import com.hazelcast.core.IMap;
import com.hazelcast.monitor.NearCacheStats;
import com.hazelcast.test.AssertTask;
import com.hazelcast.test.HazelcastSerialClassRunner;
import com.hazelcast.test.HazelcastTestSupport;
import com.hazelcast.test.TestHazelcastInstanceFactory;
import com.hazelcast.test.annotation.ProblematicTest;
import com.hazelcast.test.annotation.QuickTest;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import java.util.HashSet;
import java.util.concurrent.Future;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
@RunWith(HazelcastSerialClassRunner.class)
@Category(QuickTest.class)
public class ClientNearCacheTest {
@After
@Before
public void cleanup() throws Exception {
HazelcastClient.shutdownAll();
Hazelcast.shutdownAll();
}
@Test
public void testNearCache() {
final HazelcastInstance hz1 = Hazelcast.newHazelcastInstance();
final HazelcastInstance hz2 = Hazelcast.newHazelcastInstance();
final ClientConfig clientConfig = new ClientConfig();
clientConfig.getNetworkConfig().setSmartRouting(false);
clientConfig.addNearCacheConfig("map*", new NearCacheConfig().setInMemoryFormat(InMemoryFormat.OBJECT));
final HazelcastInstance client = HazelcastClient.newHazelcastClient(clientConfig);
final IMap map = client.getMap("map1");
for (int i = 0; i < 10 * 1000; i++) {
map.put("key" + i, "value" + i);
}
long begin = System.currentTimeMillis();
for (int i = 0; i < 1000; i++) {
map.get("key" + i);
}
long firstRead = System.currentTimeMillis() - begin;
begin = System.currentTimeMillis();
for (int i = 0; i < 1000; i++) {
map.get("key" + i);
}
long secondRead = System.currentTimeMillis() - begin;
assertTrue(secondRead < firstRead);
}
@Test
public void testGetAll() throws Exception {
final String mapName = "testGetAllWithNearCache";
ClientConfig config = new ClientConfig();
config.addNearCacheConfig(mapName, new NearCacheConfig());
HazelcastInstance instance1 = Hazelcast.newHazelcastInstance();
HazelcastInstance instance2 = Hazelcast.newHazelcastInstance();
HazelcastInstance client = HazelcastClient.newHazelcastClient(config);
IMap<Integer, Integer> map = client.getMap(mapName);
HashSet keys = new HashSet();
int size = 1000;
for (int i = 0; i < size; i++) {
map.put(i,i);
keys.add(i);
}
//populate near cache
for (int i = 0; i < size; i++) {
map.get(i);
}
map.getAll(keys);
NearCacheStats stats = map.getLocalMapStats().getNearCacheStats();
assertEquals(1000, stats.getHits());
}
@Test
public void testGetAsync() throws Exception {
final String mapName = "testGetAsyncWithNearCache";
ClientConfig config = new ClientConfig();
config.addNearCacheConfig(mapName, new NearCacheConfig());
HazelcastInstance instance1 = Hazelcast.newHazelcastInstance();
HazelcastInstance instance2 = Hazelcast.newHazelcastInstance();
HazelcastInstance client = HazelcastClient.newHazelcastClient(config);
IMap<Integer, Integer> map = client.getMap(mapName);
HashSet keys = new HashSet();
int size = 1000;
for (int i = 0; i < size; i++) {
map.put(i,i);
keys.add(i);
}
//populate near cache
for (int i = 0; i < size; i++) {
map.get(i);
}
for (int i = 0; i < size; i++) {
Future<Integer> async = map.getAsync(i);
async.get();
}
NearCacheStats stats = map.getLocalMapStats().getNearCacheStats();
assertEquals(1000, stats.getHits());
}
@Test
public void testIssue2009() throws Exception {
final String mapName = "testIssue2009";
ClientConfig config = new ClientConfig();
config.addNearCacheConfig(mapName, new NearCacheConfig());
HazelcastInstance instance1 = Hazelcast.newHazelcastInstance();
HazelcastInstance instance2 = Hazelcast.newHazelcastInstance();
HazelcastInstance client = HazelcastClient.newHazelcastClient(config);
IMap map = client.getMap(mapName);
NearCacheStats stats = map.getLocalMapStats().getNearCacheStats();
assertNotNull(stats);
}
@Test
public void nearCacheEvect_withMaxSize() {
final String mapName = "nearCashWithMaxSizeSet";
final HazelcastInstance hz1 = Hazelcast.newHazelcastInstance();
final HazelcastInstance hz2 = Hazelcast.newHazelcastInstance();
final ClientConfig clientConfig = new ClientConfig();
clientConfig.getNetworkConfig().setSmartRouting(false);
final int cacheSize = 100;
NearCacheConfig cashConfig = new NearCacheConfig();
cashConfig.setInMemoryFormat(InMemoryFormat.OBJECT);
cashConfig.setMaxSize(cacheSize);
clientConfig.addNearCacheConfig(mapName, cashConfig);
final HazelcastInstance client = HazelcastClient.newHazelcastClient(clientConfig);
final IMap map = client.getMap(mapName);
for (int i = 0; i < cacheSize+1; i++) {
map.put("key" + i, "value" + i);
}
//populate near cache
for (int i = 0; i < cacheSize+1; i++) {
map.get(i);
}
HazelcastTestSupport.assertTrueEventually(new AssertTask() {
@Override
public void run() throws Exception {
final NearCacheStats stats = map.getLocalMapStats().getNearCacheStats();
assertEquals(80, stats.getOwnedEntryCount());
}
});
}
@Test
public void getNearCacheStatsBeforePopulation() {
final String mapName = "getNearCashStatsBeforePopulation";
final HazelcastInstance hz1 = Hazelcast.newHazelcastInstance();
final HazelcastInstance hz2 = Hazelcast.newHazelcastInstance();
NearCacheConfig cacheConfig = new NearCacheConfig();
cacheConfig.setInMemoryFormat(InMemoryFormat.OBJECT);
final ClientConfig clientConfig = new ClientConfig();
clientConfig.getNetworkConfig().setSmartRouting(false);
clientConfig.addNearCacheConfig(mapName, cacheConfig);
final HazelcastInstance client = HazelcastClient.newHazelcastClient(clientConfig);
final IMap map = client.getMap(mapName);
for (int i = 0; i < 300; i++) {
map.put("key" + i, "value" + i);
}
final NearCacheStats stats = map.getLocalMapStats().getNearCacheStats();
//This Test throws a NullPointerException
assertEquals(0, stats.getOwnedEntryCount());
}
} | hazelcast-client/src/test/java/com/hazelcast/client/ClientNearCacheTest.java | /*
* Copyright (c) 2008-2013, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.client;
import com.hazelcast.client.config.ClientConfig;
import com.hazelcast.client.nearcache.ClientNearCache;
import com.hazelcast.config.InMemoryFormat;
import com.hazelcast.config.MapConfig;
import com.hazelcast.config.NearCacheConfig;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.HazelcastTest;
import com.hazelcast.core.IMap;
import com.hazelcast.monitor.NearCacheStats;
import com.hazelcast.test.AssertTask;
import com.hazelcast.test.HazelcastSerialClassRunner;
import com.hazelcast.test.HazelcastTestSupport;
import com.hazelcast.test.TestHazelcastInstanceFactory;
import com.hazelcast.test.annotation.ProblematicTest;
import com.hazelcast.test.annotation.QuickTest;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import java.util.HashSet;
import java.util.concurrent.Future;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
@RunWith(HazelcastSerialClassRunner.class)
@Category(QuickTest.class)
public class ClientNearCacheTest {
@After
@Before
public void cleanup() throws Exception {
HazelcastClient.shutdownAll();
Hazelcast.shutdownAll();
}
@Test
public void testNearCache() {
final HazelcastInstance hz1 = Hazelcast.newHazelcastInstance();
final HazelcastInstance hz2 = Hazelcast.newHazelcastInstance();
final ClientConfig clientConfig = new ClientConfig();
clientConfig.getNetworkConfig().setSmartRouting(false);
clientConfig.addNearCacheConfig("map*", new NearCacheConfig().setInMemoryFormat(InMemoryFormat.OBJECT));
final HazelcastInstance client = HazelcastClient.newHazelcastClient(clientConfig);
final IMap map = client.getMap("map1");
for (int i = 0; i < 10 * 1000; i++) {
map.put("key" + i, "value" + i);
}
long begin = System.currentTimeMillis();
for (int i = 0; i < 1000; i++) {
map.get("key" + i);
}
long firstRead = System.currentTimeMillis() - begin;
begin = System.currentTimeMillis();
for (int i = 0; i < 1000; i++) {
map.get("key" + i);
}
long secondRead = System.currentTimeMillis() - begin;
assertTrue(secondRead < firstRead);
}
@Test
public void testGetAll() throws Exception {
final String mapName = "testGetAllWithNearCache";
ClientConfig config = new ClientConfig();
config.addNearCacheConfig(mapName, new NearCacheConfig());
HazelcastInstance instance1 = Hazelcast.newHazelcastInstance();
HazelcastInstance instance2 = Hazelcast.newHazelcastInstance();
HazelcastInstance client = HazelcastClient.newHazelcastClient(config);
IMap<Integer, Integer> map = client.getMap(mapName);
HashSet keys = new HashSet();
int size = 1000;
for (int i = 0; i < size; i++) {
map.put(i,i);
keys.add(i);
}
//populate near cache
for (int i = 0; i < size; i++) {
map.get(i);
}
map.getAll(keys);
NearCacheStats stats = map.getLocalMapStats().getNearCacheStats();
assertEquals(1000, stats.getHits());
}
@Test
public void testGetAsync() throws Exception {
final String mapName = "testGetAsyncWithNearCache";
ClientConfig config = new ClientConfig();
config.addNearCacheConfig(mapName, new NearCacheConfig());
HazelcastInstance instance1 = Hazelcast.newHazelcastInstance();
HazelcastInstance instance2 = Hazelcast.newHazelcastInstance();
HazelcastInstance client = HazelcastClient.newHazelcastClient(config);
IMap<Integer, Integer> map = client.getMap(mapName);
HashSet keys = new HashSet();
int size = 1000;
for (int i = 0; i < size; i++) {
map.put(i,i);
keys.add(i);
}
//populate near cache
for (int i = 0; i < size; i++) {
map.get(i);
}
for (int i = 0; i < size; i++) {
Future<Integer> async = map.getAsync(i);
async.get();
}
NearCacheStats stats = map.getLocalMapStats().getNearCacheStats();
assertEquals(1000, stats.getHits());
}
@Test
public void testIssue2009() throws Exception {
final String mapName = "testIssue2009";
ClientConfig config = new ClientConfig();
config.addNearCacheConfig(mapName, new NearCacheConfig());
HazelcastInstance instance1 = Hazelcast.newHazelcastInstance();
HazelcastInstance instance2 = Hazelcast.newHazelcastInstance();
HazelcastInstance client = HazelcastClient.newHazelcastClient(config);
IMap map = client.getMap(mapName);
NearCacheStats stats = map.getLocalMapStats().getNearCacheStats();
assertNotNull(stats);
}
@Test
@Category(ProblematicTest.class)
public void nearCacheWithMaxSizeSet() {
final String mapName = "nearCashWithMaxSizeSet";
final HazelcastInstance hz1 = Hazelcast.newHazelcastInstance();
final HazelcastInstance hz2 = Hazelcast.newHazelcastInstance();
final ClientConfig clientConfig = new ClientConfig();
clientConfig.getNetworkConfig().setSmartRouting(false);
final int cacheSize = 2;
NearCacheConfig cashConfig = new NearCacheConfig();
cashConfig.setInMemoryFormat(InMemoryFormat.OBJECT);
cashConfig.setMaxSize(cacheSize);
clientConfig.addNearCacheConfig(mapName, cashConfig);
final HazelcastInstance client = HazelcastClient.newHazelcastClient(clientConfig);
final IMap map = client.getMap(mapName);
for (int i = 0; i < cacheSize * 100; i++) {
map.put("key" + i, "value" + i);
}
//populate near cache
for (int i = 0; i < cacheSize * 100; i++) {
map.get(i);
}
final NearCacheStats stats = map.getLocalMapStats().getNearCacheStats();
HazelcastTestSupport.assertTrueEventually(new AssertTask() {
@Override
public void run() throws Exception {
assertEquals(cacheSize, stats.getOwnedEntryCount());
}
});
}
@Test
public void getNearCacheStatsBeforePopulation() {
final String mapName = "getNearCashStatsBeforePopulation";
final HazelcastInstance hz1 = Hazelcast.newHazelcastInstance();
final HazelcastInstance hz2 = Hazelcast.newHazelcastInstance();
NearCacheConfig cacheConfig = new NearCacheConfig();
cacheConfig.setInMemoryFormat(InMemoryFormat.OBJECT);
final ClientConfig clientConfig = new ClientConfig();
clientConfig.getNetworkConfig().setSmartRouting(false);
clientConfig.addNearCacheConfig(mapName, cacheConfig);
final HazelcastInstance client = HazelcastClient.newHazelcastClient(clientConfig);
final IMap map = client.getMap(mapName);
for (int i = 0; i < 300; i++) {
map.put("key" + i, "value" + i);
}
final NearCacheStats stats = map.getLocalMapStats().getNearCacheStats();
//This Test throws a NullPointerException
assertEquals(0, stats.getOwnedEntryCount());
}
} | fix test
| hazelcast-client/src/test/java/com/hazelcast/client/ClientNearCacheTest.java | fix test | <ide><path>azelcast-client/src/test/java/com/hazelcast/client/ClientNearCacheTest.java
<ide> }
<ide>
<ide> @Test
<del> @Category(ProblematicTest.class)
<del> public void nearCacheWithMaxSizeSet() {
<add> public void nearCacheEvect_withMaxSize() {
<ide> final String mapName = "nearCashWithMaxSizeSet";
<ide> final HazelcastInstance hz1 = Hazelcast.newHazelcastInstance();
<ide> final HazelcastInstance hz2 = Hazelcast.newHazelcastInstance();
<ide> final ClientConfig clientConfig = new ClientConfig();
<ide> clientConfig.getNetworkConfig().setSmartRouting(false);
<ide>
<del> final int cacheSize = 2;
<add> final int cacheSize = 100;
<ide>
<ide> NearCacheConfig cashConfig = new NearCacheConfig();
<ide> cashConfig.setInMemoryFormat(InMemoryFormat.OBJECT);
<ide>
<ide> final IMap map = client.getMap(mapName);
<ide>
<del> for (int i = 0; i < cacheSize * 100; i++) {
<add> for (int i = 0; i < cacheSize+1; i++) {
<ide> map.put("key" + i, "value" + i);
<ide> }
<ide> //populate near cache
<del> for (int i = 0; i < cacheSize * 100; i++) {
<add> for (int i = 0; i < cacheSize+1; i++) {
<ide> map.get(i);
<ide> }
<ide>
<del> final NearCacheStats stats = map.getLocalMapStats().getNearCacheStats();
<ide> HazelcastTestSupport.assertTrueEventually(new AssertTask() {
<ide> @Override
<ide> public void run() throws Exception {
<del> assertEquals(cacheSize, stats.getOwnedEntryCount());
<add> final NearCacheStats stats = map.getLocalMapStats().getNearCacheStats();
<add> assertEquals(80, stats.getOwnedEntryCount());
<ide> }
<ide> });
<ide> } |
|
Java | apache-2.0 | 2348b113fd82a97b84662596834807f031a9a6ef | 0 | apache/tomcat,apache/tomcat,apache/tomcat,apache/tomcat,apache/tomcat | /*
* 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.coyote.http2;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import org.hamcrest.Description;
import org.hamcrest.MatcherAssert;
import org.hamcrest.TypeSafeMatcher;
import org.junit.Assert;
import org.junit.Test;
import org.apache.catalina.connector.Connector;
import org.apache.coyote.http11.AbstractHttp11Protocol;
import org.apache.coyote.http2.HpackEncoder.State;
import org.apache.tomcat.util.http.MimeHeaders;
import org.apache.tomcat.util.res.StringManager;
public class TestHttp2Limits extends Http2TestBase {
private static final StringManager sm = StringManager.getManager(TestHttp2Limits.class);
@Test
public void testSettingsOverheadLimits() throws Exception {
http2Connect(false);
for (int i = 0; i < 100; i++) {
try {
sendSettings(0, false);
parser.readFrame(true);
} catch (IOException ioe) {
// Server closed connection before client has a chance to read
// the Goaway frame. Treat this as a pass.
return;
}
String trace = output.getTrace();
if (trace.equals("0-Settings-Ack\n")) {
// Test continues
output.clearTrace();
} else if (trace.startsWith("0-Goaway-[1]-[11]-[Connection [")) {
// Test passed
return;
} else {
// Test failed
Assert.fail("Unexpected output: " + output.getTrace());
}
Thread.sleep(100);
}
// Test failed
Assert.fail("Connection not closed down");
}
@Test
public void testHeaderLimits1x128() throws Exception {
// Well within limits
doTestHeaderLimits(1, 128, FailureMode.NONE);
}
@Test
public void testHeaderLimits100x32() throws Exception {
// Just within default maxHeaderCount
// Note request has 4 standard headers
doTestHeaderLimits(96, 32, FailureMode.NONE);
}
@Test
public void testHeaderLimits101x32() throws Exception {
// Just above default maxHeaderCount
doTestHeaderLimits(97, 32, FailureMode.STREAM_RESET);
}
@Test
public void testHeaderLimits20x32WithLimit10() throws Exception {
// Check lower count limit is enforced
doTestHeaderLimits(20, 32, -1, 10, Constants.DEFAULT_MAX_HEADER_SIZE, 0,
FailureMode.STREAM_RESET);
}
@Test
public void testHeaderLimits8x1144() throws Exception {
// Just within default maxHttpHeaderSize
// per header overhead plus standard 3 headers
doTestHeaderLimits(7, 1144, FailureMode.NONE);
}
@Test
public void testHeaderLimits8x1145() throws Exception {
// Just above default maxHttpHeaderSize
doTestHeaderLimits(7, 1145, FailureMode.STREAM_RESET);
}
@Test
public void testHeaderLimits3x1024WithLimit2048() throws Exception {
// Check lower size limit is enforced
doTestHeaderLimits(3, 1024, -1, Constants.DEFAULT_MAX_HEADER_COUNT, 2 * 1024, 0,
FailureMode.STREAM_RESET);
}
@Test
public void testHeaderLimits1x12k() throws Exception {
// Bug 60232
doTestHeaderLimits(1, 12*1024, FailureMode.STREAM_RESET);
}
@Test
public void testHeaderLimits1x12kin1kChunks() throws Exception {
// Bug 60232
doTestHeaderLimits(1, 12*1024, 1024, FailureMode.STREAM_RESET);
}
@Test
public void testHeaderLimits1x12kin1kChunksThenNewRequest() throws Exception {
// Bug 60232
doTestHeaderLimits(1, 12*1024, 1024, FailureMode.STREAM_RESET);
output.clearTrace();
sendSimpleGetRequest(5);
parser.readFrame(true);
parser.readFrame(true);
Assert.assertEquals(getSimpleResponseTrace(5), output.getTrace());
}
@Test
public void testHeaderLimits1x32k() throws Exception {
// Bug 60232
doTestHeaderLimits(1, 32*1024, FailureMode.CONNECTION_RESET);
}
@Test
public void testHeaderLimits1x32kin1kChunks() throws Exception {
// Bug 60232
// 500ms per frame write delay to give server a chance to process the
// stream reset and the connection reset before the request is fully
// sent.
doTestHeaderLimits(1, 32*1024, 1024, 500, FailureMode.CONNECTION_RESET);
}
@Test
public void testHeaderLimits1x128k() throws Exception {
// Bug 60232
doTestHeaderLimits(1, 128*1024, FailureMode.CONNECTION_RESET);
}
@Test
public void testHeaderLimits1x512k() throws Exception {
// Bug 60232
doTestHeaderLimits(1, 512*1024, FailureMode.CONNECTION_RESET);
}
@Test
public void testHeaderLimits10x512k() throws Exception {
// Bug 60232
doTestHeaderLimits(10, 512*1024, FailureMode.CONNECTION_RESET);
}
private void doTestHeaderLimits(int headerCount, int headerSize, FailureMode failMode)
throws Exception {
doTestHeaderLimits(headerCount, headerSize, -1, failMode);
}
private void doTestHeaderLimits(int headerCount, int headerSize, int maxHeaderPayloadSize,
FailureMode failMode) throws Exception {
doTestHeaderLimits(headerCount, headerSize, maxHeaderPayloadSize, 0, failMode);
}
private void doTestHeaderLimits(int headerCount, int headerSize, int maxHeaderPayloadSize,
int delayms, FailureMode failMode) throws Exception {
doTestHeaderLimits(headerCount, headerSize, maxHeaderPayloadSize,
Constants.DEFAULT_MAX_HEADER_COUNT, Constants.DEFAULT_MAX_HEADER_SIZE, delayms,
failMode);
}
private void doTestHeaderLimits(int headerCount, int headerSize, int maxHeaderPayloadSize,
int maxHeaderCount, int maxHeaderSize, int delayms, FailureMode failMode)
throws Exception {
// Build the custom headers
List<String[]> customHeaders = new ArrayList<>();
StringBuilder headerValue = new StringBuilder(headerSize);
// Does not need to be secure
Random r = new Random();
for (int i = 0; i < headerSize; i++) {
// Random lower case characters
headerValue.append((char) ('a' + r.nextInt(26)));
}
String v = headerValue.toString();
for (int i = 0; i < headerCount; i++) {
customHeaders.add(new String[] {"X-TomcatTest" + i, v});
}
enableHttp2();
configureAndStartWebApplication();
http2Protocol.setMaxHeaderCount(maxHeaderCount);
((AbstractHttp11Protocol<?>) http2Protocol.getHttp11Protocol()).setMaxHttpHeaderSize(maxHeaderSize);
openClientConnection();
doHttpUpgrade();
sendClientPreface();
validateHttp2InitialResponse();
if (maxHeaderPayloadSize == -1) {
maxHeaderPayloadSize = output.getMaxFrameSize();
}
// Build the simple request
byte[] frameHeader = new byte[9];
// Assumes at least one custom header and that all headers are the same
// length. These assumptions are valid for these tests.
ByteBuffer headersPayload = ByteBuffer.allocate(200 + (int) (customHeaders.size() *
customHeaders.iterator().next()[1].length() * 1.2));
populateHeadersPayload(headersPayload, customHeaders, "/simple");
Exception e = null;
try {
int written = 0;
int left = headersPayload.limit() - written;
while (left > 0) {
int thisTime = Math.min(left, maxHeaderPayloadSize);
populateFrameHeader(frameHeader, written, left, thisTime, 3);
writeFrame(frameHeader, headersPayload, headersPayload.limit() - left,
thisTime, delayms);
left -= thisTime;
written += thisTime;
}
} catch (IOException ioe) {
e = ioe;
}
switch (failMode) {
case NONE: {
// Expect a normal response
readSimpleGetResponse();
Assert.assertEquals(getSimpleResponseTrace(3), output.getTrace());
Assert.assertNull(e);
break;
}
case STREAM_RESET: {
// Expect a stream reset
parser.readFrame(true);
Assert.assertEquals("3-RST-[11]\n", output.getTrace());
Assert.assertNull(e);
break;
}
case CONNECTION_RESET: {
// This message uses i18n and needs to be used in a regular
// expression (since we don't know the connection ID). Generate the
// string as a regular expression and then replace '[' and ']' with
// the escaped values.
String limitMessage = sm.getString("http2Parser.headerLimitSize", "\\d++", "3");
limitMessage = limitMessage.replace("[", "\\[").replace("]", "\\]");
// Connection reset. Connection ID will vary so use a pattern
// On some platform / Connector combinations (e.g. Windows / APR),
// the TCP connection close will be processed before the client gets
// a chance to read the connection close frame which will trigger an
// IOException when we try to read the frame.
// Note: Some platforms will allow the read if if the write fails
// above.
try {
parser.readFrame(true);
MatcherAssert.assertThat(output.getTrace(), RegexMatcher.matchesRegex(
"0-Goaway-\\[1\\]-\\[11\\]-\\[" + limitMessage + "\\]"));
} catch (IOException se) {
// Expected on some platforms
}
break;
}
}
}
private void populateHeadersPayload(ByteBuffer headersPayload, List<String[]> customHeaders,
String path) throws Exception {
MimeHeaders headers = new MimeHeaders();
headers.addValue(":method").setString("GET");
headers.addValue(":scheme").setString("http");
headers.addValue(":path").setString(path);
headers.addValue(":authority").setString("localhost:" + getPort());
for (String[] customHeader : customHeaders) {
headers.addValue(customHeader[0]).setString(customHeader[1]);
}
State state = hpackEncoder.encode(headers, headersPayload);
if (state != State.COMPLETE) {
throw new Exception("Unable to build headers");
}
headersPayload.flip();
log.debug("Headers payload generated of size [" + headersPayload.limit() + "]");
}
private void populateFrameHeader(byte[] frameHeader, int written, int left, int thisTime,
int streamId) throws Exception {
ByteUtil.setThreeBytes(frameHeader, 0, thisTime);
if (written == 0) {
frameHeader[3] = FrameType.HEADERS.getIdByte();
// Flags. End of stream
frameHeader[4] = 0x01;
} else {
frameHeader[3] = FrameType.CONTINUATION.getIdByte();
}
if (left == thisTime) {
// Flags. End of headers
frameHeader[4] = (byte) (frameHeader[4] + 0x04);
}
// Stream id
ByteUtil.set31Bits(frameHeader, 5, streamId);
}
@Test
public void testCookieLimit1() throws Exception {
doTestCookieLimit(1, 0);
}
@Test
public void testCookieLimit2() throws Exception {
doTestCookieLimit(2, 0);
}
@Test
public void testCookieLimit100() throws Exception {
doTestCookieLimit(100, 0);
}
@Test
public void testCookieLimit100WithLimit50() throws Exception {
doTestCookieLimit(100, 50, 1);
}
@Test
public void testCookieLimit200() throws Exception {
doTestCookieLimit(200, 0);
}
@Test
public void testCookieLimit201() throws Exception {
doTestCookieLimit(201, 1);
}
private void doTestCookieLimit(int cookieCount, int failMode) throws Exception {
doTestCookieLimit(cookieCount, Constants.DEFAULT_MAX_COOKIE_COUNT, failMode);
}
private void doTestCookieLimit(int cookieCount, int maxCookieCount, int failMode)
throws Exception {
enableHttp2();
Connector connector = getTomcatInstance().getConnector();
connector.setMaxCookieCount(maxCookieCount);
configureAndStartWebApplication();
openClientConnection();
doHttpUpgrade();
sendClientPreface();
validateHttp2InitialResponse();
output.setTraceBody(true);
byte[] frameHeader = new byte[9];
ByteBuffer headersPayload = ByteBuffer.allocate(8192);
List<String[]> customHeaders = new ArrayList<>();
for (int i = 0; i < cookieCount; i++) {
customHeaders.add(new String[] {"Cookie", "a" + cookieCount + "=b" + cookieCount});
}
populateHeadersPayload(headersPayload, customHeaders, "/cookie");
populateFrameHeader(frameHeader, 0, headersPayload.limit(), headersPayload.limit(), 3);
writeFrame(frameHeader, headersPayload);
switch (failMode) {
case 0: {
parser.readFrame(true);
parser.readFrame(true);
parser.readFrame(true);
System.out.println(output.getTrace());
Assert.assertEquals(getCookieResponseTrace(3, cookieCount), output.getTrace());
break;
}
case 1: {
// Check status is 400
parser.readFrame(true);
Assert.assertTrue(output.getTrace(), output.getTrace().startsWith(
"3-HeadersStart\n3-Header-[:status]-[400]"));
output.clearTrace();
// Check EOS followed by error page body
parser.readFrame(true);
Assert.assertTrue(output.getTrace(), output.getTrace().startsWith("3-EndOfStream\n3-Body-<!doctype"));
break;
}
default: {
Assert.fail("Unknown failure mode specified");
}
}
}
@Test
public void testPostWithTrailerHeadersDefaultLimit() throws Exception{
doTestPostWithTrailerHeaders(Constants.DEFAULT_MAX_TRAILER_COUNT,
Constants.DEFAULT_MAX_TRAILER_SIZE, FailureMode.NONE);
}
@Test
public void testPostWithTrailerHeadersCount0() throws Exception{
doTestPostWithTrailerHeaders(0, Constants.DEFAULT_MAX_TRAILER_SIZE,
FailureMode.STREAM_RESET);
}
@Test
public void testPostWithTrailerHeadersSize0() throws Exception{
doTestPostWithTrailerHeaders(Constants.DEFAULT_MAX_TRAILER_COUNT, 0,
FailureMode.CONNECTION_RESET);
}
private void doTestPostWithTrailerHeaders(int maxTrailerCount, int maxTrailerSize,
FailureMode failMode) throws Exception {
enableHttp2();
configureAndStartWebApplication();
((AbstractHttp11Protocol<?>) http2Protocol.getHttp11Protocol()).setAllowedTrailerHeaders(TRAILER_HEADER_NAME);
http2Protocol.setMaxTrailerCount(maxTrailerCount);
((AbstractHttp11Protocol<?>) http2Protocol.getHttp11Protocol()).setMaxTrailerSize(maxTrailerSize);
openClientConnection();
doHttpUpgrade();
sendClientPreface();
validateHttp2InitialResponse();
byte[] headersFrameHeader = new byte[9];
ByteBuffer headersPayload = ByteBuffer.allocate(128);
byte[] dataFrameHeader = new byte[9];
ByteBuffer dataPayload = ByteBuffer.allocate(256);
byte[] trailerFrameHeader = new byte[9];
ByteBuffer trailerPayload = ByteBuffer.allocate(256);
buildPostRequest(headersFrameHeader, headersPayload, false, dataFrameHeader, dataPayload,
null, trailerFrameHeader, trailerPayload, 3);
// Write the headers
writeFrame(headersFrameHeader, headersPayload);
// Body
writeFrame(dataFrameHeader, dataPayload);
// Trailers
writeFrame(trailerFrameHeader, trailerPayload);
switch (failMode) {
case NONE: {
parser.readFrame(true);
parser.readFrame(true);
parser.readFrame(true);
parser.readFrame(true);
String len = Integer.toString(256 + TRAILER_HEADER_VALUE.length());
Assert.assertEquals("0-WindowSize-[256]\n" +
"3-WindowSize-[256]\n" +
"3-HeadersStart\n" +
"3-Header-[:status]-[200]\n" +
"3-Header-[content-length]-[" + len + "]\n" +
"3-Header-[date]-["+ DEFAULT_DATE + "]\n" +
"3-HeadersEnd\n" +
"3-Body-" +
len +
"\n" +
"3-EndOfStream\n",
output.getTrace());
break;
}
case STREAM_RESET: {
// NIO2 can sometimes send window updates depending timing
skipWindowSizeFrames();
Assert.assertEquals("3-RST-[11]\n", output.getTrace());
break;
}
case CONNECTION_RESET: {
// NIO2 can sometimes send window updates depending timing
skipWindowSizeFrames();
// This message uses i18n and needs to be used in a regular
// expression (since we don't know the connection ID). Generate the
// string as a regular expression and then replace '[' and ']' with
// the escaped values.
String limitMessage = sm.getString("http2Parser.headerLimitSize", "\\d++", "3");
limitMessage = limitMessage.replace("[", "\\[").replace("]", "\\]");
MatcherAssert.assertThat(output.getTrace(), RegexMatcher.matchesRegex(
"0-Goaway-\\[3\\]-\\[11\\]-\\[" + limitMessage + "\\]"));
break;
}
}
}
private enum FailureMode {
NONE,
STREAM_RESET,
CONNECTION_RESET,
}
private static class RegexMatcher extends TypeSafeMatcher<String> {
private final String pattern;
public RegexMatcher(String pattern) {
this.pattern = pattern;
}
@Override
public void describeTo(Description description) {
description.appendText("match to regular expression pattern [" + pattern + "]");
}
@Override
protected boolean matchesSafely(String item) {
return item.matches(pattern);
}
public static RegexMatcher matchesRegex(String pattern) {
return new RegexMatcher(pattern);
}
}
}
| test/org/apache/coyote/http2/TestHttp2Limits.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.coyote.http2;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import org.hamcrest.Description;
import org.hamcrest.MatcherAssert;
import org.hamcrest.TypeSafeMatcher;
import org.junit.Assert;
import org.junit.Test;
import org.apache.catalina.connector.Connector;
import org.apache.coyote.http11.AbstractHttp11Protocol;
import org.apache.coyote.http2.HpackEncoder.State;
import org.apache.tomcat.util.http.MimeHeaders;
import org.apache.tomcat.util.res.StringManager;
public class TestHttp2Limits extends Http2TestBase {
private static final StringManager sm = StringManager.getManager(TestHttp2Limits.class);
@Test
public void testSettingsOverheadLimits() throws Exception {
http2Connect(false);
for (int i = 0; i < 100; i++) {
sendSettings(0, false);
try {
parser.readFrame(true);
} catch (IOException ioe) {
// Server closed connection before client has a chance to read
// the Goaway frame. Treat this as a pass.
return;
}
String trace = output.getTrace();
if (trace.equals("0-Settings-Ack\n")) {
// Test continues
output.clearTrace();
} else if (trace.startsWith("0-Goaway-[1]-[11]-[Connection [")) {
// Test passed
return;
} else {
// Test failed
Assert.fail("Unexpected output: " + output.getTrace());
}
Thread.sleep(100);
}
// Test failed
Assert.fail("Connection not closed down");
}
@Test
public void testHeaderLimits1x128() throws Exception {
// Well within limits
doTestHeaderLimits(1, 128, FailureMode.NONE);
}
@Test
public void testHeaderLimits100x32() throws Exception {
// Just within default maxHeaderCount
// Note request has 4 standard headers
doTestHeaderLimits(96, 32, FailureMode.NONE);
}
@Test
public void testHeaderLimits101x32() throws Exception {
// Just above default maxHeaderCount
doTestHeaderLimits(97, 32, FailureMode.STREAM_RESET);
}
@Test
public void testHeaderLimits20x32WithLimit10() throws Exception {
// Check lower count limit is enforced
doTestHeaderLimits(20, 32, -1, 10, Constants.DEFAULT_MAX_HEADER_SIZE, 0,
FailureMode.STREAM_RESET);
}
@Test
public void testHeaderLimits8x1144() throws Exception {
// Just within default maxHttpHeaderSize
// per header overhead plus standard 3 headers
doTestHeaderLimits(7, 1144, FailureMode.NONE);
}
@Test
public void testHeaderLimits8x1145() throws Exception {
// Just above default maxHttpHeaderSize
doTestHeaderLimits(7, 1145, FailureMode.STREAM_RESET);
}
@Test
public void testHeaderLimits3x1024WithLimit2048() throws Exception {
// Check lower size limit is enforced
doTestHeaderLimits(3, 1024, -1, Constants.DEFAULT_MAX_HEADER_COUNT, 2 * 1024, 0,
FailureMode.STREAM_RESET);
}
@Test
public void testHeaderLimits1x12k() throws Exception {
// Bug 60232
doTestHeaderLimits(1, 12*1024, FailureMode.STREAM_RESET);
}
@Test
public void testHeaderLimits1x12kin1kChunks() throws Exception {
// Bug 60232
doTestHeaderLimits(1, 12*1024, 1024, FailureMode.STREAM_RESET);
}
@Test
public void testHeaderLimits1x12kin1kChunksThenNewRequest() throws Exception {
// Bug 60232
doTestHeaderLimits(1, 12*1024, 1024, FailureMode.STREAM_RESET);
output.clearTrace();
sendSimpleGetRequest(5);
parser.readFrame(true);
parser.readFrame(true);
Assert.assertEquals(getSimpleResponseTrace(5), output.getTrace());
}
@Test
public void testHeaderLimits1x32k() throws Exception {
// Bug 60232
doTestHeaderLimits(1, 32*1024, FailureMode.CONNECTION_RESET);
}
@Test
public void testHeaderLimits1x32kin1kChunks() throws Exception {
// Bug 60232
// 500ms per frame write delay to give server a chance to process the
// stream reset and the connection reset before the request is fully
// sent.
doTestHeaderLimits(1, 32*1024, 1024, 500, FailureMode.CONNECTION_RESET);
}
@Test
public void testHeaderLimits1x128k() throws Exception {
// Bug 60232
doTestHeaderLimits(1, 128*1024, FailureMode.CONNECTION_RESET);
}
@Test
public void testHeaderLimits1x512k() throws Exception {
// Bug 60232
doTestHeaderLimits(1, 512*1024, FailureMode.CONNECTION_RESET);
}
@Test
public void testHeaderLimits10x512k() throws Exception {
// Bug 60232
doTestHeaderLimits(10, 512*1024, FailureMode.CONNECTION_RESET);
}
private void doTestHeaderLimits(int headerCount, int headerSize, FailureMode failMode)
throws Exception {
doTestHeaderLimits(headerCount, headerSize, -1, failMode);
}
private void doTestHeaderLimits(int headerCount, int headerSize, int maxHeaderPayloadSize,
FailureMode failMode) throws Exception {
doTestHeaderLimits(headerCount, headerSize, maxHeaderPayloadSize, 0, failMode);
}
private void doTestHeaderLimits(int headerCount, int headerSize, int maxHeaderPayloadSize,
int delayms, FailureMode failMode) throws Exception {
doTestHeaderLimits(headerCount, headerSize, maxHeaderPayloadSize,
Constants.DEFAULT_MAX_HEADER_COUNT, Constants.DEFAULT_MAX_HEADER_SIZE, delayms,
failMode);
}
private void doTestHeaderLimits(int headerCount, int headerSize, int maxHeaderPayloadSize,
int maxHeaderCount, int maxHeaderSize, int delayms, FailureMode failMode)
throws Exception {
// Build the custom headers
List<String[]> customHeaders = new ArrayList<>();
StringBuilder headerValue = new StringBuilder(headerSize);
// Does not need to be secure
Random r = new Random();
for (int i = 0; i < headerSize; i++) {
// Random lower case characters
headerValue.append((char) ('a' + r.nextInt(26)));
}
String v = headerValue.toString();
for (int i = 0; i < headerCount; i++) {
customHeaders.add(new String[] {"X-TomcatTest" + i, v});
}
enableHttp2();
configureAndStartWebApplication();
http2Protocol.setMaxHeaderCount(maxHeaderCount);
((AbstractHttp11Protocol<?>) http2Protocol.getHttp11Protocol()).setMaxHttpHeaderSize(maxHeaderSize);
openClientConnection();
doHttpUpgrade();
sendClientPreface();
validateHttp2InitialResponse();
if (maxHeaderPayloadSize == -1) {
maxHeaderPayloadSize = output.getMaxFrameSize();
}
// Build the simple request
byte[] frameHeader = new byte[9];
// Assumes at least one custom header and that all headers are the same
// length. These assumptions are valid for these tests.
ByteBuffer headersPayload = ByteBuffer.allocate(200 + (int) (customHeaders.size() *
customHeaders.iterator().next()[1].length() * 1.2));
populateHeadersPayload(headersPayload, customHeaders, "/simple");
Exception e = null;
try {
int written = 0;
int left = headersPayload.limit() - written;
while (left > 0) {
int thisTime = Math.min(left, maxHeaderPayloadSize);
populateFrameHeader(frameHeader, written, left, thisTime, 3);
writeFrame(frameHeader, headersPayload, headersPayload.limit() - left,
thisTime, delayms);
left -= thisTime;
written += thisTime;
}
} catch (IOException ioe) {
e = ioe;
}
switch (failMode) {
case NONE: {
// Expect a normal response
readSimpleGetResponse();
Assert.assertEquals(getSimpleResponseTrace(3), output.getTrace());
Assert.assertNull(e);
break;
}
case STREAM_RESET: {
// Expect a stream reset
parser.readFrame(true);
Assert.assertEquals("3-RST-[11]\n", output.getTrace());
Assert.assertNull(e);
break;
}
case CONNECTION_RESET: {
// This message uses i18n and needs to be used in a regular
// expression (since we don't know the connection ID). Generate the
// string as a regular expression and then replace '[' and ']' with
// the escaped values.
String limitMessage = sm.getString("http2Parser.headerLimitSize", "\\d++", "3");
limitMessage = limitMessage.replace("[", "\\[").replace("]", "\\]");
// Connection reset. Connection ID will vary so use a pattern
// On some platform / Connector combinations (e.g. Windows / APR),
// the TCP connection close will be processed before the client gets
// a chance to read the connection close frame which will trigger an
// IOException when we try to read the frame.
// Note: Some platforms will allow the read if if the write fails
// above.
try {
parser.readFrame(true);
MatcherAssert.assertThat(output.getTrace(), RegexMatcher.matchesRegex(
"0-Goaway-\\[1\\]-\\[11\\]-\\[" + limitMessage + "\\]"));
} catch (IOException se) {
// Expected on some platforms
}
break;
}
}
}
private void populateHeadersPayload(ByteBuffer headersPayload, List<String[]> customHeaders,
String path) throws Exception {
MimeHeaders headers = new MimeHeaders();
headers.addValue(":method").setString("GET");
headers.addValue(":scheme").setString("http");
headers.addValue(":path").setString(path);
headers.addValue(":authority").setString("localhost:" + getPort());
for (String[] customHeader : customHeaders) {
headers.addValue(customHeader[0]).setString(customHeader[1]);
}
State state = hpackEncoder.encode(headers, headersPayload);
if (state != State.COMPLETE) {
throw new Exception("Unable to build headers");
}
headersPayload.flip();
log.debug("Headers payload generated of size [" + headersPayload.limit() + "]");
}
private void populateFrameHeader(byte[] frameHeader, int written, int left, int thisTime,
int streamId) throws Exception {
ByteUtil.setThreeBytes(frameHeader, 0, thisTime);
if (written == 0) {
frameHeader[3] = FrameType.HEADERS.getIdByte();
// Flags. End of stream
frameHeader[4] = 0x01;
} else {
frameHeader[3] = FrameType.CONTINUATION.getIdByte();
}
if (left == thisTime) {
// Flags. End of headers
frameHeader[4] = (byte) (frameHeader[4] + 0x04);
}
// Stream id
ByteUtil.set31Bits(frameHeader, 5, streamId);
}
@Test
public void testCookieLimit1() throws Exception {
doTestCookieLimit(1, 0);
}
@Test
public void testCookieLimit2() throws Exception {
doTestCookieLimit(2, 0);
}
@Test
public void testCookieLimit100() throws Exception {
doTestCookieLimit(100, 0);
}
@Test
public void testCookieLimit100WithLimit50() throws Exception {
doTestCookieLimit(100, 50, 1);
}
@Test
public void testCookieLimit200() throws Exception {
doTestCookieLimit(200, 0);
}
@Test
public void testCookieLimit201() throws Exception {
doTestCookieLimit(201, 1);
}
private void doTestCookieLimit(int cookieCount, int failMode) throws Exception {
doTestCookieLimit(cookieCount, Constants.DEFAULT_MAX_COOKIE_COUNT, failMode);
}
private void doTestCookieLimit(int cookieCount, int maxCookieCount, int failMode)
throws Exception {
enableHttp2();
Connector connector = getTomcatInstance().getConnector();
connector.setMaxCookieCount(maxCookieCount);
configureAndStartWebApplication();
openClientConnection();
doHttpUpgrade();
sendClientPreface();
validateHttp2InitialResponse();
output.setTraceBody(true);
byte[] frameHeader = new byte[9];
ByteBuffer headersPayload = ByteBuffer.allocate(8192);
List<String[]> customHeaders = new ArrayList<>();
for (int i = 0; i < cookieCount; i++) {
customHeaders.add(new String[] {"Cookie", "a" + cookieCount + "=b" + cookieCount});
}
populateHeadersPayload(headersPayload, customHeaders, "/cookie");
populateFrameHeader(frameHeader, 0, headersPayload.limit(), headersPayload.limit(), 3);
writeFrame(frameHeader, headersPayload);
switch (failMode) {
case 0: {
parser.readFrame(true);
parser.readFrame(true);
parser.readFrame(true);
System.out.println(output.getTrace());
Assert.assertEquals(getCookieResponseTrace(3, cookieCount), output.getTrace());
break;
}
case 1: {
// Check status is 400
parser.readFrame(true);
Assert.assertTrue(output.getTrace(), output.getTrace().startsWith(
"3-HeadersStart\n3-Header-[:status]-[400]"));
output.clearTrace();
// Check EOS followed by error page body
parser.readFrame(true);
Assert.assertTrue(output.getTrace(), output.getTrace().startsWith("3-EndOfStream\n3-Body-<!doctype"));
break;
}
default: {
Assert.fail("Unknown failure mode specified");
}
}
}
@Test
public void testPostWithTrailerHeadersDefaultLimit() throws Exception{
doTestPostWithTrailerHeaders(Constants.DEFAULT_MAX_TRAILER_COUNT,
Constants.DEFAULT_MAX_TRAILER_SIZE, FailureMode.NONE);
}
@Test
public void testPostWithTrailerHeadersCount0() throws Exception{
doTestPostWithTrailerHeaders(0, Constants.DEFAULT_MAX_TRAILER_SIZE,
FailureMode.STREAM_RESET);
}
@Test
public void testPostWithTrailerHeadersSize0() throws Exception{
doTestPostWithTrailerHeaders(Constants.DEFAULT_MAX_TRAILER_COUNT, 0,
FailureMode.CONNECTION_RESET);
}
private void doTestPostWithTrailerHeaders(int maxTrailerCount, int maxTrailerSize,
FailureMode failMode) throws Exception {
enableHttp2();
configureAndStartWebApplication();
((AbstractHttp11Protocol<?>) http2Protocol.getHttp11Protocol()).setAllowedTrailerHeaders(TRAILER_HEADER_NAME);
http2Protocol.setMaxTrailerCount(maxTrailerCount);
((AbstractHttp11Protocol<?>) http2Protocol.getHttp11Protocol()).setMaxTrailerSize(maxTrailerSize);
openClientConnection();
doHttpUpgrade();
sendClientPreface();
validateHttp2InitialResponse();
byte[] headersFrameHeader = new byte[9];
ByteBuffer headersPayload = ByteBuffer.allocate(128);
byte[] dataFrameHeader = new byte[9];
ByteBuffer dataPayload = ByteBuffer.allocate(256);
byte[] trailerFrameHeader = new byte[9];
ByteBuffer trailerPayload = ByteBuffer.allocate(256);
buildPostRequest(headersFrameHeader, headersPayload, false, dataFrameHeader, dataPayload,
null, trailerFrameHeader, trailerPayload, 3);
// Write the headers
writeFrame(headersFrameHeader, headersPayload);
// Body
writeFrame(dataFrameHeader, dataPayload);
// Trailers
writeFrame(trailerFrameHeader, trailerPayload);
switch (failMode) {
case NONE: {
parser.readFrame(true);
parser.readFrame(true);
parser.readFrame(true);
parser.readFrame(true);
String len = Integer.toString(256 + TRAILER_HEADER_VALUE.length());
Assert.assertEquals("0-WindowSize-[256]\n" +
"3-WindowSize-[256]\n" +
"3-HeadersStart\n" +
"3-Header-[:status]-[200]\n" +
"3-Header-[content-length]-[" + len + "]\n" +
"3-Header-[date]-["+ DEFAULT_DATE + "]\n" +
"3-HeadersEnd\n" +
"3-Body-" +
len +
"\n" +
"3-EndOfStream\n",
output.getTrace());
break;
}
case STREAM_RESET: {
// NIO2 can sometimes send window updates depending timing
skipWindowSizeFrames();
Assert.assertEquals("3-RST-[11]\n", output.getTrace());
break;
}
case CONNECTION_RESET: {
// NIO2 can sometimes send window updates depending timing
skipWindowSizeFrames();
// This message uses i18n and needs to be used in a regular
// expression (since we don't know the connection ID). Generate the
// string as a regular expression and then replace '[' and ']' with
// the escaped values.
String limitMessage = sm.getString("http2Parser.headerLimitSize", "\\d++", "3");
limitMessage = limitMessage.replace("[", "\\[").replace("]", "\\]");
MatcherAssert.assertThat(output.getTrace(), RegexMatcher.matchesRegex(
"0-Goaway-\\[3\\]-\\[11\\]-\\[" + limitMessage + "\\]"));
break;
}
}
}
private enum FailureMode {
NONE,
STREAM_RESET,
CONNECTION_RESET,
}
private static class RegexMatcher extends TypeSafeMatcher<String> {
private final String pattern;
public RegexMatcher(String pattern) {
this.pattern = pattern;
}
@Override
public void describeTo(Description description) {
description.appendText("match to regular expression pattern [" + pattern + "]");
}
@Override
protected boolean matchesSafely(String item) {
return item.matches(pattern);
}
public static RegexMatcher matchesRegex(String pattern) {
return new RegexMatcher(pattern);
}
}
}
| Fix intermittently failing test
Writes as well as reads will break if the server closes the connection | test/org/apache/coyote/http2/TestHttp2Limits.java | Fix intermittently failing test | <ide><path>est/org/apache/coyote/http2/TestHttp2Limits.java
<ide> http2Connect(false);
<ide>
<ide> for (int i = 0; i < 100; i++) {
<del> sendSettings(0, false);
<ide> try {
<add> sendSettings(0, false);
<ide> parser.readFrame(true);
<ide> } catch (IOException ioe) {
<ide> // Server closed connection before client has a chance to read |
|
Java | mit | error: pathspec 'src/main/java/org/ftcTeam/utils/CryptoBoxLocation.java' did not match any file(s) known to git
| f68dee80f505089dbeaac5e107fd673800675762 | 1 | Innovotics/ftc8702 | package org.ftcTeam.utils;
/**
* Created by tylerkim on 11/13/16.
*/
public enum CryptoBoxLocation {
LEFT,
CENTER,
RIGHT,
UNKNOWN
}
| src/main/java/org/ftcTeam/utils/CryptoBoxLocation.java | Add cryptobox location
| src/main/java/org/ftcTeam/utils/CryptoBoxLocation.java | Add cryptobox location | <ide><path>rc/main/java/org/ftcTeam/utils/CryptoBoxLocation.java
<add>package org.ftcTeam.utils;
<add>
<add>/**
<add> * Created by tylerkim on 11/13/16.
<add> */
<add>
<add>public enum CryptoBoxLocation {
<add>
<add> LEFT,
<add> CENTER,
<add> RIGHT,
<add> UNKNOWN
<add>} |
|
Java | apache-2.0 | dd70a3b2a2af2c7dda0d7d9c8b97833a47456418 | 0 | twitter/cloudhopper-commons | /** DO NOT EDIT THIS FILE. IT IS AUTO GENERATED BY MAVEN */
package com.cloudhopper.commons.xbean;
public final class Version {
private static final String TIMESTAMP="20120216-1720";
private static final String VERSION="2.0.0";
private static final String NAME="ch-commons-xbean";
private static final String VENDOR="cloudhopper";
private static final String LONG_VERSION="2.0.0 (Build @ 20120216-1720)";
/** Returns the library vendor such as "cloudhopper" */
static public String getVendor() { return VENDOR; }
/** Returns the library build timestamp such as "20120216-1720" */
static public String getTimestamp() { return TIMESTAMP; }
/** Returns the library name such as "ch-commons-xbean" */
static public String getName() { return NAME; }
/** Returns the library version such as "2.0.0" */
static public String getVersion() { return VERSION; }
/** Returns a longer library version that includes the timestamp such as "2.0.0 (Build @ 20120216-1720)" */
static public String getLongVersion() { return LONG_VERSION; }
}
| src/main/java/com/cloudhopper/commons/xbean/Version.java | /** DO NOT EDIT THIS FILE. IT IS AUTO GENERATED BY MAVEN */
package com.cloudhopper.commons.xbean;
public final class Version {
private static final String TIMESTAMP="20120216-1600";
private static final String VERSION="2.0.0";
private static final String NAME="ch-commons-xbean";
private static final String VENDOR="cloudhopper";
private static final String LONG_VERSION="2.0.0 (Build @ 20120216-1600)";
/** Returns the library vendor such as "cloudhopper" */
static public String getVendor() { return VENDOR; }
/** Returns the library build timestamp such as "20120216-1600" */
static public String getTimestamp() { return TIMESTAMP; }
/** Returns the library name such as "ch-commons-xbean" */
static public String getName() { return NAME; }
/** Returns the library version such as "2.0.0" */
static public String getVersion() { return VERSION; }
/** Returns a longer library version that includes the timestamp such as "2.0.0 (Build @ 20120216-1600)" */
static public String getLongVersion() { return LONG_VERSION; }
}
|
git-svn-id: https://svn.cloudhopper.lan/repos/dev/utility/java/ch-commons-xbean/trunk@4986 db02c596-f934-4852-9b2a-e10ddaadd22d
| src/main/java/com/cloudhopper/commons/xbean/Version.java | <ide><path>rc/main/java/com/cloudhopper/commons/xbean/Version.java
<ide> /** DO NOT EDIT THIS FILE. IT IS AUTO GENERATED BY MAVEN */
<ide> package com.cloudhopper.commons.xbean;
<ide> public final class Version {
<del> private static final String TIMESTAMP="20120216-1600";
<add> private static final String TIMESTAMP="20120216-1720";
<ide> private static final String VERSION="2.0.0";
<ide> private static final String NAME="ch-commons-xbean";
<ide> private static final String VENDOR="cloudhopper";
<del> private static final String LONG_VERSION="2.0.0 (Build @ 20120216-1600)";
<add> private static final String LONG_VERSION="2.0.0 (Build @ 20120216-1720)";
<ide> /** Returns the library vendor such as "cloudhopper" */
<ide> static public String getVendor() { return VENDOR; }
<del> /** Returns the library build timestamp such as "20120216-1600" */
<add> /** Returns the library build timestamp such as "20120216-1720" */
<ide> static public String getTimestamp() { return TIMESTAMP; }
<ide> /** Returns the library name such as "ch-commons-xbean" */
<ide> static public String getName() { return NAME; }
<ide> /** Returns the library version such as "2.0.0" */
<ide> static public String getVersion() { return VERSION; }
<del> /** Returns a longer library version that includes the timestamp such as "2.0.0 (Build @ 20120216-1600)" */
<add> /** Returns a longer library version that includes the timestamp such as "2.0.0 (Build @ 20120216-1720)" */
<ide> static public String getLongVersion() { return LONG_VERSION; }
<ide> } |
||
Java | mit | e0b22d4d1c6d0571d75cc760462df8c6c9ebf5a5 | 0 | EnigmaBridge/client.java,EnigmaBridge/client.java | package com.enigmabridge;
import com.enigmabridge.comm.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.annotations.*;
import java.util.List;
import static org.testng.Assert.*;
/**
* Simple test to obtain import public keys from the EB.
* Created by dusanklinec on 02.05.16.
*/
public class EBGetPubKeyCallIT {
private static final Logger LOG = LoggerFactory.getLogger(EBGetPubKeyCallIT.class);
public EBGetPubKeyCallIT() {
}
@BeforeClass
public static void setUpClass() throws Exception {
}
@AfterClass
public static void tearDownClass() throws Exception {
}
@BeforeMethod(alwaysRun = true, groups = {"integration"})
public void setUpMethod() throws Exception {
}
@AfterMethod(alwaysRun = true, groups = {"integration"}, enabled = false)
public void tearDownMethod() throws Exception {
}
@Test(groups = {"integration"}) //, timeOut = 100000
public void testCall() throws Exception {
LOG.trace("### UT ## EBGetPubKeyCallIT::testCall ## BEGIN ###");
try {
final EBEngine engine = new EBEngine();
final EBEndpointInfo endpoint = new EBEndpointInfo("https://site2.enigmabridge.com:11180");
final String apiKey = "TEST_API";
final EBConnectionSettings settings = new EBConnectionSettings()
.setMethod(EBCommUtils.METHOD_GET);
final EBGetPubKeyCall call = new EBGetPubKeyCall.Builder()
.setApiKey(apiKey)
.setEndpoint(endpoint)
.setEngine(engine)
.setSettings(settings)
.build();
final EBGetPubKeyResponse response = call.doRequest();
assertNotNull(response, "Response is null");
assertNotNull(response.getRawResponse(), "Raw response is null");
assertTrue(response.isCodeOk(), "Response code is not OK");
assertTrue(response.getRawResponse().isSuccessful(), "HTTP request was not successful");
final List<EBImportPubKey> keys = response.getImportKeys();
assertNotNull(keys, "Keys are null");
assertTrue(!keys.isEmpty(), "Key list is empty");
for(EBImportPubKey key : keys){
LOG.trace(key.toString());
}
} catch (Exception ex){
LOG.error("Exception in get import keys call", ex);
assertTrue(false);
}
LOG.trace("### UT ## EBGetPubKeyCallIT::testCall ## END ###");
}
}
| src/test/java/com/enigmabridge/EBGetPubKeyCallIT.java | package com.enigmabridge;
import com.enigmabridge.comm.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.annotations.*;
import java.util.List;
import static org.testng.Assert.*;
/**
* Simple test to obtain import public keys from the EB.
* Created by dusanklinec on 02.05.16.
*/
public class EBGetPubKeyCallIT {
private static final Logger LOG = LoggerFactory.getLogger(EBGetPubKeyCallIT.class);
public EBGetPubKeyCallIT() {
}
@BeforeClass
public static void setUpClass() throws Exception {
}
@AfterClass
public static void tearDownClass() throws Exception {
}
@BeforeMethod(alwaysRun = true, groups = {"integration"})
public void setUpMethod() throws Exception {
}
@AfterMethod(alwaysRun = true, groups = {"integration"}, enabled = false)
public void tearDownMethod() throws Exception {
}
@Test(groups = {"integration"}) //, timeOut = 100000
public void testCall() throws Exception {
LOG.trace("### UT ## EBGetPubKeyCallIT::testCall ## BEGIN ###");
try {
final EBEngine engine = new EBEngine();
final EBEndpointInfo endpoint = new EBEndpointInfo("https://site2.enigmabridge.com:11180");
final String apiKey = "TEST_API";
final EBAdditionalTrust trust = new EBAdditionalTrust(true, true, null);
final EBConnectionSettings settings = new EBConnectionSettings()
.setMethod(EBCommUtils.METHOD_GET)
.setTrust(trust);
final EBGetPubKeyCall call = new EBGetPubKeyCall.Builder()
.setApiKey(apiKey)
.setEndpoint(endpoint)
.setEngine(engine)
.setSettings(settings)
.build();
final EBGetPubKeyResponse response = call.doRequest();
assertNotNull(response, "Response is null");
assertNotNull(response.getRawResponse(), "Raw response is null");
assertTrue(response.isCodeOk(), "Response code is not OK");
assertTrue(response.getRawResponse().isSuccessful(), "HTTP request was not successful");
final List<EBImportPubKey> keys = response.getImportKeys();
assertNotNull(keys, "Keys are null");
assertTrue(!keys.isEmpty(), "Key list is empty");
for(EBImportPubKey key : keys){
LOG.trace(key.toString());
}
} catch (Exception ex){
LOG.error("Exception in get import keys call", ex);
assertTrue(false);
}
LOG.trace("### UT ## EBGetPubKeyCallIT::testCall ## END ###");
}
}
| get import key IT uses default trust object
| src/test/java/com/enigmabridge/EBGetPubKeyCallIT.java | get import key IT uses default trust object | <ide><path>rc/test/java/com/enigmabridge/EBGetPubKeyCallIT.java
<ide> final EBEndpointInfo endpoint = new EBEndpointInfo("https://site2.enigmabridge.com:11180");
<ide> final String apiKey = "TEST_API";
<ide>
<del> final EBAdditionalTrust trust = new EBAdditionalTrust(true, true, null);
<ide> final EBConnectionSettings settings = new EBConnectionSettings()
<del> .setMethod(EBCommUtils.METHOD_GET)
<del> .setTrust(trust);
<add> .setMethod(EBCommUtils.METHOD_GET);
<ide>
<ide> final EBGetPubKeyCall call = new EBGetPubKeyCall.Builder()
<ide> .setApiKey(apiKey) |
|
Java | apache-2.0 | 32593513c9197a5de225d6bf7d6f7185f4feea4b | 0 | ChadKillingsworth/closure-compiler,nawawi/closure-compiler,monetate/closure-compiler,ChadKillingsworth/closure-compiler,Yannic/closure-compiler,ChadKillingsworth/closure-compiler,shantanusharma/closure-compiler,shantanusharma/closure-compiler,shantanusharma/closure-compiler,monetate/closure-compiler,tiobe/closure-compiler,google/closure-compiler,monetate/closure-compiler,google/closure-compiler,vobruba-martin/closure-compiler,tiobe/closure-compiler,google/closure-compiler,tiobe/closure-compiler,Yannic/closure-compiler,Yannic/closure-compiler,shantanusharma/closure-compiler,vobruba-martin/closure-compiler,nawawi/closure-compiler,Yannic/closure-compiler,monetate/closure-compiler,tiobe/closure-compiler,nawawi/closure-compiler,ChadKillingsworth/closure-compiler,vobruba-martin/closure-compiler,nawawi/closure-compiler,google/closure-compiler,vobruba-martin/closure-compiler | /*
* Copyright 2008 The Closure Compiler 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.javascript.jscomp;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static com.google.javascript.rhino.jstype.JSTypeNative.ARRAY_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.BOOLEAN_OBJECT_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.BOOLEAN_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.CHECKED_UNKNOWN_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.ITERABLE_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.I_TEMPLATE_ARRAY_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.NULL_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.NUMBER_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.NUMBER_VALUE_OR_OBJECT_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.STRING_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.UNKNOWN_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.VOID_TYPE;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.javascript.jscomp.CodingConvention.AssertionFunctionSpec;
import com.google.javascript.jscomp.ControlFlowGraph.Branch;
import com.google.javascript.jscomp.graph.DiGraph.DiGraphEdge;
import com.google.javascript.jscomp.type.FlowScope;
import com.google.javascript.jscomp.type.ReverseAbstractInterpreter;
import com.google.javascript.rhino.JSDocInfo;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.Token;
import com.google.javascript.rhino.jstype.BooleanLiteralSet;
import com.google.javascript.rhino.jstype.FunctionBuilder;
import com.google.javascript.rhino.jstype.FunctionType;
import com.google.javascript.rhino.jstype.JSType;
import com.google.javascript.rhino.jstype.JSTypeNative;
import com.google.javascript.rhino.jstype.JSTypeRegistry;
import com.google.javascript.rhino.jstype.ModificationVisitor;
import com.google.javascript.rhino.jstype.ObjectType;
import com.google.javascript.rhino.jstype.StaticTypedSlot;
import com.google.javascript.rhino.jstype.TemplateType;
import com.google.javascript.rhino.jstype.TemplateTypeMap;
import com.google.javascript.rhino.jstype.TemplateTypeMapReplacer;
import com.google.javascript.rhino.jstype.TemplatizedType;
import com.google.javascript.rhino.jstype.UnionType;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.annotation.CheckReturnValue;
import javax.annotation.Nullable;
/**
* Type inference within a script node or a function body, using the data-flow
* analysis framework.
*
*/
class TypeInference
extends DataFlowAnalysis.BranchedForwardDataFlowAnalysis<Node, FlowScope> {
// TODO(johnlenz): We no longer make this check, but we should.
static final DiagnosticType FUNCTION_LITERAL_UNDEFINED_THIS =
DiagnosticType.warning(
"JSC_FUNCTION_LITERAL_UNDEFINED_THIS",
"Function literal argument refers to undefined this argument");
private final AbstractCompiler compiler;
private final JSTypeRegistry registry;
private final ReverseAbstractInterpreter reverseInterpreter;
private final FlowScope functionScope;
private final FlowScope bottomScope;
private final TypedScope containerScope;
private final TypedScopeCreator scopeCreator;
private final Map<String, AssertionFunctionSpec> assertionFunctionsMap;
// Scopes that have had their unbound untyped vars inferred as undefined.
private final Set<TypedScope> inferredUnboundVars = new HashSet<>();
// For convenience
private final ObjectType unknownType;
TypeInference(AbstractCompiler compiler, ControlFlowGraph<Node> cfg,
ReverseAbstractInterpreter reverseInterpreter,
TypedScope syntacticScope, TypedScopeCreator scopeCreator,
Map<String, AssertionFunctionSpec> assertionFunctionsMap) {
super(cfg, new LinkedFlowScope.FlowScopeJoinOp());
this.compiler = compiler;
this.registry = compiler.getTypeRegistry();
this.reverseInterpreter = reverseInterpreter;
this.unknownType = registry.getNativeObjectType(UNKNOWN_TYPE);
this.containerScope = syntacticScope;
this.scopeCreator = scopeCreator;
this.assertionFunctionsMap = assertionFunctionsMap;
FlowScope entryScope =
inferDeclarativelyUnboundVarsWithoutTypes(
LinkedFlowScope.createEntryLattice(syntacticScope));
this.functionScope = inferParameters(syntacticScope, entryScope);
this.bottomScope =
LinkedFlowScope.createEntryLattice(
TypedScope.createLatticeBottom(syntacticScope.getRootNode()));
}
@CheckReturnValue
private FlowScope inferDeclarativelyUnboundVarsWithoutTypes(FlowScope flow) {
TypedScope scope = (TypedScope) flow.getDeclarationScope();
if (!inferredUnboundVars.add(scope)) {
return flow;
}
// For each local variable declared with the VAR keyword, the entry
// type is VOID.
for (TypedVar var : scope.getDeclarativelyUnboundVarsWithoutTypes()) {
if (isUnflowable(var)) {
continue;
}
flow = flow.inferSlotType(var.getName(), getNativeType(VOID_TYPE));
}
return flow;
}
/** Infers all of a function's parameters if their types aren't declared. */
@SuppressWarnings("ReferenceEquality") // unknownType is a singleton
private FlowScope inferParameters(TypedScope functionScope, FlowScope entryFlowScope) {
Node functionNode = functionScope.getRootNode();
Node astParameters = functionNode.getSecondChild();
Node iifeArgumentNode = null;
if (NodeUtil.isInvocationTarget(functionNode)) {
iifeArgumentNode = functionNode.getNext();
}
FunctionType functionType =
JSType.toMaybeFunctionType(functionNode.getJSType());
if (functionType != null) {
Node parameterTypes = functionType.getParametersNode();
if (parameterTypes != null) {
Node parameterTypeNode = parameterTypes.getFirstChild();
for (Node astParameter : astParameters.children()) {
boolean isRest = false;
Node defaultValue = null;
if (astParameter.isDefaultValue()) {
defaultValue = astParameter.getSecondChild();
astParameter = astParameter.getFirstChild();
}
if (astParameter.isRest()) {
// e.g. `function f(p1, ...restParamName) {}`
// set astParameter = restParamName
astParameter = astParameter.getOnlyChild();
isRest = true;
}
if (!astParameter.isName()) {
// TODO(lharker): support destructuring parameters
continue;
}
if (iifeArgumentNode != null && iifeArgumentNode.isSpread()) {
// block inference on all parameters that might possibly be set by a spread, e.g. `z` in
// (function f(x, y, z = 1))(...[1, 2], 'foo')
iifeArgumentNode = null;
}
TypedVar var = functionScope.getVar(astParameter.getString());
checkNotNull(var);
if (var.isTypeInferred() && (var.getType() == unknownType || isRest)) {
JSType newType = null;
if (iifeArgumentNode != null) {
newType = iifeArgumentNode.getJSType();
} else if (parameterTypeNode != null) {
newType = parameterTypeNode.getJSType();
}
if (newType != null) {
if (isRest) {
// convert 'number' into 'Array<number>' for rest parameters
newType =
registry.createTemplatizedType(
registry.getNativeObjectType(ARRAY_TYPE), newType);
}
var.setType(newType);
astParameter.setJSType(newType);
}
}
if (parameterTypeNode != null) {
parameterTypeNode = parameterTypeNode.getNext();
}
if (iifeArgumentNode != null) {
iifeArgumentNode = iifeArgumentNode.getNext();
}
// 1. do type inference within the default value expression
// 2. add a flow scope slot for the assignment to the parameter. (which will not matter
// for declared parameters, just inferred parameters.
if (defaultValue != null) {
traverse(defaultValue, entryFlowScope);
JSType newType =
registry.createUnionType(
getJSType(astParameter).restrictByNotUndefined(), getJSType(defaultValue));
entryFlowScope = updateScopeForAssignment(entryFlowScope, astParameter, newType);
}
}
}
}
return entryFlowScope;
}
@Override
FlowScope createInitialEstimateLattice() {
return bottomScope;
}
@Override
FlowScope createEntryLattice() {
return functionScope;
}
@Override
@CheckReturnValue
FlowScope flowThrough(Node n, FlowScope input) {
// If we have not walked a path from <entry> to <n>, then we don't
// want to infer anything about this scope.
if (input == bottomScope) {
return input;
}
Node root = NodeUtil.getEnclosingScopeRoot(n);
FlowScope output = input.withSyntacticScope(scopeCreator.createScope(root));
output = inferDeclarativelyUnboundVarsWithoutTypes(output);
output = traverse(n, output);
return output;
}
@Override
@SuppressWarnings({"fallthrough", "incomplete-switch"})
List<FlowScope> branchedFlowThrough(Node source, FlowScope input) {
// NOTE(nicksantos): Right now, we just treat ON_EX edges like UNCOND
// edges. If we wanted to be perfect, we'd actually JOIN all the out
// lattices of this flow with the in lattice, and then make that the out
// lattice for the ON_EX edge. But it's probably too expensive to be
// worthwhile.
FlowScope output = flowThrough(source, input);
Node condition = null;
FlowScope conditionFlowScope = null;
BooleanOutcomePair conditionOutcomes = null;
List<DiGraphEdge<Node, Branch>> branchEdges = getCfg().getOutEdges(source);
List<FlowScope> result = new ArrayList<>(branchEdges.size());
for (DiGraphEdge<Node, Branch> branchEdge : branchEdges) {
Branch branch = branchEdge.getValue();
FlowScope newScope = output;
switch (branch) {
case ON_TRUE:
if (source.isForIn() || source.isForOf()) {
Node item = source.getFirstChild();
Node obj = item.getNext();
FlowScope informed = traverse(obj, output);
if (NodeUtil.isNameDeclaration(item)) {
item = item.getFirstChild();
}
if (item.isDestructuringLhs()) {
item = item.getFirstChild();
}
if (source.isForIn()) {
// item is assigned a property name, so its type should be string.
if (item.isName()) {
JSType iterKeyType = getNativeType(STRING_TYPE);
JSType objType = getJSType(obj).autobox();
JSType objIndexType =
objType
.getTemplateTypeMap()
.getResolvedTemplateType(registry.getObjectIndexKey());
if (objIndexType != null && !objIndexType.isUnknownType()) {
JSType narrowedKeyType = iterKeyType.getGreatestSubtype(objIndexType);
if (!narrowedKeyType.isEmptyType()) {
iterKeyType = narrowedKeyType;
}
}
informed = redeclareSimpleVar(informed, item, iterKeyType);
}
} else {
// for/of. The type of `item` is the type parameter of the Iterable type.
JSType objType = getJSType(obj).autobox();
// NOTE: this returns the UNKNOWN_TYPE if objType does not implement Iterable
JSType newType = objType.getInstantiatedTypeArgument(getNativeType(ITERABLE_TYPE));
// Note that `item` can be an arbitrary LHS expression we need to check.
if (item.isDestructuringPattern()) {
// for (const {x, y} of data) {
informed = traverseDestructuringPattern(item, informed, newType);
} else {
informed = traverse(item, informed);
informed = updateScopeForAssignment(informed, item, newType);
}
}
newScope = informed;
break;
}
// FALL THROUGH
case ON_FALSE:
if (condition == null) {
condition = NodeUtil.getConditionExpression(source);
if (condition == null && source.isCase()) {
condition = source;
// conditionFlowScope is cached from previous iterations
// of the loop.
if (conditionFlowScope == null) {
conditionFlowScope = traverse(condition.getFirstChild(), output);
}
}
}
if (condition != null) {
if (condition.isAnd() || condition.isOr()) {
// When handling the short-circuiting binary operators,
// the outcome scope on true can be different than the outcome
// scope on false.
//
// TODO(nicksantos): The "right" way to do this is to
// carry the known outcome all the way through the
// recursive traversal, so that we can construct a
// different flow scope based on the outcome. However,
// this would require a bunch of code and a bunch of
// extra computation for an edge case. This seems to be
// a "good enough" approximation.
// conditionOutcomes is cached from previous iterations
// of the loop.
if (conditionOutcomes == null) {
conditionOutcomes =
condition.isAnd()
? traverseAnd(condition, output)
: traverseOr(condition, output);
}
newScope =
reverseInterpreter.getPreciserScopeKnowingConditionOutcome(
condition,
conditionOutcomes.getOutcomeFlowScope(
condition.getToken(), branch == Branch.ON_TRUE),
branch == Branch.ON_TRUE);
} else {
// conditionFlowScope is cached from previous iterations
// of the loop.
if (conditionFlowScope == null) {
conditionFlowScope = traverse(condition, output);
}
newScope =
reverseInterpreter.getPreciserScopeKnowingConditionOutcome(
condition, conditionFlowScope, branch == Branch.ON_TRUE);
}
}
break;
default:
break;
}
result.add(newScope);
}
return result;
}
private FlowScope traverse(Node n, FlowScope scope) {
switch (n.getToken()) {
case ASSIGN:
scope = traverseAssign(n, scope);
break;
case NAME:
scope = traverseName(n, scope);
break;
case GETPROP:
scope = traverseGetProp(n, scope);
break;
case CLASS:
scope = traverseClass(n, scope);
break;
case AND:
scope = traverseAnd(n, scope).getJoinedFlowScope();
break;
case OR:
scope = traverseOr(n, scope).getJoinedFlowScope();
break;
case HOOK:
scope = traverseHook(n, scope);
break;
case OBJECTLIT:
scope = traverseObjectLiteral(n, scope);
break;
case CALL:
scope = traverseFunctionInvocation(n, scope);
scope = tightenTypesAfterAssertions(scope, n);
break;
case NEW:
scope = traverseNew(n, scope);
break;
case NEW_TARGET:
traverseNewTarget(n);
break;
case ASSIGN_ADD:
case ADD:
scope = traverseAdd(n, scope);
break;
case POS:
case NEG:
scope = traverse(n.getFirstChild(), scope); // Find types.
n.setJSType(getNativeType(NUMBER_TYPE));
break;
case ARRAYLIT:
scope = traverseArrayLiteral(n, scope);
break;
case THIS:
n.setJSType(scope.getTypeOfThis());
break;
case ASSIGN_LSH:
case ASSIGN_RSH:
case ASSIGN_URSH:
case ASSIGN_DIV:
case ASSIGN_MOD:
case ASSIGN_BITAND:
case ASSIGN_BITXOR:
case ASSIGN_BITOR:
case ASSIGN_MUL:
case ASSIGN_SUB:
case ASSIGN_EXPONENT:
scope = traverseAssignOp(n, scope, getNativeType(NUMBER_TYPE));
break;
case LSH:
case RSH:
case URSH:
case DIV:
case MOD:
case BITAND:
case BITXOR:
case BITOR:
case MUL:
case SUB:
case DEC:
case INC:
case BITNOT:
case EXPONENT:
scope = traverseChildren(n, scope);
n.setJSType(getNativeType(NUMBER_TYPE));
break;
case COMMA:
scope = traverseChildren(n, scope);
n.setJSType(getJSType(n.getLastChild()));
break;
case TEMPLATELIT:
case TYPEOF:
scope = traverseChildren(n, scope);
n.setJSType(getNativeType(STRING_TYPE));
break;
case TEMPLATELIT_SUB:
// TEMPLATELIT_SUBs are untyped but we do need to traverse their children.
scope = traverseChildren(n, scope);
break;
case TAGGED_TEMPLATELIT:
scope = traverseFunctionInvocation(n, scope);
break;
case DELPROP:
case LT:
case LE:
case GT:
case GE:
case NOT:
case EQ:
case NE:
case SHEQ:
case SHNE:
case INSTANCEOF:
case IN:
scope = traverseChildren(n, scope);
n.setJSType(getNativeType(BOOLEAN_TYPE));
break;
case GETELEM:
scope = traverseGetElem(n, scope);
break;
case EXPR_RESULT:
scope = traverseChildren(n, scope);
if (n.getFirstChild().isGetProp()) {
Node getprop = n.getFirstChild();
ObjectType ownerType = ObjectType.cast(
getJSType(getprop.getFirstChild()).restrictByNotNullOrUndefined());
if (ownerType != null) {
ensurePropertyDeclaredHelper(getprop, ownerType, scope);
}
}
break;
case SWITCH:
scope = traverse(n.getFirstChild(), scope);
break;
case RETURN:
scope = traverseReturn(n, scope);
break;
case YIELD:
scope = traverseChildren(n, scope);
n.setJSType(getNativeType(UNKNOWN_TYPE));
break;
case VAR:
case LET:
case CONST:
scope = traverseDeclaration(n, scope);
break;
case THROW:
scope = traverseChildren(n, scope);
break;
case CATCH:
scope = traverseCatch(n, scope);
break;
case CAST:
scope = traverseChildren(n, scope);
JSDocInfo info = n.getJSDocInfo();
if (info != null && info.hasType()) {
n.setJSType(info.getType().evaluate(scope.getDeclarationScope(), registry));
}
break;
case SUPER:
traverseSuper(n);
break;
case SPREAD:
// The spread itself has no type, but the expression it contains does and may affect
// type inference.
scope = traverseChildren(n, scope);
break;
case AWAIT:
scope = traverseAwait(n, scope);
break;
case VOID:
n.setJSType(getNativeType(VOID_TYPE));
scope = traverseChildren(n, scope);
break;
case ROOT:
case SCRIPT:
case FUNCTION:
case PARAM_LIST:
case BLOCK:
case EMPTY:
case IF:
case WHILE:
case DO:
case FOR:
case FOR_IN:
case FOR_OF:
case FOR_AWAIT_OF:
case BREAK:
case CONTINUE:
case TRY:
case CASE:
case DEFAULT_CASE:
case WITH:
case DEBUGGER:
// These don't need to be typed here, since they only affect control flow.
break;
case TRUE:
case FALSE:
case STRING:
case NUMBER:
case NULL:
case REGEXP:
// Primitives are typed in TypedScopeCreator.AbstractScopeBuilder#attachLiteralTypes
break;
default:
throw new IllegalStateException(
"Type inference doesn't know to handle token " + n.getToken());
}
return scope;
}
private void traverseSuper(Node superNode) {
// Find the closest non-arrow function (TODO(sdh): this could be an AbstractScope method).
TypedScope scope = containerScope;
while (scope != null && !NodeUtil.isVanillaFunction(scope.getRootNode())) {
scope = scope.getParent();
}
if (scope == null) {
superNode.setJSType(unknownType);
return;
}
Node root = scope.getRootNode();
JSType jsType = root.getJSType();
FunctionType functionType = jsType != null ? jsType.toMaybeFunctionType() : null;
ObjectType superNodeType = unknownType;
Node context = superNode.getParent();
// NOTE: we currently transpile subclass constructors to use "super.apply", which is not
// actually valid ES6. For now, provide a special case to support this, but it should be
// removed once class transpilation is after type checking.
if (context.isCall()) {
// Call the superclass constructor.
if (functionType != null && functionType.isConstructor()) {
FunctionType superCtor = functionType.getSuperClassConstructor();
if (superCtor != null) {
superNodeType = superCtor;
}
}
} else if (context.isGetProp() || context.isGetElem()) {
// TODO(sdh): once getTypeOfThis supports statics, we can get rid of this branch, as well as
// the vanilla function search at the top and just return functionScope.getVar("super").
if (root.getParent().isStaticMember()) {
// Since the root is a static member, we're guaranteed that the parent scope is a class.
Node classNode = scope.getParent().getRootNode();
checkState(classNode.isClass());
FunctionType thisCtor = JSType.toMaybeFunctionType(classNode.getJSType());
if (thisCtor != null) {
FunctionType superCtor = thisCtor.getSuperClassConstructor();
if (superCtor != null) {
superNodeType = superCtor;
}
}
} else if (functionType != null) {
// Refer to a superclass instance property.
ObjectType thisInstance = ObjectType.cast(functionType.getTypeOfThis());
if (thisInstance != null) {
FunctionType superCtor = thisInstance.getSuperClassConstructor();
if (superCtor != null) {
ObjectType superInstance = superCtor.getInstanceType();
if (superInstance != null) {
superNodeType = superInstance;
}
}
}
}
}
superNode.setJSType(superNodeType);
}
private void traverseNewTarget(Node newTargetNode) {
// new.target is (undefined|!Function) within a vanilla function and !Function within an ES6
// constructor.
// Find the closest non-arrow function (TODO(sdh): this could be an AbstractScope method).
TypedScope scope = containerScope;
while (scope != null && !NodeUtil.isVanillaFunction(scope.getRootNode())) {
scope = scope.getParent();
}
if (scope == null) {
// NOTE: we already have a parse error for new.target outside a function. The only other case
// where this might happen is a top-level arrow function, which is a parse error in the VM,
// but allowed by our parser.
newTargetNode.setJSType(unknownType);
return;
}
Node root = scope.getRootNode();
Node parent = root.getParent();
if (parent.isMemberFunctionDef() && parent.getGrandparent().isClass()) {
// In an ES6 constuctor, new.target may not be undefined. In any other method, it must be
// undefined, since methods are not constructable.
JSTypeNative type =
"constructor".equals(parent.getString()) ? JSTypeNative.U2U_CONSTRUCTOR_TYPE : VOID_TYPE;
newTargetNode.setJSType(registry.getNativeType(type));
} else {
// Other functions also include undefined, in case they are not called with 'new'.
newTargetNode.setJSType(
registry.createUnionType(
registry.getNativeType(JSTypeNative.U2U_CONSTRUCTOR_TYPE),
registry.getNativeType(VOID_TYPE)));
}
}
/** Traverse a return value. */
@CheckReturnValue
private FlowScope traverseReturn(Node n, FlowScope scope) {
scope = traverseChildren(n, scope);
Node retValue = n.getFirstChild();
if (retValue != null) {
JSType type = functionScope.getRootNode().getJSType();
if (type != null) {
FunctionType fnType = type.toMaybeFunctionType();
if (fnType != null) {
inferPropertyTypesToMatchConstraint(
retValue.getJSType(), fnType.getReturnType());
}
}
}
return scope;
}
/**
* Any value can be thrown, so it's really impossible to determine the type of a CATCH param.
* Treat it as the UNKNOWN type.
*/
@CheckReturnValue
private FlowScope traverseCatch(Node catchNode, FlowScope scope) {
Node name = catchNode.getFirstChild();
JSType type;
// If the catch expression name was declared in the catch use that type,
// otherwise use "unknown".
JSDocInfo info = name.getJSDocInfo();
if (info != null && info.hasType()) {
type = info.getType().evaluate(scope.getDeclarationScope(), registry);
} else {
type = getNativeType(JSTypeNative.UNKNOWN_TYPE);
}
name.setJSType(type);
return redeclareSimpleVar(scope, name, type);
}
@CheckReturnValue
private FlowScope traverseAssign(Node n, FlowScope scope) {
Node target = n.getFirstChild();
Node value = n.getLastChild();
if (target.isDestructuringPattern()) {
scope = traverse(value, scope);
JSType valueType = getJSType(value);
n.setJSType(valueType);
return traverseDestructuringPattern(target, scope, valueType);
} else {
scope = traverseChildren(n, scope);
JSType valueType = getJSType(value);
n.setJSType(valueType);
return updateScopeForAssignment(scope, target, valueType);
}
}
@CheckReturnValue
private FlowScope traverseAssignOp(Node n, FlowScope scope, JSType resultType) {
Node left = n.getFirstChild();
scope = traverseChildren(n, scope);
n.setJSType(resultType);
// The lhs is both an input and an output, so don't update the input type here.
return updateScopeForAssignment(scope, left, resultType, null);
}
private static boolean isInExternFile(Node n) {
return NodeUtil.getSourceFile(n).isExtern();
}
private static boolean isPossibleMixinApplication(Node lvalue, Node rvalue) {
if (isInExternFile(lvalue)) {
return true;
}
JSDocInfo jsdoc = NodeUtil.getBestJSDocInfo(lvalue);
return jsdoc != null
&& jsdoc.isConstructor()
&& jsdoc.getImplementedInterfaceCount() > 0
&& lvalue.isQualifiedName()
&& rvalue.isCall();
}
/**
* @param constructor A constructor function defined by a call, which may be a mixin application.
* The constructor implements at least one interface. If the constructor is missing some
* properties of the inherited interfaces, this method declares these properties.
*/
private static void addMissingInterfaceProperties(JSType constructor) {
if (constructor != null && constructor.isConstructor()) {
FunctionType f = constructor.toMaybeFunctionType();
ObjectType proto = f.getPrototype();
for (ObjectType interf : f.getImplementedInterfaces()) {
for (String pname : interf.getPropertyNames()) {
if (!proto.hasProperty(pname)) {
proto.defineDeclaredProperty(pname, interf.getPropertyType(pname), null);
}
}
}
}
}
/**
* Calls {@link #updateScopeForAssignment(FlowScope, Node, JSType, Node)} and updates the given
* `target` node with the given `resultType` if it's a name or getprop.
*/
@CheckReturnValue
private FlowScope updateScopeForAssignment(FlowScope scope, Node target, JSType resultType) {
return updateScopeForAssignment(scope, target, resultType, target);
}
/**
* Updates the scope according to the result of an assignment.
*
* @param target the node being assigned to, e.g. `a.b` in `a.b = 3;`
* @param resultType the type being assigned to `target`, e.g. `number` in `a.b = 3;`
* @param updateNode a node to update with the `resultType`. must be either `target` or null.
*/
@CheckReturnValue
private FlowScope updateScopeForAssignment(
FlowScope scope, Node target, JSType resultType, @Nullable Node updateNode) {
checkNotNull(resultType);
checkState(updateNode == null || updateNode == target);
JSType targetType = target.getJSType();
Node right = NodeUtil.getRValueOfLValue(target);
if (isPossibleMixinApplication(target, right)) {
addMissingInterfaceProperties(targetType);
}
switch (target.getToken()) {
case NAME:
String varName = target.getString();
TypedVar var = getDeclaredVar(scope, varName);
JSType varType = var == null ? null : var.getType();
boolean isVarDeclaration =
// TODO(b/77597706): this won't work for destructuring declarations
target.hasChildren()
&& varType != null
&& !var.isTypeInferred()
&& var.getNameNode() != null;
boolean isTypelessConstDecl =
isVarDeclaration
&& NodeUtil.isConstantDeclaration(
compiler.getCodingConvention(), var.getJSDocInfo(), var.getNameNode())
&& !(var.getJSDocInfo() != null && var.getJSDocInfo().hasType());
// When looking at VAR initializers for declared VARs, we tend
// to use the declared type over the type it's being
// initialized to in the global scope.
//
// For example,
// /** @param {number} */ var f = goog.abstractMethod;
// it's obvious that the programmer wants you to use
// the declared function signature, not the inferred signature.
//
// Or,
// /** @type {Object.<string>} */ var x = {};
// the one-time anonymous object on the right side
// is as narrow as it can possibly be, but we need to make
// sure we back-infer the <string> element constraint on
// the left hand side, so we use the left hand side.
boolean isVarTypeBetter = isVarDeclaration
// Makes it easier to check for NPEs.
&& !resultType.isNullType() && !resultType.isVoidType()
// Do not use the var type if the declaration looked like
// /** @const */ var x = 3;
// because this type was computed from the RHS
&& !isTypelessConstDecl;
// TODO(nicksantos): This might be a better check once we have
// back-inference of object/array constraints. It will probably
// introduce more type warnings. It uses the result type iff it's
// strictly narrower than the declared var type.
//
//boolean isVarTypeBetter = isVarDeclaration &&
// (varType.restrictByNotNullOrUndefined().isSubtype(resultType)
// || !resultType.isSubtype(varType));
if (isVarTypeBetter) {
scope = redeclareSimpleVar(scope, target, varType);
} else {
scope = redeclareSimpleVar(scope, target, resultType);
}
if (updateNode != null) {
updateNode.setJSType(resultType);
}
if (var != null
&& var.isTypeInferred()
// Don't change the typed scope to include "undefined" upon seeing "let foo;", because
// this is incompatible with how we currently handle VARs and breaks existing code.
// TODO(sdh): remove this condition after cleaning up code depending on it.
&& !(target.getParent().isLet() && !target.hasChildren())) {
JSType oldType = var.getType();
var.setType(oldType == null ? resultType : oldType.getLeastSupertype(resultType));
} else if (isTypelessConstDecl) {
// /** @const */ var x = y;
// should be redeclared, so that the type of y
// gets propagated to inner scopes.
var.setType(resultType);
}
break;
case GETPROP:
if (target.isQualifiedName()) {
String qualifiedName = target.getQualifiedName();
boolean declaredSlotType = false;
JSType rawObjType = target.getFirstChild().getJSType();
if (rawObjType != null) {
ObjectType objType = ObjectType.cast(
rawObjType.restrictByNotNullOrUndefined());
if (objType != null) {
String propName = target.getLastChild().getString();
declaredSlotType = objType.isPropertyTypeDeclared(propName);
}
}
JSType safeLeftType = targetType == null ? unknownType : targetType;
scope =
scope.inferQualifiedSlot(
target, qualifiedName, safeLeftType, resultType, declaredSlotType);
}
if (updateNode != null) {
updateNode.setJSType(resultType);
}
ensurePropertyDefined(target, resultType, scope);
break;
default:
break;
}
return scope;
}
/** Defines a property if the property has not been defined yet. */
private void ensurePropertyDefined(Node getprop, JSType rightType, FlowScope scope) {
String propName = getprop.getLastChild().getString();
Node obj = getprop.getFirstChild();
JSType nodeType = getJSType(obj);
ObjectType objectType = ObjectType.cast(
nodeType.restrictByNotNullOrUndefined());
boolean propCreationInConstructor =
obj.isThis() && getJSType(containerScope.getRootNode()).isConstructor();
if (objectType == null) {
registry.registerPropertyOnType(propName, nodeType);
} else {
if (nodeType.isStruct() && !objectType.hasProperty(propName)) {
// In general, we don't want to define a property on a struct object,
// b/c TypeCheck will later check for improper property creation on
// structs. There are two exceptions.
// 1) If it's a property created inside the constructor, on the newly
// created instance, allow it.
// 2) If it's a prototype property, allow it. For example:
// Foo.prototype.bar = baz;
// where Foo.prototype is a struct and the assignment happens at the
// top level and the constructor Foo is defined in the same file.
boolean staticPropCreation = false;
Node maybeAssignStm = getprop.getGrandparent();
if (containerScope.isGlobal() && NodeUtil.isPrototypePropertyDeclaration(maybeAssignStm)) {
String propCreationFilename = maybeAssignStm.getSourceFileName();
Node ctor = objectType.getOwnerFunction().getSource();
if (ctor != null && ctor.getSourceFileName().equals(propCreationFilename)) {
staticPropCreation = true;
}
}
if (!propCreationInConstructor && !staticPropCreation) {
return; // Early return to avoid creating the property below.
}
}
if (ensurePropertyDeclaredHelper(getprop, objectType, scope)) {
return;
}
if (!objectType.isPropertyTypeDeclared(propName)) {
// We do not want a "stray" assign to define an inferred property
// for every object of this type in the program. So we use a heuristic
// approach to determine whether to infer the property.
//
// 1) If the property is already defined, join it with the previously
// inferred type.
// 2) If this isn't an instance object, define it.
// 3) If the property of an object is being assigned in the constructor,
// define it.
// 4) If this is a stub, define it.
// 5) Otherwise, do not define the type, but declare it in the registry
// so that we can use it for missing property checks.
if (objectType.hasProperty(propName) || !objectType.isInstanceType()) {
if ("prototype".equals(propName)) {
objectType.defineDeclaredProperty(propName, rightType, getprop);
} else {
objectType.defineInferredProperty(propName, rightType, getprop);
}
} else if (propCreationInConstructor) {
objectType.defineInferredProperty(propName, rightType, getprop);
} else {
registry.registerPropertyOnType(propName, objectType);
}
}
}
}
/**
* Declares a property on its owner, if necessary.
*
* @return True if a property was declared.
*/
private boolean ensurePropertyDeclaredHelper(
Node getprop, ObjectType objectType, FlowScope scope) {
if (getprop.isQualifiedName()) {
String propName = getprop.getLastChild().getString();
String qName = getprop.getQualifiedName();
TypedVar var = getDeclaredVar(scope, qName);
if (var != null && !var.isTypeInferred()) {
// Handle normal declarations that could not be addressed earlier.
if (propName.equals("prototype")
||
// Handle prototype declarations that could not be addressed earlier.
(!objectType.hasOwnProperty(propName)
&& (!objectType.isInstanceType()
|| (var.isExtern() && !objectType.isNativeObjectType())))) {
return objectType.defineDeclaredProperty(
propName, var.getType(), getprop);
}
}
}
return false;
}
private FlowScope traverseDeclaration(Node n, FlowScope scope) {
for (Node declarationChild : n.children()) {
scope = traverseDeclarationChild(declarationChild, scope);
}
return scope;
}
private FlowScope traverseDeclarationChild(Node n, FlowScope scope) {
if (n.isName()) {
return traverseName(n, scope);
}
checkState(n.isDestructuringLhs(), n);
scope = traverse(n.getSecondChild(), scope);
return traverseDestructuringPattern(n.getFirstChild(), scope, getJSType(n.getSecondChild()));
}
/** Traverses a destructuring pattern in an assignment or declaration */
private FlowScope traverseDestructuringPattern(
Node pattern, FlowScope scope, JSType patternType) {
checkArgument(pattern.isDestructuringPattern(), pattern);
checkNotNull(patternType);
for (Node key : pattern.children()) {
DestructuredTarget target = DestructuredTarget.createTarget(registry, patternType, key);
// The computed property is always evaluated first.
if (target.hasComputedProperty()) {
scope = traverse(target.getComputedProperty().getFirstChild(), scope);
}
Node targetNode = target.getNode();
if (targetNode.isDestructuringPattern()) {
if (target.hasDefaultValue()) {
traverse(target.getDefaultValue(), scope);
}
// traverse into nested patterns
JSType targetType = target.inferType();
targetType = targetType != null ? targetType : getNativeType(UNKNOWN_TYPE);
scope = traverseDestructuringPattern(targetNode, scope, targetType);
} else {
scope = traverse(targetNode, scope);
if (target.hasDefaultValue()) {
// TODO(lharker): what do we do with the inferred slots in the scope?
// throw them away or join them with the previous scope?
traverse(target.getDefaultValue(), scope);
}
// declare in the scope
JSType targetType = target.inferType();
targetType = targetType != null ? targetType : getNativeType(UNKNOWN_TYPE);
scope = updateScopeForAssignment(scope, targetNode, targetType);
}
}
// put the `inferred type` of a pattern on it, to make it easier to do typechecking
pattern.setJSType(patternType);
return scope;
}
private FlowScope traverseName(Node n, FlowScope scope) {
String varName = n.getString();
Node value = n.getFirstChild();
JSType type = n.getJSType();
if (value != null) {
scope = traverse(value, scope);
return updateScopeForAssignment(scope, n, getJSType(value));
} else if (n.getParent().isLet()) {
// Whenever we see a LET, we're guaranteed it's not yet in the scope, and we don't need to
// worry about it being from an outer scope. In this case, it has no child, so the actual
// type should be undefined, but we make a special allowance for type-annotated variables.
// In that case, we use the annotated type instead.
// TODO(sdh): I would have thought that #updateScopeForTypeChange would handle using the
// declared type correctly, but for some reason it doesn't so we handle it here.
JSType resultType = type != null ? type : getNativeType(VOID_TYPE);
scope = updateScopeForAssignment(scope, n, resultType);
type = resultType;
} else {
StaticTypedSlot var = scope.getSlot(varName);
if (var != null) {
// There are two situations where we don't want to use type information
// from the scope, even if we have it.
// 1) The var is escaped and assigned in an inner scope, e.g.,
// function f() { var x = 3; function g() { x = null } (x); }
boolean isInferred = var.isTypeInferred();
boolean unflowable = isInferred && isUnflowable(getDeclaredVar(scope, varName));
// 2) We're reading type information from another scope for an
// inferred variable. That variable is assigned more than once,
// and we can't know which type we're getting.
//
// var t = null; function f() { (t); } doStuff(); t = {};
//
// Notice that this heuristic isn't perfect. For example, you might
// have:
//
// function f() { (t); } f(); var t = 3;
//
// In this case, we would infer the first reference to t as
// type {number}, even though it's undefined.
TypedVar maybeOuterVar =
isInferred && containerScope.isLocal()
? containerScope.getParent().getVar(varName)
: null;
boolean nonLocalInferredSlot =
var.equals(maybeOuterVar) && !maybeOuterVar.isMarkedAssignedExactlyOnce();
if (!unflowable && !nonLocalInferredSlot) {
type = var.getType();
if (type == null) {
type = unknownType;
}
}
}
}
n.setJSType(type);
return scope;
}
private FlowScope traverseClass(Node n, FlowScope scope) {
// The name already has a type applied (from TypedScopeCreator) if it's non-empty, and the
// members are traversed in the class scope (and in their own function scopes). But the extends
// clause and computed property keys are in the outer scope and must be traversed here.
scope = traverse(n.getSecondChild(), scope);
Node classMembers = NodeUtil.getClassMembers(n);
for (Node member = classMembers.getFirstChild(); member != null; member = member.getNext()) {
if (member.isComputedProp()) {
scope = traverse(member.getFirstChild(), scope);
}
}
return scope;
}
/** Traverse each element of the array. */
private FlowScope traverseArrayLiteral(Node n, FlowScope scope) {
scope = traverseChildren(n, scope);
n.setJSType(getNativeType(ARRAY_TYPE));
return scope;
}
private FlowScope traverseObjectLiteral(Node n, FlowScope scope) {
JSType type = n.getJSType();
checkNotNull(type);
for (Node name = n.getFirstChild(); name != null; name = name.getNext()) {
scope = traverseChildren(name, scope);
}
// Object literals can be reflected on other types.
// See CodingConvention#getObjectLiteralCast and goog.reflect.object
// Ignore these types of literals.
ObjectType objectType = ObjectType.cast(type);
if (objectType == null
|| n.getBooleanProp(Node.REFLECTED_OBJECT)
|| objectType.isEnumType()) {
return scope;
}
String qObjName = NodeUtil.getBestLValueName(
NodeUtil.getBestLValue(n));
for (Node name = n.getFirstChild(); name != null;
name = name.getNext()) {
if (name.isComputedProp()) {
// Don't define computed properties as inferred properties on the object
continue;
}
String memberName = NodeUtil.getObjectLitKeyName(name);
if (memberName != null) {
JSType rawValueType = name.getFirstChild().getJSType();
JSType valueType =
TypeCheck.getObjectLitKeyTypeFromValueType(name, rawValueType);
if (valueType == null) {
valueType = unknownType;
}
objectType.defineInferredProperty(memberName, valueType, name);
// Do normal flow inference if this is a direct property assignment.
if (qObjName != null && name.isStringKey()) {
String qKeyName = qObjName + "." + memberName;
TypedVar var = getDeclaredVar(scope, qKeyName);
JSType oldType = var == null ? null : var.getType();
if (var != null && var.isTypeInferred()) {
var.setType(oldType == null ? valueType : oldType.getLeastSupertype(oldType));
}
scope =
scope.inferQualifiedSlot(
name, qKeyName, oldType == null ? unknownType : oldType, valueType, false);
}
} else {
n.setJSType(unknownType);
}
}
return scope;
}
private FlowScope traverseAdd(Node n, FlowScope scope) {
Node left = n.getFirstChild();
Node right = left.getNext();
scope = traverseChildren(n, scope);
JSType leftType = left.getJSType();
JSType rightType = right.getJSType();
JSType type = unknownType;
if (leftType != null && rightType != null) {
boolean leftIsUnknown = leftType.isUnknownType();
boolean rightIsUnknown = rightType.isUnknownType();
if (leftIsUnknown && rightIsUnknown) {
type = unknownType;
} else if ((!leftIsUnknown && leftType.isString())
|| (!rightIsUnknown && rightType.isString())) {
type = getNativeType(STRING_TYPE);
} else if (leftIsUnknown || rightIsUnknown) {
type = unknownType;
} else if (isAddedAsNumber(leftType) && isAddedAsNumber(rightType)) {
type = getNativeType(NUMBER_TYPE);
} else {
type = registry.createUnionType(STRING_TYPE, NUMBER_TYPE);
}
}
n.setJSType(type);
if (n.isAssignAdd()) {
// TODO(johnlenz): this should not update the type of the lhs as that is use as a
// input and need to be preserved for type checking.
// Instead call this overload `updateScopeForAssignment(scope, left, type, null);`
scope = updateScopeForAssignment(scope, left, type);
}
return scope;
}
private boolean isAddedAsNumber(JSType type) {
return type.isSubtypeOf(registry.createUnionType(VOID_TYPE, NULL_TYPE,
NUMBER_VALUE_OR_OBJECT_TYPE, BOOLEAN_TYPE, BOOLEAN_OBJECT_TYPE));
}
private FlowScope traverseHook(Node n, FlowScope scope) {
Node condition = n.getFirstChild();
Node trueNode = condition.getNext();
Node falseNode = n.getLastChild();
// verify the condition
scope = traverse(condition, scope);
// reverse abstract interpret the condition to produce two new scopes
FlowScope trueScope = reverseInterpreter.
getPreciserScopeKnowingConditionOutcome(
condition, scope, true);
FlowScope falseScope = reverseInterpreter.
getPreciserScopeKnowingConditionOutcome(
condition, scope, false);
// traverse the true node with the trueScope
traverse(trueNode, trueScope);
// traverse the false node with the falseScope
traverse(falseNode, falseScope);
// meet true and false nodes' types and assign
JSType trueType = trueNode.getJSType();
JSType falseType = falseNode.getJSType();
if (trueType != null && falseType != null) {
n.setJSType(trueType.getLeastSupertype(falseType));
} else {
n.setJSType(null);
}
return scope;
}
/** @param n A non-constructor function invocation, i.e. CALL or TAGGED_TEMPLATELIT */
private FlowScope traverseFunctionInvocation(Node n, FlowScope scope) {
checkArgument(n.isCall() || n.isTaggedTemplateLit(), n);
scope = traverseChildren(n, scope);
Node left = n.getFirstChild();
JSType functionType = getJSType(left).restrictByNotNullOrUndefined();
if (left.isSuper()) {
// TODO(sdh): This will probably return the super type; might want to return 'this' instead?
return traverseInstantiation(n, functionType, scope);
} else if (functionType.isFunctionType()) {
FunctionType fnType = functionType.toMaybeFunctionType();
n.setJSType(fnType.getReturnType());
backwardsInferenceFromCallSite(n, fnType, scope);
} else if (functionType.isEquivalentTo(getNativeType(CHECKED_UNKNOWN_TYPE))) {
n.setJSType(getNativeType(CHECKED_UNKNOWN_TYPE));
} else if (left.getJSType() != null && left.getJSType().isUnknownType()) {
// TODO(lharker): do we also want to set this to unknown if the left's type is null? We would
// lose some inference that TypeCheck does when given a null type.
n.setJSType(getNativeType(UNKNOWN_TYPE));
}
return scope;
}
private FlowScope tightenTypesAfterAssertions(FlowScope scope, Node callNode) {
Node left = callNode.getFirstChild();
Node firstParam = left.getNext();
AssertionFunctionSpec assertionFunctionSpec =
assertionFunctionsMap.get(left.getQualifiedName());
if (assertionFunctionSpec == null || firstParam == null) {
return scope;
}
Node assertedNode = assertionFunctionSpec.getAssertedParam(firstParam);
if (assertedNode == null) {
return scope;
}
JSType assertedType = assertionFunctionSpec.getAssertedOldType(
callNode, registry);
String assertedNodeName = assertedNode.getQualifiedName();
JSType narrowed;
// Handle assertions that enforce expressions evaluate to true.
if (assertedType == null) {
// Handle arbitrary expressions within the assert.
scope = reverseInterpreter.getPreciserScopeKnowingConditionOutcome(
assertedNode, scope, true);
// Build the result of the assertExpression
narrowed = getJSType(assertedNode).restrictByNotNullOrUndefined();
} else {
// Handle assertions that enforce expressions are of a certain type.
JSType type = getJSType(assertedNode);
if (assertedType.isUnknownType() || type.isUnknownType()) {
narrowed = assertedType;
} else {
narrowed = type.getGreatestSubtype(assertedType);
}
if (assertedNodeName != null && type.differsFrom(narrowed)) {
scope = narrowScope(scope, assertedNode, narrowed);
}
}
callNode.setJSType(narrowed);
return scope;
}
private FlowScope narrowScope(FlowScope scope, Node node, JSType narrowed) {
if (node.isThis()) {
// "this" references don't need to be modeled in the control flow graph.
return scope;
}
if (node.isGetProp()) {
return scope.inferQualifiedSlot(
node, node.getQualifiedName(), getJSType(node), narrowed, false);
}
return redeclareSimpleVar(scope, node, narrowed);
}
/**
* We only do forward type inference. We do not do full backwards type inference.
*
* In other words, if we have,
* <code>
* var x = f();
* g(x);
* </code>
* a forward type-inference engine would try to figure out the type
* of "x" from the return type of "f". A backwards type-inference engine
* would try to figure out the type of "x" from the parameter type of "g".
*
* <p>However, there are a few special syntactic forms where we do some some half-assed backwards
* type-inference, because programmers expect it in this day and age. To take an example from
* Java,
* <code>
* List<String> x = Lists.newArrayList();
* </code>
* The Java compiler will be able to infer the generic type of the List returned by
* newArrayList().
*
* <p>In much the same way, we do some special-case backwards inference for JS. Those cases are
* enumerated here.
*/
private void backwardsInferenceFromCallSite(Node n, FunctionType fnType, FlowScope scope) {
boolean updatedFnType = inferTemplatedTypesForCall(n, fnType, scope);
if (updatedFnType) {
fnType = n.getFirstChild().getJSType().toMaybeFunctionType();
}
updateTypeOfArguments(n, fnType);
updateBind(n);
}
/**
* When "bind" is called on a function, we infer the type of the returned
* "bound" function by looking at the number of parameters in the call site.
* We also infer the "this" type of the target, if it's a function expression.
*/
private void updateBind(Node n) {
CodingConvention.Bind bind =
compiler.getCodingConvention().describeFunctionBind(n, false, true);
if (bind == null) {
return;
}
Node target = bind.target;
FunctionType callTargetFn = getJSType(target)
.restrictByNotNullOrUndefined().toMaybeFunctionType();
if (callTargetFn == null) {
return;
}
if (bind.thisValue != null && target.isFunction()) {
JSType thisType = getJSType(bind.thisValue);
if (thisType.toObjectType() != null && !thisType.isUnknownType()
&& callTargetFn.getTypeOfThis().isUnknownType()) {
callTargetFn = new FunctionBuilder(registry)
.copyFromOtherFunction(callTargetFn)
.withTypeOfThis(thisType.toObjectType())
.build();
target.setJSType(callTargetFn);
}
}
n.setJSType(
callTargetFn.getBindReturnType(
// getBindReturnType expects the 'this' argument to be included.
bind.getBoundParameterCount() + 1));
}
/**
* For functions with function parameters, type inference will set the type of a function literal
* argument from the function parameter type.
*/
private void updateTypeOfArguments(Node n, FunctionType fnType) {
checkState(NodeUtil.isInvocation(n), n);
Iterator<Node> parameters = fnType.getParameters().iterator();
if (n.isTaggedTemplateLit()) {
// Skip the first parameter because it corresponds to a constructed array of the template lit
// subs, not an actual AST node, so there's nothing to update.
if (!parameters.hasNext()) {
// TypeCheck will warn if there is no first parameter. Just bail out here.
return;
}
parameters.next();
}
Iterator<Node> arguments = NodeUtil.getInvocationArgsAsIterable(n).iterator();
Node iParameter;
Node iArgument;
// Note: if there are too many or too few arguments, TypeCheck will warn.
while (parameters.hasNext() && arguments.hasNext()) {
iArgument = arguments.next();
JSType iArgumentType = getJSType(iArgument);
iParameter = parameters.next();
JSType iParameterType = getJSType(iParameter);
inferPropertyTypesToMatchConstraint(iArgumentType, iParameterType);
// If the parameter to the call is a function expression, propagate the
// function signature from the call site to the function node.
// Filter out non-function types (such as null and undefined) as
// we only care about FUNCTION subtypes here.
FunctionType restrictedParameter = null;
if (iParameterType.isUnionType()) {
UnionType union = iParameterType.toMaybeUnionType();
for (JSType alternative : union.getAlternates()) {
if (alternative.isFunctionType()) {
// There is only one function type per union.
restrictedParameter = alternative.toMaybeFunctionType();
break;
}
}
} else {
restrictedParameter = iParameterType.toMaybeFunctionType();
}
if (restrictedParameter != null
&& iArgument.isFunction()
&& iArgumentType.isFunctionType()) {
FunctionType argFnType = iArgumentType.toMaybeFunctionType();
JSDocInfo argJsdoc = iArgument.getJSDocInfo();
boolean declared = argJsdoc != null && argJsdoc.containsDeclaration();
iArgument.setJSType(matchFunction(restrictedParameter, argFnType, declared));
}
}
}
/**
* Take the current function type, and try to match the expected function
* type. This is a form of backwards-inference, like record-type constraint
* matching.
*/
private FunctionType matchFunction(
FunctionType expectedType, FunctionType currentType, boolean declared) {
if (declared) {
// If the function was declared but it doesn't have a known "this"
// but the expected type does, back fill it.
if (currentType.getTypeOfThis().isUnknownType()
&& !expectedType.getTypeOfThis().isUnknownType()) {
FunctionType replacement = new FunctionBuilder(registry)
.copyFromOtherFunction(currentType)
.withTypeOfThis(expectedType.getTypeOfThis())
.build();
return replacement;
}
} else {
// For now, we just make sure the current type has enough
// arguments to match the expected type, and return the
// expected type if it does.
if (currentType.getMaxArity() <= expectedType.getMaxArity()) {
return expectedType;
}
}
return currentType;
}
/** @param call A CALL, NEW, or TAGGED_TEMPLATELIT node */
private Map<TemplateType, JSType> inferTemplateTypesFromParameters(
FunctionType fnType, Node call) {
if (fnType.getTemplateTypeMap().getTemplateKeys().isEmpty()) {
return Collections.emptyMap();
}
Map<TemplateType, JSType> resolvedTypes = Maps.newIdentityHashMap();
Set<JSType> seenTypes = Sets.newIdentityHashSet();
Node callTarget = call.getFirstChild();
if (NodeUtil.isGet(callTarget)) {
Node obj = callTarget.getFirstChild();
maybeResolveTemplatedType(
fnType.getTypeOfThis(),
getJSType(obj).restrictByNotNullOrUndefined(),
resolvedTypes,
seenTypes);
}
if (call.isTaggedTemplateLit()) {
Iterator<Node> fnParameters = fnType.getParameters().iterator();
if (!fnParameters.hasNext()) {
// TypeCheck will warn if there are too few function parameters
return resolvedTypes;
}
// The first argument to the tag function is an array of strings (typed as ITemplateArray)
// but not an actual AST node
maybeResolveTemplatedType(
fnParameters.next().getJSType(),
getNativeType(I_TEMPLATE_ARRAY_TYPE),
resolvedTypes,
seenTypes);
// Resolve the remaining template types from the template literal substitutions.
maybeResolveTemplateTypeFromNodes(
Iterables.skip(fnType.getParameters(), 1),
NodeUtil.getInvocationArgsAsIterable(call),
resolvedTypes,
seenTypes);
} else if (call.hasMoreThanOneChild()) {
maybeResolveTemplateTypeFromNodes(
fnType.getParameters(),
NodeUtil.getInvocationArgsAsIterable(call),
resolvedTypes,
seenTypes);
}
return resolvedTypes;
}
private void maybeResolveTemplatedType(
JSType paramType,
JSType argType,
Map<TemplateType, JSType> resolvedTypes, Set<JSType> seenTypes) {
if (paramType.isTemplateType()) {
// example: @param {T}
resolvedTemplateType(
resolvedTypes, paramType.toMaybeTemplateType(), argType);
} else if (paramType.isUnionType()) {
// example: @param {Array.<T>|NodeList|Arguments|{length:number}}
UnionType unionType = paramType.toMaybeUnionType();
for (JSType alernative : unionType.getAlternates()) {
maybeResolveTemplatedType(alernative, argType, resolvedTypes, seenTypes);
}
} else if (paramType.isFunctionType()) {
FunctionType paramFunctionType = paramType.toMaybeFunctionType();
FunctionType argFunctionType = argType
.restrictByNotNullOrUndefined()
.collapseUnion()
.toMaybeFunctionType();
if (argFunctionType != null && argFunctionType.isSubtype(paramType)) {
// infer from return type of the function type
maybeResolveTemplatedType(
paramFunctionType.getTypeOfThis(),
argFunctionType.getTypeOfThis(), resolvedTypes, seenTypes);
// infer from return type of the function type
maybeResolveTemplatedType(
paramFunctionType.getReturnType(),
argFunctionType.getReturnType(), resolvedTypes, seenTypes);
// infer from parameter types of the function type
maybeResolveTemplateTypeFromNodes(
paramFunctionType.getParameters(),
argFunctionType.getParameters(), resolvedTypes, seenTypes);
}
} else if (paramType.isRecordType() && !paramType.isNominalType()) {
// example: @param {{foo:T}}
if (seenTypes.add(paramType)) {
ObjectType paramRecordType = paramType.toObjectType();
ObjectType argObjectType = argType.restrictByNotNullOrUndefined().toObjectType();
if (argObjectType != null && !argObjectType.isUnknownType()
&& !argObjectType.isEmptyType()) {
Set<String> names = paramRecordType.getPropertyNames();
for (String name : names) {
if (paramRecordType.hasOwnProperty(name) && argObjectType.hasProperty(name)) {
maybeResolveTemplatedType(paramRecordType.getPropertyType(name),
argObjectType.getPropertyType(name), resolvedTypes, seenTypes);
}
}
}
seenTypes.remove(paramType);
}
} else if (paramType.isTemplatizedType()) {
// example: @param {Array<T>}
TemplatizedType templatizedParamType = paramType.toMaybeTemplatizedType();
int keyCount = templatizedParamType.getTemplateTypes().size();
// TODO(johnlenz): determine why we are creating TemplatizedTypes for
// types with no type arguments.
if (keyCount > 0) {
ObjectType referencedParamType = templatizedParamType.getReferencedType();
JSType argObjectType = argType
.restrictByNotNullOrUndefined()
.collapseUnion();
if (argObjectType.isSubtypeOf(referencedParamType)) {
// If the argument type is a subtype of the parameter type, resolve any
// template types amongst their templatized types.
TemplateTypeMap paramTypeMap = paramType.getTemplateTypeMap();
ImmutableList<TemplateType> keys = paramTypeMap.getTemplateKeys();
TemplateTypeMap argTypeMap = argObjectType.getTemplateTypeMap();
for (int index = keys.size() - keyCount; index < keys.size(); index++) {
TemplateType key = keys.get(index);
maybeResolveTemplatedType(
paramTypeMap.getResolvedTemplateType(key),
argTypeMap.getResolvedTemplateType(key),
resolvedTypes, seenTypes);
}
}
}
}
}
private void maybeResolveTemplateTypeFromNodes(
Iterable<Node> declParams,
Iterable<Node> callParams,
Map<TemplateType, JSType> resolvedTypes, Set<JSType> seenTypes) {
maybeResolveTemplateTypeFromNodes(
declParams.iterator(), callParams.iterator(), resolvedTypes, seenTypes);
}
private void maybeResolveTemplateTypeFromNodes(
Iterator<Node> declParams,
Iterator<Node> callParams,
Map<TemplateType, JSType> resolvedTypes,
Set<JSType> seenTypes) {
while (declParams.hasNext() && callParams.hasNext()) {
Node declParam = declParams.next();
maybeResolveTemplatedType(
getJSType(declParam),
getJSType(callParams.next()),
resolvedTypes, seenTypes);
if (declParam.isVarArgs()) {
while (callParams.hasNext()) {
maybeResolveTemplatedType(
getJSType(declParam),
getJSType(callParams.next()),
resolvedTypes, seenTypes);
}
}
}
}
private static void resolvedTemplateType(
Map<TemplateType, JSType> map, TemplateType template, JSType resolved) {
JSType previous = map.get(template);
if (!resolved.isUnknownType()) {
if (previous == null) {
map.put(template, resolved);
} else {
JSType join = previous.getLeastSupertype(resolved);
map.put(template, join);
}
}
}
private static class TemplateTypeReplacer extends ModificationVisitor {
private final Map<TemplateType, JSType> replacements;
private final JSTypeRegistry registry;
boolean madeChanges = false;
TemplateTypeReplacer(
JSTypeRegistry registry, Map<TemplateType, JSType> replacements) {
super(registry, true);
this.registry = registry;
this.replacements = replacements;
}
@Override
public JSType caseTemplateType(TemplateType type) {
madeChanges = true;
JSType replacement = replacements.get(type);
return replacement != null ? replacement : registry.getNativeType(UNKNOWN_TYPE);
}
}
/**
* Build the type environment where type transformations will be evaluated.
* It only considers the template type variables that do not have a type
* transformation.
*/
private Map<String, JSType> buildTypeVariables(
Map<TemplateType, JSType> inferredTypes) {
Map<String, JSType> typeVars = new LinkedHashMap<>();
for (Entry<TemplateType, JSType> e : inferredTypes.entrySet()) {
// Only add the template type that do not have a type transformation
if (!e.getKey().isTypeTransformation()) {
typeVars.put(e.getKey().getReferenceName(), e.getValue());
}
}
return typeVars;
}
/** This function will evaluate the type transformations associated to the template types */
private Map<TemplateType, JSType> evaluateTypeTransformations(
ImmutableList<TemplateType> templateTypes,
Map<TemplateType, JSType> inferredTypes,
FlowScope scope) {
Map<String, JSType> typeVars = null;
Map<TemplateType, JSType> result = null;
TypeTransformation ttlObj = null;
for (TemplateType type : templateTypes) {
if (type.isTypeTransformation()) {
// Lazy initialization when the first type transformation is found
if (ttlObj == null) {
ttlObj = new TypeTransformation(compiler, scope.getDeclarationScope());
typeVars = buildTypeVariables(inferredTypes);
result = new LinkedHashMap<>();
}
// Evaluate the type transformation expression using the current
// known types for the template type variables
JSType transformedType = ttlObj.eval(
type.getTypeTransformation(),
ImmutableMap.copyOf(typeVars));
result.put(type, transformedType);
// Add the transformed type to the type variables
typeVars.put(type.getReferenceName(), transformedType);
}
}
return result;
}
/**
* For functions that use template types, specialize the function type for the call target based
* on the call-site specific arguments. Specifically, this enables inference to set the type of
* any function literal parameters based on these inferred types.
*/
private boolean inferTemplatedTypesForCall(Node n, FunctionType fnType, FlowScope scope) {
ImmutableList<TemplateType> keys = fnType.getTemplateTypeMap().getTemplateKeys();
if (keys.isEmpty()) {
return false;
}
// Try to infer the template types
Map<TemplateType, JSType> rawInferrence = inferTemplateTypesFromParameters(fnType, n);
Map<TemplateType, JSType> inferred = Maps.newIdentityHashMap();
for (TemplateType key : keys) {
JSType type = rawInferrence.get(key);
if (type == null) {
type = unknownType;
}
inferred.put(key, type);
}
// Try to infer the template types using the type transformations
Map<TemplateType, JSType> typeTransformations =
evaluateTypeTransformations(keys, inferred, scope);
if (typeTransformations != null) {
inferred.putAll(typeTransformations);
}
// Replace all template types. If we couldn't find a replacement, we
// replace it with UNKNOWN.
TemplateTypeReplacer replacer = new TemplateTypeReplacer(registry, inferred);
Node callTarget = n.getFirstChild();
FunctionType replacementFnType = fnType.visit(replacer).toMaybeFunctionType();
checkNotNull(replacementFnType);
callTarget.setJSType(replacementFnType);
n.setJSType(replacementFnType.getReturnType());
return replacer.madeChanges;
}
private FlowScope traverseNew(Node n, FlowScope scope) {
scope = traverseChildren(n, scope);
Node constructor = n.getFirstChild();
JSType constructorType = constructor.getJSType();
return traverseInstantiation(n, constructorType, scope);
}
private FlowScope traverseInstantiation(Node n, JSType constructorType, FlowScope scope) {
JSType type = null;
if (constructorType != null) {
constructorType = constructorType.restrictByNotNullOrUndefined();
if (constructorType.isUnknownType()) {
type = unknownType;
} else {
FunctionType ct = constructorType.toMaybeFunctionType();
if (ct == null && constructorType instanceof FunctionType) {
// If constructorType is a NoObjectType, then toMaybeFunctionType will
// return null. But NoObjectType implements the FunctionType
// interface, precisely because it can validly construct objects.
ct = (FunctionType) constructorType;
}
if (ct != null && ct.isConstructor()) {
backwardsInferenceFromCallSite(n, ct, scope);
// If necessary, create a TemplatizedType wrapper around the instance
// type, based on the types of the constructor parameters.
ObjectType instanceType = ct.getInstanceType();
Map<TemplateType, JSType> inferredTypes =
inferTemplateTypesFromParameters(ct, n);
if (inferredTypes.isEmpty()) {
type = instanceType;
} else {
type = registry.createTemplatizedType(instanceType, inferredTypes);
}
}
}
}
n.setJSType(type);
return scope;
}
private BooleanOutcomePair traverseAnd(Node n, FlowScope scope) {
return traverseShortCircuitingBinOp(n, scope);
}
private FlowScope traverseChildren(Node n, FlowScope scope) {
for (Node el = n.getFirstChild(); el != null; el = el.getNext()) {
scope = traverse(el, scope);
}
return scope;
}
private FlowScope traverseGetElem(Node n, FlowScope scope) {
scope = traverseChildren(n, scope);
Node indexKey = n.getLastChild();
JSType indexType = getJSType(indexKey);
if (indexType.isSymbolValueType()) {
// For now, allow symbols definitions/access on any type. In the future only allow them
// on the subtypes for which they are defined.
// TODO(b/77474174): Type well known symbol accesses.
n.setJSType(unknownType);
} else {
JSType type = getJSType(n.getFirstChild()).restrictByNotNullOrUndefined();
TemplateTypeMap typeMap = type.getTemplateTypeMap();
if (typeMap.hasTemplateType(registry.getObjectElementKey())) {
n.setJSType(typeMap.getResolvedTemplateType(registry.getObjectElementKey()));
}
}
return tightenTypeAfterDereference(n.getFirstChild(), scope);
}
private FlowScope traverseGetProp(Node n, FlowScope scope) {
Node objNode = n.getFirstChild();
Node property = n.getLastChild();
scope = traverseChildren(n, scope);
n.setJSType(
getPropertyType(
objNode.getJSType(), property.getString(), n, scope));
return tightenTypeAfterDereference(n.getFirstChild(), scope);
}
/**
* Suppose X is an object with inferred properties.
* Suppose also that X is used in a way where it would only type-check
* correctly if some of those properties are widened.
* Then we should be polite and automatically widen X's properties.
*
* For a concrete example, consider:
* param x {{prop: (number|undefined)}}
* function f(x) {}
* f({});
*
* If we give the anonymous object an inferred property of (number|undefined),
* then this code will type-check appropriately.
*/
private static void inferPropertyTypesToMatchConstraint(
JSType type, JSType constraint) {
if (type == null || constraint == null) {
return;
}
type.matchConstraint(constraint);
}
/**
* If we access a property of a symbol, then that symbol is not
* null or undefined.
*/
private FlowScope tightenTypeAfterDereference(Node n, FlowScope scope) {
if (n.isQualifiedName()) {
JSType type = getJSType(n);
JSType narrowed = type.restrictByNotNullOrUndefined();
if (!type.equals(narrowed)) {
scope = narrowScope(scope, n, narrowed);
}
}
return scope;
}
private JSType getPropertyType(JSType objType, String propName,
Node n, FlowScope scope) {
// We often have a couple of different types to choose from for the
// property. Ordered by accuracy, we have
// 1) A locally inferred qualified name (which is in the FlowScope)
// 2) A globally declared qualified name (which is in the FlowScope)
// 3) A property on the owner type (which is on objType)
// 4) A name in the type registry (as a last resort)
JSType propertyType = null;
boolean isLocallyInferred = false;
// Scopes sometimes contain inferred type info about qualified names.
String qualifiedName = n.getQualifiedName();
StaticTypedSlot var = qualifiedName != null ? scope.getSlot(qualifiedName) : null;
if (var != null) {
JSType varType = var.getType();
if (varType != null) {
boolean isDeclared = !var.isTypeInferred();
isLocallyInferred = (var != getDeclaredVar(scope, qualifiedName));
if (isDeclared || isLocallyInferred) {
propertyType = varType;
}
}
}
if (propertyType == null && objType != null) {
JSType foundType = objType.findPropertyType(propName);
if (foundType != null) {
propertyType = foundType;
}
}
if (propertyType != null && objType != null) {
JSType restrictedObjType = objType.restrictByNotNullOrUndefined();
if (!restrictedObjType.getTemplateTypeMap().isEmpty()
&& propertyType.hasAnyTemplateTypes()) {
TemplateTypeMap typeMap = restrictedObjType.getTemplateTypeMap();
TemplateTypeMapReplacer replacer = new TemplateTypeMapReplacer(
registry, typeMap);
propertyType = propertyType.visit(replacer);
}
}
if ((propertyType == null || propertyType.isUnknownType())
&& qualifiedName != null) {
// If we find this node in the registry, then we can infer its type.
ObjectType regType = ObjectType.cast(
registry.getType(scope.getDeclarationScope(), qualifiedName));
if (regType != null) {
propertyType = regType.getConstructor();
}
}
if (propertyType == null) {
return unknownType;
} else if (propertyType.isEquivalentTo(unknownType) && isLocallyInferred) {
// If the type has been checked in this scope,
// then use CHECKED_UNKNOWN_TYPE instead to indicate that.
return getNativeType(CHECKED_UNKNOWN_TYPE);
} else {
return propertyType;
}
}
private BooleanOutcomePair traverseOr(Node n, FlowScope scope) {
return traverseShortCircuitingBinOp(n, scope);
}
private BooleanOutcomePair traverseShortCircuitingBinOp(
Node n, FlowScope scope) {
checkArgument(n.isAnd() || n.isOr());
boolean nIsAnd = n.isAnd();
Node left = n.getFirstChild();
Node right = n.getLastChild();
// type the left node
BooleanOutcomePair leftOutcome = traverseWithinShortCircuitingBinOp(left, scope);
JSType leftType = left.getJSType();
// reverse abstract interpret the left node to produce the correct
// scope in which to verify the right node
FlowScope rightScope =
reverseInterpreter.getPreciserScopeKnowingConditionOutcome(
left, leftOutcome.getOutcomeFlowScope(left.getToken(), nIsAnd), nIsAnd);
// type the right node
BooleanOutcomePair rightOutcome = traverseWithinShortCircuitingBinOp(right, rightScope);
JSType rightType = right.getJSType();
JSType type;
BooleanOutcomePair outcome;
if (leftType != null && rightType != null) {
leftType = leftType.getRestrictedTypeGivenToBooleanOutcome(!nIsAnd);
if (leftOutcome.toBooleanOutcomes == BooleanLiteralSet.get(!nIsAnd)) {
// Either n is && and lhs is false, or n is || and lhs is true.
// Use the restricted left type; the right side never gets evaluated.
type = leftType;
outcome = leftOutcome;
} else {
// Use the join of the restricted left type knowing the outcome of the
// ToBoolean predicate and of the right type.
type = leftType.getLeastSupertype(rightType);
outcome = new BooleanOutcomePair(
joinBooleanOutcomes(nIsAnd,
leftOutcome.toBooleanOutcomes, rightOutcome.toBooleanOutcomes),
joinBooleanOutcomes(nIsAnd,
leftOutcome.booleanValues, rightOutcome.booleanValues),
leftOutcome.getJoinedFlowScope(),
rightOutcome.getJoinedFlowScope());
}
// Exclude the boolean type if the literal set is empty because a boolean
// can never actually be returned.
if (outcome.booleanValues == BooleanLiteralSet.EMPTY
&& getNativeType(BOOLEAN_TYPE).isSubtypeOf(type)) {
// Exclusion only makes sense for a union type.
if (type.isUnionType()) {
type = type.toMaybeUnionType().getRestrictedUnion(
getNativeType(BOOLEAN_TYPE));
}
}
} else {
type = null;
outcome = new BooleanOutcomePair(
BooleanLiteralSet.BOTH, BooleanLiteralSet.BOTH,
leftOutcome.getJoinedFlowScope(),
rightOutcome.getJoinedFlowScope());
}
n.setJSType(type);
return outcome;
}
private BooleanOutcomePair traverseWithinShortCircuitingBinOp(
Node n, FlowScope scope) {
switch (n.getToken()) {
case AND:
return traverseAnd(n, scope);
case OR:
return traverseOr(n, scope);
default:
scope = traverse(n, scope);
return newBooleanOutcomePair(n.getJSType(), scope);
}
}
private FlowScope traverseAwait(Node await, FlowScope scope) {
scope = traverseChildren(await, scope);
Node expr = await.getFirstChild();
JSType exprType = getJSType(expr);
await.setJSType(Promises.getResolvedType(registry, exprType));
return scope;
}
private static BooleanLiteralSet joinBooleanOutcomes(
boolean isAnd, BooleanLiteralSet left, BooleanLiteralSet right) {
// A truthy value on the lhs of an {@code &&} can never make it to the
// result. Same for a falsy value on the lhs of an {@code ||}.
// Hence the intersection.
return right.union(left.intersection(BooleanLiteralSet.get(!isAnd)));
}
/**
* When traversing short-circuiting binary operations, we need to keep track
* of two sets of boolean literals:
* 1. {@code toBooleanOutcomes}: boolean literals as converted from any types,
* 2. {@code booleanValues}: boolean literals from just boolean types.
*/
private final class BooleanOutcomePair {
final BooleanLiteralSet toBooleanOutcomes;
final BooleanLiteralSet booleanValues;
// The scope if only half of the expression executed, when applicable.
final FlowScope leftScope;
// The scope when the whole expression executed.
final FlowScope rightScope;
// The scope when we don't know how much of the expression is executed.
FlowScope joinedScope = null;
BooleanOutcomePair(
BooleanLiteralSet toBooleanOutcomes, BooleanLiteralSet booleanValues,
FlowScope leftScope, FlowScope rightScope) {
this.toBooleanOutcomes = toBooleanOutcomes;
this.booleanValues = booleanValues;
this.leftScope = leftScope;
this.rightScope = rightScope;
}
/**
* Gets the safe estimated scope without knowing if all of the
* subexpressions will be evaluated.
*/
FlowScope getJoinedFlowScope() {
if (joinedScope == null) {
if (leftScope == rightScope) {
joinedScope = rightScope;
} else {
joinedScope = join(leftScope, rightScope);
}
}
return joinedScope;
}
/**
* Gets the outcome scope if we do know the outcome of the entire
* expression.
*/
FlowScope getOutcomeFlowScope(Token nodeType, boolean outcome) {
if ((nodeType == Token.AND && outcome) || (nodeType == Token.OR && !outcome)) {
// We know that the whole expression must have executed.
return rightScope;
} else {
return getJoinedFlowScope();
}
}
}
private BooleanOutcomePair newBooleanOutcomePair(
JSType jsType, FlowScope flowScope) {
if (jsType == null) {
return new BooleanOutcomePair(
BooleanLiteralSet.BOTH, BooleanLiteralSet.BOTH, flowScope, flowScope);
}
return new BooleanOutcomePair(
jsType.getPossibleToBooleanOutcomes(),
registry.getNativeType(BOOLEAN_TYPE).isSubtypeOf(jsType)
? BooleanLiteralSet.BOTH
: BooleanLiteralSet.EMPTY,
flowScope,
flowScope);
}
@CheckReturnValue
private FlowScope redeclareSimpleVar(FlowScope scope, Node nameNode, JSType varType) {
checkState(nameNode.isName(), nameNode);
String varName = nameNode.getString();
if (varType == null) {
varType = getNativeType(JSTypeNative.UNKNOWN_TYPE);
}
if (isUnflowable(getDeclaredVar(scope, varName))) {
return scope;
}
return scope.inferSlotType(varName, varType);
}
private boolean isUnflowable(TypedVar v) {
return v != null
&& v.isLocal()
&& v.isMarkedEscaped()
// It's OK to flow a variable in the scope where it's escaped.
&& v.getScope().getClosestContainerScope() == containerScope;
}
/**
* This method gets the JSType from the Node argument and verifies that it is
* present.
*/
private JSType getJSType(Node n) {
JSType jsType = n.getJSType();
if (jsType == null) {
// TODO(nicksantos): This branch indicates a compiler bug, not worthy of
// halting the compilation but we should log this and analyze to track
// down why it happens. This is not critical and will be resolved over
// time as the type checker is extended.
return unknownType;
} else {
return jsType;
}
}
private JSType getNativeType(JSTypeNative typeId) {
return registry.getNativeType(typeId);
}
private static TypedVar getDeclaredVar(FlowScope scope, String name) {
return ((TypedScope) scope.getDeclarationScope()).getVar(name);
}
}
| src/com/google/javascript/jscomp/TypeInference.java | /*
* Copyright 2008 The Closure Compiler 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.javascript.jscomp;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static com.google.javascript.rhino.jstype.JSTypeNative.ARRAY_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.BOOLEAN_OBJECT_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.BOOLEAN_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.CHECKED_UNKNOWN_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.ITERABLE_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.I_TEMPLATE_ARRAY_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.NULL_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.NUMBER_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.NUMBER_VALUE_OR_OBJECT_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.STRING_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.UNKNOWN_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.VOID_TYPE;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.javascript.jscomp.CodingConvention.AssertionFunctionSpec;
import com.google.javascript.jscomp.ControlFlowGraph.Branch;
import com.google.javascript.jscomp.graph.DiGraph.DiGraphEdge;
import com.google.javascript.jscomp.type.FlowScope;
import com.google.javascript.jscomp.type.ReverseAbstractInterpreter;
import com.google.javascript.rhino.JSDocInfo;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.Token;
import com.google.javascript.rhino.jstype.BooleanLiteralSet;
import com.google.javascript.rhino.jstype.FunctionBuilder;
import com.google.javascript.rhino.jstype.FunctionType;
import com.google.javascript.rhino.jstype.JSType;
import com.google.javascript.rhino.jstype.JSTypeNative;
import com.google.javascript.rhino.jstype.JSTypeRegistry;
import com.google.javascript.rhino.jstype.ModificationVisitor;
import com.google.javascript.rhino.jstype.ObjectType;
import com.google.javascript.rhino.jstype.StaticTypedSlot;
import com.google.javascript.rhino.jstype.TemplateType;
import com.google.javascript.rhino.jstype.TemplateTypeMap;
import com.google.javascript.rhino.jstype.TemplateTypeMapReplacer;
import com.google.javascript.rhino.jstype.TemplatizedType;
import com.google.javascript.rhino.jstype.UnionType;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.annotation.CheckReturnValue;
/**
* Type inference within a script node or a function body, using the data-flow
* analysis framework.
*
*/
class TypeInference
extends DataFlowAnalysis.BranchedForwardDataFlowAnalysis<Node, FlowScope> {
// TODO(johnlenz): We no longer make this check, but we should.
static final DiagnosticType FUNCTION_LITERAL_UNDEFINED_THIS =
DiagnosticType.warning(
"JSC_FUNCTION_LITERAL_UNDEFINED_THIS",
"Function literal argument refers to undefined this argument");
private final AbstractCompiler compiler;
private final JSTypeRegistry registry;
private final ReverseAbstractInterpreter reverseInterpreter;
private final FlowScope functionScope;
private final FlowScope bottomScope;
private final TypedScope containerScope;
private final TypedScopeCreator scopeCreator;
private final Map<String, AssertionFunctionSpec> assertionFunctionsMap;
// Scopes that have had their unbound untyped vars inferred as undefined.
private final Set<TypedScope> inferredUnboundVars = new HashSet<>();
// For convenience
private final ObjectType unknownType;
TypeInference(AbstractCompiler compiler, ControlFlowGraph<Node> cfg,
ReverseAbstractInterpreter reverseInterpreter,
TypedScope syntacticScope, TypedScopeCreator scopeCreator,
Map<String, AssertionFunctionSpec> assertionFunctionsMap) {
super(cfg, new LinkedFlowScope.FlowScopeJoinOp());
this.compiler = compiler;
this.registry = compiler.getTypeRegistry();
this.reverseInterpreter = reverseInterpreter;
this.unknownType = registry.getNativeObjectType(UNKNOWN_TYPE);
this.containerScope = syntacticScope;
this.scopeCreator = scopeCreator;
this.assertionFunctionsMap = assertionFunctionsMap;
FlowScope entryScope =
inferDeclarativelyUnboundVarsWithoutTypes(
LinkedFlowScope.createEntryLattice(syntacticScope));
this.functionScope = inferParameters(syntacticScope, entryScope);
this.bottomScope =
LinkedFlowScope.createEntryLattice(
TypedScope.createLatticeBottom(syntacticScope.getRootNode()));
}
@CheckReturnValue
private FlowScope inferDeclarativelyUnboundVarsWithoutTypes(FlowScope flow) {
TypedScope scope = (TypedScope) flow.getDeclarationScope();
if (!inferredUnboundVars.add(scope)) {
return flow;
}
// For each local variable declared with the VAR keyword, the entry
// type is VOID.
for (TypedVar var : scope.getDeclarativelyUnboundVarsWithoutTypes()) {
if (isUnflowable(var)) {
continue;
}
flow = flow.inferSlotType(var.getName(), getNativeType(VOID_TYPE));
}
return flow;
}
/** Infers all of a function's parameters if their types aren't declared. */
@SuppressWarnings("ReferenceEquality") // unknownType is a singleton
private FlowScope inferParameters(TypedScope functionScope, FlowScope entryFlowScope) {
Node functionNode = functionScope.getRootNode();
Node astParameters = functionNode.getSecondChild();
Node iifeArgumentNode = null;
if (NodeUtil.isInvocationTarget(functionNode)) {
iifeArgumentNode = functionNode.getNext();
}
FunctionType functionType =
JSType.toMaybeFunctionType(functionNode.getJSType());
if (functionType != null) {
Node parameterTypes = functionType.getParametersNode();
if (parameterTypes != null) {
Node parameterTypeNode = parameterTypes.getFirstChild();
for (Node astParameter : astParameters.children()) {
boolean isRest = false;
Node defaultValue = null;
if (astParameter.isDefaultValue()) {
defaultValue = astParameter.getSecondChild();
astParameter = astParameter.getFirstChild();
}
if (astParameter.isRest()) {
// e.g. `function f(p1, ...restParamName) {}`
// set astParameter = restParamName
astParameter = astParameter.getOnlyChild();
isRest = true;
}
if (!astParameter.isName()) {
// TODO(lharker): support destructuring parameters
continue;
}
if (iifeArgumentNode != null && iifeArgumentNode.isSpread()) {
// block inference on all parameters that might possibly be set by a spread, e.g. `z` in
// (function f(x, y, z = 1))(...[1, 2], 'foo')
iifeArgumentNode = null;
}
TypedVar var = functionScope.getVar(astParameter.getString());
checkNotNull(var);
if (var.isTypeInferred() && (var.getType() == unknownType || isRest)) {
JSType newType = null;
if (iifeArgumentNode != null) {
newType = iifeArgumentNode.getJSType();
} else if (parameterTypeNode != null) {
newType = parameterTypeNode.getJSType();
}
if (newType != null) {
if (isRest) {
// convert 'number' into 'Array<number>' for rest parameters
newType =
registry.createTemplatizedType(
registry.getNativeObjectType(ARRAY_TYPE), newType);
}
var.setType(newType);
astParameter.setJSType(newType);
}
}
if (parameterTypeNode != null) {
parameterTypeNode = parameterTypeNode.getNext();
}
if (iifeArgumentNode != null) {
iifeArgumentNode = iifeArgumentNode.getNext();
}
// 1. do type inference within the default value expression
// 2. add a flow scope slot for the assignment to the parameter. (which will not matter
// for declared parameters, just inferred parameters.
if (defaultValue != null) {
traverse(defaultValue, entryFlowScope);
JSType newType =
registry.createUnionType(
getJSType(astParameter).restrictByNotUndefined(), getJSType(defaultValue));
entryFlowScope =
updateScopeForAssignment(
entryFlowScope, astParameter, getJSType(astParameter), newType);
}
}
}
}
return entryFlowScope;
}
@Override
FlowScope createInitialEstimateLattice() {
return bottomScope;
}
@Override
FlowScope createEntryLattice() {
return functionScope;
}
@Override
@CheckReturnValue
FlowScope flowThrough(Node n, FlowScope input) {
// If we have not walked a path from <entry> to <n>, then we don't
// want to infer anything about this scope.
if (input == bottomScope) {
return input;
}
Node root = NodeUtil.getEnclosingScopeRoot(n);
FlowScope output = input.withSyntacticScope(scopeCreator.createScope(root));
output = inferDeclarativelyUnboundVarsWithoutTypes(output);
output = traverse(n, output);
return output;
}
@Override
@SuppressWarnings({"fallthrough", "incomplete-switch"})
List<FlowScope> branchedFlowThrough(Node source, FlowScope input) {
// NOTE(nicksantos): Right now, we just treat ON_EX edges like UNCOND
// edges. If we wanted to be perfect, we'd actually JOIN all the out
// lattices of this flow with the in lattice, and then make that the out
// lattice for the ON_EX edge. But it's probably too expensive to be
// worthwhile.
FlowScope output = flowThrough(source, input);
Node condition = null;
FlowScope conditionFlowScope = null;
BooleanOutcomePair conditionOutcomes = null;
List<DiGraphEdge<Node, Branch>> branchEdges = getCfg().getOutEdges(source);
List<FlowScope> result = new ArrayList<>(branchEdges.size());
for (DiGraphEdge<Node, Branch> branchEdge : branchEdges) {
Branch branch = branchEdge.getValue();
FlowScope newScope = output;
switch (branch) {
case ON_TRUE:
if (source.isForIn() || source.isForOf()) {
Node item = source.getFirstChild();
Node obj = item.getNext();
FlowScope informed = traverse(obj, output);
if (NodeUtil.isNameDeclaration(item)) {
item = item.getFirstChild();
}
if (item.isDestructuringLhs()) {
item = item.getFirstChild();
}
if (source.isForIn()) {
// item is assigned a property name, so its type should be string.
if (item.isName()) {
JSType iterKeyType = getNativeType(STRING_TYPE);
JSType objType = getJSType(obj).autobox();
JSType objIndexType =
objType
.getTemplateTypeMap()
.getResolvedTemplateType(registry.getObjectIndexKey());
if (objIndexType != null && !objIndexType.isUnknownType()) {
JSType narrowedKeyType = iterKeyType.getGreatestSubtype(objIndexType);
if (!narrowedKeyType.isEmptyType()) {
iterKeyType = narrowedKeyType;
}
}
informed = redeclareSimpleVar(informed, item, iterKeyType);
}
} else {
// for/of. The type of `item` is the type parameter of the Iterable type.
JSType objType = getJSType(obj).autobox();
// NOTE: this returns the UNKNOWN_TYPE if objType does not implement Iterable
JSType newType = objType.getInstantiatedTypeArgument(getNativeType(ITERABLE_TYPE));
// Note that `item` can be an arbitrary LHS expression we need to check.
if (item.isDestructuringPattern()) {
// for (const {x, y} of data) {
informed = traverseDestructuringPattern(item, informed, newType);
} else {
informed = traverse(item, informed);
informed = updateScopeForAssignment(informed, item, item.getJSType(), newType);
}
}
newScope = informed;
break;
}
// FALL THROUGH
case ON_FALSE:
if (condition == null) {
condition = NodeUtil.getConditionExpression(source);
if (condition == null && source.isCase()) {
condition = source;
// conditionFlowScope is cached from previous iterations
// of the loop.
if (conditionFlowScope == null) {
conditionFlowScope = traverse(condition.getFirstChild(), output);
}
}
}
if (condition != null) {
if (condition.isAnd() || condition.isOr()) {
// When handling the short-circuiting binary operators,
// the outcome scope on true can be different than the outcome
// scope on false.
//
// TODO(nicksantos): The "right" way to do this is to
// carry the known outcome all the way through the
// recursive traversal, so that we can construct a
// different flow scope based on the outcome. However,
// this would require a bunch of code and a bunch of
// extra computation for an edge case. This seems to be
// a "good enough" approximation.
// conditionOutcomes is cached from previous iterations
// of the loop.
if (conditionOutcomes == null) {
conditionOutcomes =
condition.isAnd()
? traverseAnd(condition, output)
: traverseOr(condition, output);
}
newScope =
reverseInterpreter.getPreciserScopeKnowingConditionOutcome(
condition,
conditionOutcomes.getOutcomeFlowScope(
condition.getToken(), branch == Branch.ON_TRUE),
branch == Branch.ON_TRUE);
} else {
// conditionFlowScope is cached from previous iterations
// of the loop.
if (conditionFlowScope == null) {
conditionFlowScope = traverse(condition, output);
}
newScope =
reverseInterpreter.getPreciserScopeKnowingConditionOutcome(
condition, conditionFlowScope, branch == Branch.ON_TRUE);
}
}
break;
default:
break;
}
result.add(newScope);
}
return result;
}
private FlowScope traverse(Node n, FlowScope scope) {
switch (n.getToken()) {
case ASSIGN:
scope = traverseAssign(n, scope);
break;
case NAME:
scope = traverseName(n, scope);
break;
case GETPROP:
scope = traverseGetProp(n, scope);
break;
case CLASS:
scope = traverseClass(n, scope);
break;
case AND:
scope = traverseAnd(n, scope).getJoinedFlowScope();
break;
case OR:
scope = traverseOr(n, scope).getJoinedFlowScope();
break;
case HOOK:
scope = traverseHook(n, scope);
break;
case OBJECTLIT:
scope = traverseObjectLiteral(n, scope);
break;
case CALL:
scope = traverseFunctionInvocation(n, scope);
scope = tightenTypesAfterAssertions(scope, n);
break;
case NEW:
scope = traverseNew(n, scope);
break;
case NEW_TARGET:
traverseNewTarget(n);
break;
case ASSIGN_ADD:
case ADD:
scope = traverseAdd(n, scope);
break;
case POS:
case NEG:
scope = traverse(n.getFirstChild(), scope); // Find types.
n.setJSType(getNativeType(NUMBER_TYPE));
break;
case ARRAYLIT:
scope = traverseArrayLiteral(n, scope);
break;
case THIS:
n.setJSType(scope.getTypeOfThis());
break;
case ASSIGN_LSH:
case ASSIGN_RSH:
case ASSIGN_URSH:
case ASSIGN_DIV:
case ASSIGN_MOD:
case ASSIGN_BITAND:
case ASSIGN_BITXOR:
case ASSIGN_BITOR:
case ASSIGN_MUL:
case ASSIGN_SUB:
case ASSIGN_EXPONENT:
scope = traverseAssignOp(n, scope, getNativeType(NUMBER_TYPE));
break;
case LSH:
case RSH:
case URSH:
case DIV:
case MOD:
case BITAND:
case BITXOR:
case BITOR:
case MUL:
case SUB:
case DEC:
case INC:
case BITNOT:
case EXPONENT:
scope = traverseChildren(n, scope);
n.setJSType(getNativeType(NUMBER_TYPE));
break;
case COMMA:
scope = traverseChildren(n, scope);
n.setJSType(getJSType(n.getLastChild()));
break;
case TEMPLATELIT:
case TYPEOF:
scope = traverseChildren(n, scope);
n.setJSType(getNativeType(STRING_TYPE));
break;
case TEMPLATELIT_SUB:
// TEMPLATELIT_SUBs are untyped but we do need to traverse their children.
scope = traverseChildren(n, scope);
break;
case TAGGED_TEMPLATELIT:
scope = traverseFunctionInvocation(n, scope);
break;
case DELPROP:
case LT:
case LE:
case GT:
case GE:
case NOT:
case EQ:
case NE:
case SHEQ:
case SHNE:
case INSTANCEOF:
case IN:
scope = traverseChildren(n, scope);
n.setJSType(getNativeType(BOOLEAN_TYPE));
break;
case GETELEM:
scope = traverseGetElem(n, scope);
break;
case EXPR_RESULT:
scope = traverseChildren(n, scope);
if (n.getFirstChild().isGetProp()) {
Node getprop = n.getFirstChild();
ObjectType ownerType = ObjectType.cast(
getJSType(getprop.getFirstChild()).restrictByNotNullOrUndefined());
if (ownerType != null) {
ensurePropertyDeclaredHelper(getprop, ownerType, scope);
}
}
break;
case SWITCH:
scope = traverse(n.getFirstChild(), scope);
break;
case RETURN:
scope = traverseReturn(n, scope);
break;
case YIELD:
scope = traverseChildren(n, scope);
n.setJSType(getNativeType(UNKNOWN_TYPE));
break;
case VAR:
case LET:
case CONST:
scope = traverseDeclaration(n, scope);
break;
case THROW:
scope = traverseChildren(n, scope);
break;
case CATCH:
scope = traverseCatch(n, scope);
break;
case CAST:
scope = traverseChildren(n, scope);
JSDocInfo info = n.getJSDocInfo();
if (info != null && info.hasType()) {
n.setJSType(info.getType().evaluate(scope.getDeclarationScope(), registry));
}
break;
case SUPER:
traverseSuper(n);
break;
case SPREAD:
// The spread itself has no type, but the expression it contains does and may affect
// type inference.
scope = traverseChildren(n, scope);
break;
case AWAIT:
scope = traverseAwait(n, scope);
break;
case VOID:
n.setJSType(getNativeType(VOID_TYPE));
scope = traverseChildren(n, scope);
break;
case ROOT:
case SCRIPT:
case FUNCTION:
case PARAM_LIST:
case BLOCK:
case EMPTY:
case IF:
case WHILE:
case DO:
case FOR:
case FOR_IN:
case FOR_OF:
case FOR_AWAIT_OF:
case BREAK:
case CONTINUE:
case TRY:
case CASE:
case DEFAULT_CASE:
case WITH:
case DEBUGGER:
// These don't need to be typed here, since they only affect control flow.
break;
case TRUE:
case FALSE:
case STRING:
case NUMBER:
case NULL:
case REGEXP:
// Primitives are typed in TypedScopeCreator.AbstractScopeBuilder#attachLiteralTypes
break;
default:
throw new IllegalStateException(
"Type inference doesn't know to handle token " + n.getToken());
}
return scope;
}
private void traverseSuper(Node superNode) {
// Find the closest non-arrow function (TODO(sdh): this could be an AbstractScope method).
TypedScope scope = containerScope;
while (scope != null && !NodeUtil.isVanillaFunction(scope.getRootNode())) {
scope = scope.getParent();
}
if (scope == null) {
superNode.setJSType(unknownType);
return;
}
Node root = scope.getRootNode();
JSType jsType = root.getJSType();
FunctionType functionType = jsType != null ? jsType.toMaybeFunctionType() : null;
ObjectType superNodeType = unknownType;
Node context = superNode.getParent();
// NOTE: we currently transpile subclass constructors to use "super.apply", which is not
// actually valid ES6. For now, provide a special case to support this, but it should be
// removed once class transpilation is after type checking.
if (context.isCall()) {
// Call the superclass constructor.
if (functionType != null && functionType.isConstructor()) {
FunctionType superCtor = functionType.getSuperClassConstructor();
if (superCtor != null) {
superNodeType = superCtor;
}
}
} else if (context.isGetProp() || context.isGetElem()) {
// TODO(sdh): once getTypeOfThis supports statics, we can get rid of this branch, as well as
// the vanilla function search at the top and just return functionScope.getVar("super").
if (root.getParent().isStaticMember()) {
// Since the root is a static member, we're guaranteed that the parent scope is a class.
Node classNode = scope.getParent().getRootNode();
checkState(classNode.isClass());
FunctionType thisCtor = JSType.toMaybeFunctionType(classNode.getJSType());
if (thisCtor != null) {
FunctionType superCtor = thisCtor.getSuperClassConstructor();
if (superCtor != null) {
superNodeType = superCtor;
}
}
} else if (functionType != null) {
// Refer to a superclass instance property.
ObjectType thisInstance = ObjectType.cast(functionType.getTypeOfThis());
if (thisInstance != null) {
FunctionType superCtor = thisInstance.getSuperClassConstructor();
if (superCtor != null) {
ObjectType superInstance = superCtor.getInstanceType();
if (superInstance != null) {
superNodeType = superInstance;
}
}
}
}
}
superNode.setJSType(superNodeType);
}
private void traverseNewTarget(Node newTargetNode) {
// new.target is (undefined|!Function) within a vanilla function and !Function within an ES6
// constructor.
// Find the closest non-arrow function (TODO(sdh): this could be an AbstractScope method).
TypedScope scope = containerScope;
while (scope != null && !NodeUtil.isVanillaFunction(scope.getRootNode())) {
scope = scope.getParent();
}
if (scope == null) {
// NOTE: we already have a parse error for new.target outside a function. The only other case
// where this might happen is a top-level arrow function, which is a parse error in the VM,
// but allowed by our parser.
newTargetNode.setJSType(unknownType);
return;
}
Node root = scope.getRootNode();
Node parent = root.getParent();
if (parent.isMemberFunctionDef() && parent.getGrandparent().isClass()) {
// In an ES6 constuctor, new.target may not be undefined. In any other method, it must be
// undefined, since methods are not constructable.
JSTypeNative type =
"constructor".equals(parent.getString()) ? JSTypeNative.U2U_CONSTRUCTOR_TYPE : VOID_TYPE;
newTargetNode.setJSType(registry.getNativeType(type));
} else {
// Other functions also include undefined, in case they are not called with 'new'.
newTargetNode.setJSType(
registry.createUnionType(
registry.getNativeType(JSTypeNative.U2U_CONSTRUCTOR_TYPE),
registry.getNativeType(VOID_TYPE)));
}
}
/** Traverse a return value. */
@CheckReturnValue
private FlowScope traverseReturn(Node n, FlowScope scope) {
scope = traverseChildren(n, scope);
Node retValue = n.getFirstChild();
if (retValue != null) {
JSType type = functionScope.getRootNode().getJSType();
if (type != null) {
FunctionType fnType = type.toMaybeFunctionType();
if (fnType != null) {
inferPropertyTypesToMatchConstraint(
retValue.getJSType(), fnType.getReturnType());
}
}
}
return scope;
}
/**
* Any value can be thrown, so it's really impossible to determine the type of a CATCH param.
* Treat it as the UNKNOWN type.
*/
@CheckReturnValue
private FlowScope traverseCatch(Node catchNode, FlowScope scope) {
Node name = catchNode.getFirstChild();
JSType type;
// If the catch expression name was declared in the catch use that type,
// otherwise use "unknown".
JSDocInfo info = name.getJSDocInfo();
if (info != null && info.hasType()) {
type = info.getType().evaluate(scope.getDeclarationScope(), registry);
} else {
type = getNativeType(JSTypeNative.UNKNOWN_TYPE);
}
name.setJSType(type);
return redeclareSimpleVar(scope, name, type);
}
@CheckReturnValue
private FlowScope traverseAssign(Node n, FlowScope scope) {
Node target = n.getFirstChild();
Node value = n.getLastChild();
if (target.isDestructuringPattern()) {
scope = traverse(value, scope);
JSType valueType = getJSType(value);
n.setJSType(valueType);
return traverseDestructuringPattern(target, scope, valueType);
} else {
scope = traverseChildren(n, scope);
JSType targetType = target.getJSType();
JSType valueType = getJSType(value);
n.setJSType(valueType);
return updateScopeForAssignment(scope, target, targetType, valueType);
}
}
@CheckReturnValue
private FlowScope traverseAssignOp(Node n, FlowScope scope, JSType resultType) {
Node left = n.getFirstChild();
scope = traverseChildren(n, scope);
JSType leftType = left.getJSType();
n.setJSType(resultType);
// The lhs is both an input and an output, so don't update the input type here.
return updateScopeForAssignment(scope, left, leftType, resultType, null);
}
private static boolean isInExternFile(Node n) {
return NodeUtil.getSourceFile(n).isExtern();
}
private static boolean isPossibleMixinApplication(Node lvalue, Node rvalue) {
if (isInExternFile(lvalue)) {
return true;
}
JSDocInfo jsdoc = NodeUtil.getBestJSDocInfo(lvalue);
return jsdoc != null
&& jsdoc.isConstructor()
&& jsdoc.getImplementedInterfaceCount() > 0
&& lvalue.isQualifiedName()
&& rvalue.isCall();
}
/**
* @param constructor A constructor function defined by a call, which may be a mixin application.
* The constructor implements at least one interface. If the constructor is missing some
* properties of the inherited interfaces, this method declares these properties.
*/
private static void addMissingInterfaceProperties(JSType constructor) {
if (constructor != null && constructor.isConstructor()) {
FunctionType f = constructor.toMaybeFunctionType();
ObjectType proto = f.getPrototype();
for (ObjectType interf : f.getImplementedInterfaces()) {
for (String pname : interf.getPropertyNames()) {
if (!proto.hasProperty(pname)) {
proto.defineDeclaredProperty(pname, interf.getPropertyType(pname), null);
}
}
}
}
}
@CheckReturnValue
private FlowScope updateScopeForAssignment(
FlowScope scope, Node target, JSType targetType, JSType resultType) {
return updateScopeForAssignment(scope, target, targetType, resultType, target);
}
/** Updates the scope according to the result of an assignment. */
@CheckReturnValue
private FlowScope updateScopeForAssignment(
FlowScope scope, Node target, JSType targetType, JSType resultType, Node updateNode) {
checkNotNull(resultType);
checkState(updateNode == null || updateNode == target);
Node right = NodeUtil.getRValueOfLValue(target);
if (isPossibleMixinApplication(target, right)) {
addMissingInterfaceProperties(targetType);
}
switch (target.getToken()) {
case NAME:
String varName = target.getString();
TypedVar var = getDeclaredVar(scope, varName);
JSType varType = var == null ? null : var.getType();
boolean isVarDeclaration =
// TODO(b/77597706): this won't work for destructuring declarations
target.hasChildren()
&& varType != null
&& !var.isTypeInferred()
&& var.getNameNode() != null;
boolean isTypelessConstDecl =
isVarDeclaration
&& NodeUtil.isConstantDeclaration(
compiler.getCodingConvention(), var.getJSDocInfo(), var.getNameNode())
&& !(var.getJSDocInfo() != null && var.getJSDocInfo().hasType());
// When looking at VAR initializers for declared VARs, we tend
// to use the declared type over the type it's being
// initialized to in the global scope.
//
// For example,
// /** @param {number} */ var f = goog.abstractMethod;
// it's obvious that the programmer wants you to use
// the declared function signature, not the inferred signature.
//
// Or,
// /** @type {Object.<string>} */ var x = {};
// the one-time anonymous object on the right side
// is as narrow as it can possibly be, but we need to make
// sure we back-infer the <string> element constraint on
// the left hand side, so we use the left hand side.
boolean isVarTypeBetter = isVarDeclaration
// Makes it easier to check for NPEs.
&& !resultType.isNullType() && !resultType.isVoidType()
// Do not use the var type if the declaration looked like
// /** @const */ var x = 3;
// because this type was computed from the RHS
&& !isTypelessConstDecl;
// TODO(nicksantos): This might be a better check once we have
// back-inference of object/array constraints. It will probably
// introduce more type warnings. It uses the result type iff it's
// strictly narrower than the declared var type.
//
//boolean isVarTypeBetter = isVarDeclaration &&
// (varType.restrictByNotNullOrUndefined().isSubtype(resultType)
// || !resultType.isSubtype(varType));
if (isVarTypeBetter) {
scope = redeclareSimpleVar(scope, target, varType);
} else {
scope = redeclareSimpleVar(scope, target, resultType);
}
if (updateNode != null) {
updateNode.setJSType(resultType);
}
if (var != null
&& var.isTypeInferred()
// Don't change the typed scope to include "undefined" upon seeing "let foo;", because
// this is incompatible with how we currently handle VARs and breaks existing code.
// TODO(sdh): remove this condition after cleaning up code depending on it.
&& !(target.getParent().isLet() && !target.hasChildren())) {
JSType oldType = var.getType();
var.setType(oldType == null ? resultType : oldType.getLeastSupertype(resultType));
} else if (isTypelessConstDecl) {
// /** @const */ var x = y;
// should be redeclared, so that the type of y
// gets propagated to inner scopes.
var.setType(resultType);
}
break;
case GETPROP:
if (target.isQualifiedName()) {
String qualifiedName = target.getQualifiedName();
boolean declaredSlotType = false;
JSType rawObjType = target.getFirstChild().getJSType();
if (rawObjType != null) {
ObjectType objType = ObjectType.cast(
rawObjType.restrictByNotNullOrUndefined());
if (objType != null) {
String propName = target.getLastChild().getString();
declaredSlotType = objType.isPropertyTypeDeclared(propName);
}
}
JSType safeLeftType = targetType == null ? unknownType : targetType;
scope =
scope.inferQualifiedSlot(
target, qualifiedName, safeLeftType, resultType, declaredSlotType);
}
if (updateNode != null) {
updateNode.setJSType(resultType);
}
ensurePropertyDefined(target, resultType, scope);
break;
default:
break;
}
return scope;
}
/** Defines a property if the property has not been defined yet. */
private void ensurePropertyDefined(Node getprop, JSType rightType, FlowScope scope) {
String propName = getprop.getLastChild().getString();
Node obj = getprop.getFirstChild();
JSType nodeType = getJSType(obj);
ObjectType objectType = ObjectType.cast(
nodeType.restrictByNotNullOrUndefined());
boolean propCreationInConstructor =
obj.isThis() && getJSType(containerScope.getRootNode()).isConstructor();
if (objectType == null) {
registry.registerPropertyOnType(propName, nodeType);
} else {
if (nodeType.isStruct() && !objectType.hasProperty(propName)) {
// In general, we don't want to define a property on a struct object,
// b/c TypeCheck will later check for improper property creation on
// structs. There are two exceptions.
// 1) If it's a property created inside the constructor, on the newly
// created instance, allow it.
// 2) If it's a prototype property, allow it. For example:
// Foo.prototype.bar = baz;
// where Foo.prototype is a struct and the assignment happens at the
// top level and the constructor Foo is defined in the same file.
boolean staticPropCreation = false;
Node maybeAssignStm = getprop.getGrandparent();
if (containerScope.isGlobal() && NodeUtil.isPrototypePropertyDeclaration(maybeAssignStm)) {
String propCreationFilename = maybeAssignStm.getSourceFileName();
Node ctor = objectType.getOwnerFunction().getSource();
if (ctor != null && ctor.getSourceFileName().equals(propCreationFilename)) {
staticPropCreation = true;
}
}
if (!propCreationInConstructor && !staticPropCreation) {
return; // Early return to avoid creating the property below.
}
}
if (ensurePropertyDeclaredHelper(getprop, objectType, scope)) {
return;
}
if (!objectType.isPropertyTypeDeclared(propName)) {
// We do not want a "stray" assign to define an inferred property
// for every object of this type in the program. So we use a heuristic
// approach to determine whether to infer the property.
//
// 1) If the property is already defined, join it with the previously
// inferred type.
// 2) If this isn't an instance object, define it.
// 3) If the property of an object is being assigned in the constructor,
// define it.
// 4) If this is a stub, define it.
// 5) Otherwise, do not define the type, but declare it in the registry
// so that we can use it for missing property checks.
if (objectType.hasProperty(propName) || !objectType.isInstanceType()) {
if ("prototype".equals(propName)) {
objectType.defineDeclaredProperty(propName, rightType, getprop);
} else {
objectType.defineInferredProperty(propName, rightType, getprop);
}
} else if (propCreationInConstructor) {
objectType.defineInferredProperty(propName, rightType, getprop);
} else {
registry.registerPropertyOnType(propName, objectType);
}
}
}
}
/**
* Declares a property on its owner, if necessary.
*
* @return True if a property was declared.
*/
private boolean ensurePropertyDeclaredHelper(
Node getprop, ObjectType objectType, FlowScope scope) {
if (getprop.isQualifiedName()) {
String propName = getprop.getLastChild().getString();
String qName = getprop.getQualifiedName();
TypedVar var = getDeclaredVar(scope, qName);
if (var != null && !var.isTypeInferred()) {
// Handle normal declarations that could not be addressed earlier.
if (propName.equals("prototype")
||
// Handle prototype declarations that could not be addressed earlier.
(!objectType.hasOwnProperty(propName)
&& (!objectType.isInstanceType()
|| (var.isExtern() && !objectType.isNativeObjectType())))) {
return objectType.defineDeclaredProperty(
propName, var.getType(), getprop);
}
}
}
return false;
}
private FlowScope traverseDeclaration(Node n, FlowScope scope) {
for (Node declarationChild : n.children()) {
scope = traverseDeclarationChild(declarationChild, scope);
}
return scope;
}
private FlowScope traverseDeclarationChild(Node n, FlowScope scope) {
if (n.isName()) {
return traverseName(n, scope);
}
checkState(n.isDestructuringLhs(), n);
scope = traverse(n.getSecondChild(), scope);
return traverseDestructuringPattern(n.getFirstChild(), scope, getJSType(n.getSecondChild()));
}
/** Traverses a destructuring pattern in an assignment or declaration */
private FlowScope traverseDestructuringPattern(
Node pattern, FlowScope scope, JSType patternType) {
checkArgument(pattern.isDestructuringPattern(), pattern);
checkNotNull(patternType);
for (Node key : pattern.children()) {
DestructuredTarget target = DestructuredTarget.createTarget(registry, patternType, key);
// The computed property is always evaluated first.
if (target.hasComputedProperty()) {
scope = traverse(target.getComputedProperty().getFirstChild(), scope);
}
Node targetNode = target.getNode();
if (targetNode.isDestructuringPattern()) {
if (target.hasDefaultValue()) {
traverse(target.getDefaultValue(), scope);
}
// traverse into nested patterns
JSType targetType = target.inferType();
targetType = targetType != null ? targetType : getNativeType(UNKNOWN_TYPE);
scope = traverseDestructuringPattern(targetNode, scope, targetType);
} else {
scope = traverse(targetNode, scope);
if (target.hasDefaultValue()) {
// TODO(lharker): what do we do with the inferred slots in the scope?
// throw them away or join them with the previous scope?
traverse(target.getDefaultValue(), scope);
}
// declare in the scope
JSType targetType = target.inferType();
targetType = targetType != null ? targetType : getNativeType(UNKNOWN_TYPE);
scope = updateScopeForAssignment(scope, targetNode, targetNode.getJSType(), targetType);
}
}
// put the `inferred type` of a pattern on it, to make it easier to do typechecking
pattern.setJSType(patternType);
return scope;
}
private FlowScope traverseName(Node n, FlowScope scope) {
String varName = n.getString();
Node value = n.getFirstChild();
JSType type = n.getJSType();
if (value != null) {
scope = traverse(value, scope);
return updateScopeForAssignment(
scope, n, n.getJSType() /* could be null */, getJSType(value));
} else if (n.getParent().isLet()) {
// Whenever we see a LET, we're guaranteed it's not yet in the scope, and we don't need to
// worry about it being from an outer scope. In this case, it has no child, so the actual
// type should be undefined, but we make a special allowance for type-annotated variables.
// In that case, we use the annotated type instead.
// TODO(sdh): I would have thought that #updateScopeForTypeChange would handle using the
// declared type correctly, but for some reason it doesn't so we handle it here.
JSType resultType = type != null ? type : getNativeType(VOID_TYPE);
scope = updateScopeForAssignment(scope, n, type, resultType);
type = resultType;
} else {
StaticTypedSlot var = scope.getSlot(varName);
if (var != null) {
// There are two situations where we don't want to use type information
// from the scope, even if we have it.
// 1) The var is escaped and assigned in an inner scope, e.g.,
// function f() { var x = 3; function g() { x = null } (x); }
boolean isInferred = var.isTypeInferred();
boolean unflowable = isInferred && isUnflowable(getDeclaredVar(scope, varName));
// 2) We're reading type information from another scope for an
// inferred variable. That variable is assigned more than once,
// and we can't know which type we're getting.
//
// var t = null; function f() { (t); } doStuff(); t = {};
//
// Notice that this heuristic isn't perfect. For example, you might
// have:
//
// function f() { (t); } f(); var t = 3;
//
// In this case, we would infer the first reference to t as
// type {number}, even though it's undefined.
TypedVar maybeOuterVar =
isInferred && containerScope.isLocal()
? containerScope.getParent().getVar(varName)
: null;
boolean nonLocalInferredSlot =
var.equals(maybeOuterVar) && !maybeOuterVar.isMarkedAssignedExactlyOnce();
if (!unflowable && !nonLocalInferredSlot) {
type = var.getType();
if (type == null) {
type = unknownType;
}
}
}
}
n.setJSType(type);
return scope;
}
private FlowScope traverseClass(Node n, FlowScope scope) {
// The name already has a type applied (from TypedScopeCreator) if it's non-empty, and the
// members are traversed in the class scope (and in their own function scopes). But the extends
// clause and computed property keys are in the outer scope and must be traversed here.
scope = traverse(n.getSecondChild(), scope);
Node classMembers = NodeUtil.getClassMembers(n);
for (Node member = classMembers.getFirstChild(); member != null; member = member.getNext()) {
if (member.isComputedProp()) {
scope = traverse(member.getFirstChild(), scope);
}
}
return scope;
}
/** Traverse each element of the array. */
private FlowScope traverseArrayLiteral(Node n, FlowScope scope) {
scope = traverseChildren(n, scope);
n.setJSType(getNativeType(ARRAY_TYPE));
return scope;
}
private FlowScope traverseObjectLiteral(Node n, FlowScope scope) {
JSType type = n.getJSType();
checkNotNull(type);
for (Node name = n.getFirstChild(); name != null; name = name.getNext()) {
scope = traverseChildren(name, scope);
}
// Object literals can be reflected on other types.
// See CodingConvention#getObjectLiteralCast and goog.reflect.object
// Ignore these types of literals.
ObjectType objectType = ObjectType.cast(type);
if (objectType == null
|| n.getBooleanProp(Node.REFLECTED_OBJECT)
|| objectType.isEnumType()) {
return scope;
}
String qObjName = NodeUtil.getBestLValueName(
NodeUtil.getBestLValue(n));
for (Node name = n.getFirstChild(); name != null;
name = name.getNext()) {
if (name.isComputedProp()) {
// Don't define computed properties as inferred properties on the object
continue;
}
String memberName = NodeUtil.getObjectLitKeyName(name);
if (memberName != null) {
JSType rawValueType = name.getFirstChild().getJSType();
JSType valueType =
TypeCheck.getObjectLitKeyTypeFromValueType(name, rawValueType);
if (valueType == null) {
valueType = unknownType;
}
objectType.defineInferredProperty(memberName, valueType, name);
// Do normal flow inference if this is a direct property assignment.
if (qObjName != null && name.isStringKey()) {
String qKeyName = qObjName + "." + memberName;
TypedVar var = getDeclaredVar(scope, qKeyName);
JSType oldType = var == null ? null : var.getType();
if (var != null && var.isTypeInferred()) {
var.setType(oldType == null ? valueType : oldType.getLeastSupertype(oldType));
}
scope =
scope.inferQualifiedSlot(
name, qKeyName, oldType == null ? unknownType : oldType, valueType, false);
}
} else {
n.setJSType(unknownType);
}
}
return scope;
}
private FlowScope traverseAdd(Node n, FlowScope scope) {
Node left = n.getFirstChild();
Node right = left.getNext();
scope = traverseChildren(n, scope);
JSType leftType = left.getJSType();
JSType rightType = right.getJSType();
JSType type = unknownType;
if (leftType != null && rightType != null) {
boolean leftIsUnknown = leftType.isUnknownType();
boolean rightIsUnknown = rightType.isUnknownType();
if (leftIsUnknown && rightIsUnknown) {
type = unknownType;
} else if ((!leftIsUnknown && leftType.isString())
|| (!rightIsUnknown && rightType.isString())) {
type = getNativeType(STRING_TYPE);
} else if (leftIsUnknown || rightIsUnknown) {
type = unknownType;
} else if (isAddedAsNumber(leftType) && isAddedAsNumber(rightType)) {
type = getNativeType(NUMBER_TYPE);
} else {
type = registry.createUnionType(STRING_TYPE, NUMBER_TYPE);
}
}
n.setJSType(type);
if (n.isAssignAdd()) {
// TODO(johnlenz): this should not update the type of the lhs as that is use as a
// input and need to be preserved for type checking.
// Instead call this overload `updateScopeForAssignment(scope, left, leftType, type, null);`
scope = updateScopeForAssignment(scope, left, leftType, type);
}
return scope;
}
private boolean isAddedAsNumber(JSType type) {
return type.isSubtypeOf(registry.createUnionType(VOID_TYPE, NULL_TYPE,
NUMBER_VALUE_OR_OBJECT_TYPE, BOOLEAN_TYPE, BOOLEAN_OBJECT_TYPE));
}
private FlowScope traverseHook(Node n, FlowScope scope) {
Node condition = n.getFirstChild();
Node trueNode = condition.getNext();
Node falseNode = n.getLastChild();
// verify the condition
scope = traverse(condition, scope);
// reverse abstract interpret the condition to produce two new scopes
FlowScope trueScope = reverseInterpreter.
getPreciserScopeKnowingConditionOutcome(
condition, scope, true);
FlowScope falseScope = reverseInterpreter.
getPreciserScopeKnowingConditionOutcome(
condition, scope, false);
// traverse the true node with the trueScope
traverse(trueNode, trueScope);
// traverse the false node with the falseScope
traverse(falseNode, falseScope);
// meet true and false nodes' types and assign
JSType trueType = trueNode.getJSType();
JSType falseType = falseNode.getJSType();
if (trueType != null && falseType != null) {
n.setJSType(trueType.getLeastSupertype(falseType));
} else {
n.setJSType(null);
}
return scope;
}
/** @param n A non-constructor function invocation, i.e. CALL or TAGGED_TEMPLATELIT */
private FlowScope traverseFunctionInvocation(Node n, FlowScope scope) {
checkArgument(n.isCall() || n.isTaggedTemplateLit(), n);
scope = traverseChildren(n, scope);
Node left = n.getFirstChild();
JSType functionType = getJSType(left).restrictByNotNullOrUndefined();
if (left.isSuper()) {
// TODO(sdh): This will probably return the super type; might want to return 'this' instead?
return traverseInstantiation(n, functionType, scope);
} else if (functionType.isFunctionType()) {
FunctionType fnType = functionType.toMaybeFunctionType();
n.setJSType(fnType.getReturnType());
backwardsInferenceFromCallSite(n, fnType, scope);
} else if (functionType.isEquivalentTo(getNativeType(CHECKED_UNKNOWN_TYPE))) {
n.setJSType(getNativeType(CHECKED_UNKNOWN_TYPE));
} else if (left.getJSType() != null && left.getJSType().isUnknownType()) {
// TODO(lharker): do we also want to set this to unknown if the left's type is null? We would
// lose some inference that TypeCheck does when given a null type.
n.setJSType(getNativeType(UNKNOWN_TYPE));
}
return scope;
}
private FlowScope tightenTypesAfterAssertions(FlowScope scope, Node callNode) {
Node left = callNode.getFirstChild();
Node firstParam = left.getNext();
AssertionFunctionSpec assertionFunctionSpec =
assertionFunctionsMap.get(left.getQualifiedName());
if (assertionFunctionSpec == null || firstParam == null) {
return scope;
}
Node assertedNode = assertionFunctionSpec.getAssertedParam(firstParam);
if (assertedNode == null) {
return scope;
}
JSType assertedType = assertionFunctionSpec.getAssertedOldType(
callNode, registry);
String assertedNodeName = assertedNode.getQualifiedName();
JSType narrowed;
// Handle assertions that enforce expressions evaluate to true.
if (assertedType == null) {
// Handle arbitrary expressions within the assert.
scope = reverseInterpreter.getPreciserScopeKnowingConditionOutcome(
assertedNode, scope, true);
// Build the result of the assertExpression
narrowed = getJSType(assertedNode).restrictByNotNullOrUndefined();
} else {
// Handle assertions that enforce expressions are of a certain type.
JSType type = getJSType(assertedNode);
if (assertedType.isUnknownType() || type.isUnknownType()) {
narrowed = assertedType;
} else {
narrowed = type.getGreatestSubtype(assertedType);
}
if (assertedNodeName != null && type.differsFrom(narrowed)) {
scope = narrowScope(scope, assertedNode, narrowed);
}
}
callNode.setJSType(narrowed);
return scope;
}
private FlowScope narrowScope(FlowScope scope, Node node, JSType narrowed) {
if (node.isThis()) {
// "this" references don't need to be modeled in the control flow graph.
return scope;
}
if (node.isGetProp()) {
return scope.inferQualifiedSlot(
node, node.getQualifiedName(), getJSType(node), narrowed, false);
}
return redeclareSimpleVar(scope, node, narrowed);
}
/**
* We only do forward type inference. We do not do full backwards type inference.
*
* In other words, if we have,
* <code>
* var x = f();
* g(x);
* </code>
* a forward type-inference engine would try to figure out the type
* of "x" from the return type of "f". A backwards type-inference engine
* would try to figure out the type of "x" from the parameter type of "g".
*
* <p>However, there are a few special syntactic forms where we do some some half-assed backwards
* type-inference, because programmers expect it in this day and age. To take an example from
* Java,
* <code>
* List<String> x = Lists.newArrayList();
* </code>
* The Java compiler will be able to infer the generic type of the List returned by
* newArrayList().
*
* <p>In much the same way, we do some special-case backwards inference for JS. Those cases are
* enumerated here.
*/
private void backwardsInferenceFromCallSite(Node n, FunctionType fnType, FlowScope scope) {
boolean updatedFnType = inferTemplatedTypesForCall(n, fnType, scope);
if (updatedFnType) {
fnType = n.getFirstChild().getJSType().toMaybeFunctionType();
}
updateTypeOfArguments(n, fnType);
updateBind(n);
}
/**
* When "bind" is called on a function, we infer the type of the returned
* "bound" function by looking at the number of parameters in the call site.
* We also infer the "this" type of the target, if it's a function expression.
*/
private void updateBind(Node n) {
CodingConvention.Bind bind =
compiler.getCodingConvention().describeFunctionBind(n, false, true);
if (bind == null) {
return;
}
Node target = bind.target;
FunctionType callTargetFn = getJSType(target)
.restrictByNotNullOrUndefined().toMaybeFunctionType();
if (callTargetFn == null) {
return;
}
if (bind.thisValue != null && target.isFunction()) {
JSType thisType = getJSType(bind.thisValue);
if (thisType.toObjectType() != null && !thisType.isUnknownType()
&& callTargetFn.getTypeOfThis().isUnknownType()) {
callTargetFn = new FunctionBuilder(registry)
.copyFromOtherFunction(callTargetFn)
.withTypeOfThis(thisType.toObjectType())
.build();
target.setJSType(callTargetFn);
}
}
n.setJSType(
callTargetFn.getBindReturnType(
// getBindReturnType expects the 'this' argument to be included.
bind.getBoundParameterCount() + 1));
}
/**
* For functions with function parameters, type inference will set the type of a function literal
* argument from the function parameter type.
*/
private void updateTypeOfArguments(Node n, FunctionType fnType) {
checkState(NodeUtil.isInvocation(n), n);
Iterator<Node> parameters = fnType.getParameters().iterator();
if (n.isTaggedTemplateLit()) {
// Skip the first parameter because it corresponds to a constructed array of the template lit
// subs, not an actual AST node, so there's nothing to update.
if (!parameters.hasNext()) {
// TypeCheck will warn if there is no first parameter. Just bail out here.
return;
}
parameters.next();
}
Iterator<Node> arguments = NodeUtil.getInvocationArgsAsIterable(n).iterator();
Node iParameter;
Node iArgument;
// Note: if there are too many or too few arguments, TypeCheck will warn.
while (parameters.hasNext() && arguments.hasNext()) {
iArgument = arguments.next();
JSType iArgumentType = getJSType(iArgument);
iParameter = parameters.next();
JSType iParameterType = getJSType(iParameter);
inferPropertyTypesToMatchConstraint(iArgumentType, iParameterType);
// If the parameter to the call is a function expression, propagate the
// function signature from the call site to the function node.
// Filter out non-function types (such as null and undefined) as
// we only care about FUNCTION subtypes here.
FunctionType restrictedParameter = null;
if (iParameterType.isUnionType()) {
UnionType union = iParameterType.toMaybeUnionType();
for (JSType alternative : union.getAlternates()) {
if (alternative.isFunctionType()) {
// There is only one function type per union.
restrictedParameter = alternative.toMaybeFunctionType();
break;
}
}
} else {
restrictedParameter = iParameterType.toMaybeFunctionType();
}
if (restrictedParameter != null
&& iArgument.isFunction()
&& iArgumentType.isFunctionType()) {
FunctionType argFnType = iArgumentType.toMaybeFunctionType();
JSDocInfo argJsdoc = iArgument.getJSDocInfo();
boolean declared = argJsdoc != null && argJsdoc.containsDeclaration();
iArgument.setJSType(matchFunction(restrictedParameter, argFnType, declared));
}
}
}
/**
* Take the current function type, and try to match the expected function
* type. This is a form of backwards-inference, like record-type constraint
* matching.
*/
private FunctionType matchFunction(
FunctionType expectedType, FunctionType currentType, boolean declared) {
if (declared) {
// If the function was declared but it doesn't have a known "this"
// but the expected type does, back fill it.
if (currentType.getTypeOfThis().isUnknownType()
&& !expectedType.getTypeOfThis().isUnknownType()) {
FunctionType replacement = new FunctionBuilder(registry)
.copyFromOtherFunction(currentType)
.withTypeOfThis(expectedType.getTypeOfThis())
.build();
return replacement;
}
} else {
// For now, we just make sure the current type has enough
// arguments to match the expected type, and return the
// expected type if it does.
if (currentType.getMaxArity() <= expectedType.getMaxArity()) {
return expectedType;
}
}
return currentType;
}
/** @param call A CALL, NEW, or TAGGED_TEMPLATELIT node */
private Map<TemplateType, JSType> inferTemplateTypesFromParameters(
FunctionType fnType, Node call) {
if (fnType.getTemplateTypeMap().getTemplateKeys().isEmpty()) {
return Collections.emptyMap();
}
Map<TemplateType, JSType> resolvedTypes = Maps.newIdentityHashMap();
Set<JSType> seenTypes = Sets.newIdentityHashSet();
Node callTarget = call.getFirstChild();
if (NodeUtil.isGet(callTarget)) {
Node obj = callTarget.getFirstChild();
maybeResolveTemplatedType(
fnType.getTypeOfThis(),
getJSType(obj).restrictByNotNullOrUndefined(),
resolvedTypes,
seenTypes);
}
if (call.isTaggedTemplateLit()) {
Iterator<Node> fnParameters = fnType.getParameters().iterator();
if (!fnParameters.hasNext()) {
// TypeCheck will warn if there are too few function parameters
return resolvedTypes;
}
// The first argument to the tag function is an array of strings (typed as ITemplateArray)
// but not an actual AST node
maybeResolveTemplatedType(
fnParameters.next().getJSType(),
getNativeType(I_TEMPLATE_ARRAY_TYPE),
resolvedTypes,
seenTypes);
// Resolve the remaining template types from the template literal substitutions.
maybeResolveTemplateTypeFromNodes(
Iterables.skip(fnType.getParameters(), 1),
NodeUtil.getInvocationArgsAsIterable(call),
resolvedTypes,
seenTypes);
} else if (call.hasMoreThanOneChild()) {
maybeResolveTemplateTypeFromNodes(
fnType.getParameters(),
NodeUtil.getInvocationArgsAsIterable(call),
resolvedTypes,
seenTypes);
}
return resolvedTypes;
}
private void maybeResolveTemplatedType(
JSType paramType,
JSType argType,
Map<TemplateType, JSType> resolvedTypes, Set<JSType> seenTypes) {
if (paramType.isTemplateType()) {
// example: @param {T}
resolvedTemplateType(
resolvedTypes, paramType.toMaybeTemplateType(), argType);
} else if (paramType.isUnionType()) {
// example: @param {Array.<T>|NodeList|Arguments|{length:number}}
UnionType unionType = paramType.toMaybeUnionType();
for (JSType alernative : unionType.getAlternates()) {
maybeResolveTemplatedType(alernative, argType, resolvedTypes, seenTypes);
}
} else if (paramType.isFunctionType()) {
FunctionType paramFunctionType = paramType.toMaybeFunctionType();
FunctionType argFunctionType = argType
.restrictByNotNullOrUndefined()
.collapseUnion()
.toMaybeFunctionType();
if (argFunctionType != null && argFunctionType.isSubtype(paramType)) {
// infer from return type of the function type
maybeResolveTemplatedType(
paramFunctionType.getTypeOfThis(),
argFunctionType.getTypeOfThis(), resolvedTypes, seenTypes);
// infer from return type of the function type
maybeResolveTemplatedType(
paramFunctionType.getReturnType(),
argFunctionType.getReturnType(), resolvedTypes, seenTypes);
// infer from parameter types of the function type
maybeResolveTemplateTypeFromNodes(
paramFunctionType.getParameters(),
argFunctionType.getParameters(), resolvedTypes, seenTypes);
}
} else if (paramType.isRecordType() && !paramType.isNominalType()) {
// example: @param {{foo:T}}
if (seenTypes.add(paramType)) {
ObjectType paramRecordType = paramType.toObjectType();
ObjectType argObjectType = argType.restrictByNotNullOrUndefined().toObjectType();
if (argObjectType != null && !argObjectType.isUnknownType()
&& !argObjectType.isEmptyType()) {
Set<String> names = paramRecordType.getPropertyNames();
for (String name : names) {
if (paramRecordType.hasOwnProperty(name) && argObjectType.hasProperty(name)) {
maybeResolveTemplatedType(paramRecordType.getPropertyType(name),
argObjectType.getPropertyType(name), resolvedTypes, seenTypes);
}
}
}
seenTypes.remove(paramType);
}
} else if (paramType.isTemplatizedType()) {
// example: @param {Array<T>}
TemplatizedType templatizedParamType = paramType.toMaybeTemplatizedType();
int keyCount = templatizedParamType.getTemplateTypes().size();
// TODO(johnlenz): determine why we are creating TemplatizedTypes for
// types with no type arguments.
if (keyCount > 0) {
ObjectType referencedParamType = templatizedParamType.getReferencedType();
JSType argObjectType = argType
.restrictByNotNullOrUndefined()
.collapseUnion();
if (argObjectType.isSubtypeOf(referencedParamType)) {
// If the argument type is a subtype of the parameter type, resolve any
// template types amongst their templatized types.
TemplateTypeMap paramTypeMap = paramType.getTemplateTypeMap();
ImmutableList<TemplateType> keys = paramTypeMap.getTemplateKeys();
TemplateTypeMap argTypeMap = argObjectType.getTemplateTypeMap();
for (int index = keys.size() - keyCount; index < keys.size(); index++) {
TemplateType key = keys.get(index);
maybeResolveTemplatedType(
paramTypeMap.getResolvedTemplateType(key),
argTypeMap.getResolvedTemplateType(key),
resolvedTypes, seenTypes);
}
}
}
}
}
private void maybeResolveTemplateTypeFromNodes(
Iterable<Node> declParams,
Iterable<Node> callParams,
Map<TemplateType, JSType> resolvedTypes, Set<JSType> seenTypes) {
maybeResolveTemplateTypeFromNodes(
declParams.iterator(), callParams.iterator(), resolvedTypes, seenTypes);
}
private void maybeResolveTemplateTypeFromNodes(
Iterator<Node> declParams,
Iterator<Node> callParams,
Map<TemplateType, JSType> resolvedTypes,
Set<JSType> seenTypes) {
while (declParams.hasNext() && callParams.hasNext()) {
Node declParam = declParams.next();
maybeResolveTemplatedType(
getJSType(declParam),
getJSType(callParams.next()),
resolvedTypes, seenTypes);
if (declParam.isVarArgs()) {
while (callParams.hasNext()) {
maybeResolveTemplatedType(
getJSType(declParam),
getJSType(callParams.next()),
resolvedTypes, seenTypes);
}
}
}
}
private static void resolvedTemplateType(
Map<TemplateType, JSType> map, TemplateType template, JSType resolved) {
JSType previous = map.get(template);
if (!resolved.isUnknownType()) {
if (previous == null) {
map.put(template, resolved);
} else {
JSType join = previous.getLeastSupertype(resolved);
map.put(template, join);
}
}
}
private static class TemplateTypeReplacer extends ModificationVisitor {
private final Map<TemplateType, JSType> replacements;
private final JSTypeRegistry registry;
boolean madeChanges = false;
TemplateTypeReplacer(
JSTypeRegistry registry, Map<TemplateType, JSType> replacements) {
super(registry, true);
this.registry = registry;
this.replacements = replacements;
}
@Override
public JSType caseTemplateType(TemplateType type) {
madeChanges = true;
JSType replacement = replacements.get(type);
return replacement != null ? replacement : registry.getNativeType(UNKNOWN_TYPE);
}
}
/**
* Build the type environment where type transformations will be evaluated.
* It only considers the template type variables that do not have a type
* transformation.
*/
private Map<String, JSType> buildTypeVariables(
Map<TemplateType, JSType> inferredTypes) {
Map<String, JSType> typeVars = new LinkedHashMap<>();
for (Entry<TemplateType, JSType> e : inferredTypes.entrySet()) {
// Only add the template type that do not have a type transformation
if (!e.getKey().isTypeTransformation()) {
typeVars.put(e.getKey().getReferenceName(), e.getValue());
}
}
return typeVars;
}
/** This function will evaluate the type transformations associated to the template types */
private Map<TemplateType, JSType> evaluateTypeTransformations(
ImmutableList<TemplateType> templateTypes,
Map<TemplateType, JSType> inferredTypes,
FlowScope scope) {
Map<String, JSType> typeVars = null;
Map<TemplateType, JSType> result = null;
TypeTransformation ttlObj = null;
for (TemplateType type : templateTypes) {
if (type.isTypeTransformation()) {
// Lazy initialization when the first type transformation is found
if (ttlObj == null) {
ttlObj = new TypeTransformation(compiler, scope.getDeclarationScope());
typeVars = buildTypeVariables(inferredTypes);
result = new LinkedHashMap<>();
}
// Evaluate the type transformation expression using the current
// known types for the template type variables
JSType transformedType = ttlObj.eval(
type.getTypeTransformation(),
ImmutableMap.copyOf(typeVars));
result.put(type, transformedType);
// Add the transformed type to the type variables
typeVars.put(type.getReferenceName(), transformedType);
}
}
return result;
}
/**
* For functions that use template types, specialize the function type for the call target based
* on the call-site specific arguments. Specifically, this enables inference to set the type of
* any function literal parameters based on these inferred types.
*/
private boolean inferTemplatedTypesForCall(Node n, FunctionType fnType, FlowScope scope) {
ImmutableList<TemplateType> keys = fnType.getTemplateTypeMap().getTemplateKeys();
if (keys.isEmpty()) {
return false;
}
// Try to infer the template types
Map<TemplateType, JSType> rawInferrence = inferTemplateTypesFromParameters(fnType, n);
Map<TemplateType, JSType> inferred = Maps.newIdentityHashMap();
for (TemplateType key : keys) {
JSType type = rawInferrence.get(key);
if (type == null) {
type = unknownType;
}
inferred.put(key, type);
}
// Try to infer the template types using the type transformations
Map<TemplateType, JSType> typeTransformations =
evaluateTypeTransformations(keys, inferred, scope);
if (typeTransformations != null) {
inferred.putAll(typeTransformations);
}
// Replace all template types. If we couldn't find a replacement, we
// replace it with UNKNOWN.
TemplateTypeReplacer replacer = new TemplateTypeReplacer(registry, inferred);
Node callTarget = n.getFirstChild();
FunctionType replacementFnType = fnType.visit(replacer).toMaybeFunctionType();
checkNotNull(replacementFnType);
callTarget.setJSType(replacementFnType);
n.setJSType(replacementFnType.getReturnType());
return replacer.madeChanges;
}
private FlowScope traverseNew(Node n, FlowScope scope) {
scope = traverseChildren(n, scope);
Node constructor = n.getFirstChild();
JSType constructorType = constructor.getJSType();
return traverseInstantiation(n, constructorType, scope);
}
private FlowScope traverseInstantiation(Node n, JSType constructorType, FlowScope scope) {
JSType type = null;
if (constructorType != null) {
constructorType = constructorType.restrictByNotNullOrUndefined();
if (constructorType.isUnknownType()) {
type = unknownType;
} else {
FunctionType ct = constructorType.toMaybeFunctionType();
if (ct == null && constructorType instanceof FunctionType) {
// If constructorType is a NoObjectType, then toMaybeFunctionType will
// return null. But NoObjectType implements the FunctionType
// interface, precisely because it can validly construct objects.
ct = (FunctionType) constructorType;
}
if (ct != null && ct.isConstructor()) {
backwardsInferenceFromCallSite(n, ct, scope);
// If necessary, create a TemplatizedType wrapper around the instance
// type, based on the types of the constructor parameters.
ObjectType instanceType = ct.getInstanceType();
Map<TemplateType, JSType> inferredTypes =
inferTemplateTypesFromParameters(ct, n);
if (inferredTypes.isEmpty()) {
type = instanceType;
} else {
type = registry.createTemplatizedType(instanceType, inferredTypes);
}
}
}
}
n.setJSType(type);
return scope;
}
private BooleanOutcomePair traverseAnd(Node n, FlowScope scope) {
return traverseShortCircuitingBinOp(n, scope);
}
private FlowScope traverseChildren(Node n, FlowScope scope) {
for (Node el = n.getFirstChild(); el != null; el = el.getNext()) {
scope = traverse(el, scope);
}
return scope;
}
private FlowScope traverseGetElem(Node n, FlowScope scope) {
scope = traverseChildren(n, scope);
Node indexKey = n.getLastChild();
JSType indexType = getJSType(indexKey);
if (indexType.isSymbolValueType()) {
// For now, allow symbols definitions/access on any type. In the future only allow them
// on the subtypes for which they are defined.
// TODO(b/77474174): Type well known symbol accesses.
n.setJSType(unknownType);
} else {
JSType type = getJSType(n.getFirstChild()).restrictByNotNullOrUndefined();
TemplateTypeMap typeMap = type.getTemplateTypeMap();
if (typeMap.hasTemplateType(registry.getObjectElementKey())) {
n.setJSType(typeMap.getResolvedTemplateType(registry.getObjectElementKey()));
}
}
return tightenTypeAfterDereference(n.getFirstChild(), scope);
}
private FlowScope traverseGetProp(Node n, FlowScope scope) {
Node objNode = n.getFirstChild();
Node property = n.getLastChild();
scope = traverseChildren(n, scope);
n.setJSType(
getPropertyType(
objNode.getJSType(), property.getString(), n, scope));
return tightenTypeAfterDereference(n.getFirstChild(), scope);
}
/**
* Suppose X is an object with inferred properties.
* Suppose also that X is used in a way where it would only type-check
* correctly if some of those properties are widened.
* Then we should be polite and automatically widen X's properties.
*
* For a concrete example, consider:
* param x {{prop: (number|undefined)}}
* function f(x) {}
* f({});
*
* If we give the anonymous object an inferred property of (number|undefined),
* then this code will type-check appropriately.
*/
private static void inferPropertyTypesToMatchConstraint(
JSType type, JSType constraint) {
if (type == null || constraint == null) {
return;
}
type.matchConstraint(constraint);
}
/**
* If we access a property of a symbol, then that symbol is not
* null or undefined.
*/
private FlowScope tightenTypeAfterDereference(Node n, FlowScope scope) {
if (n.isQualifiedName()) {
JSType type = getJSType(n);
JSType narrowed = type.restrictByNotNullOrUndefined();
if (!type.equals(narrowed)) {
scope = narrowScope(scope, n, narrowed);
}
}
return scope;
}
private JSType getPropertyType(JSType objType, String propName,
Node n, FlowScope scope) {
// We often have a couple of different types to choose from for the
// property. Ordered by accuracy, we have
// 1) A locally inferred qualified name (which is in the FlowScope)
// 2) A globally declared qualified name (which is in the FlowScope)
// 3) A property on the owner type (which is on objType)
// 4) A name in the type registry (as a last resort)
JSType propertyType = null;
boolean isLocallyInferred = false;
// Scopes sometimes contain inferred type info about qualified names.
String qualifiedName = n.getQualifiedName();
StaticTypedSlot var = qualifiedName != null ? scope.getSlot(qualifiedName) : null;
if (var != null) {
JSType varType = var.getType();
if (varType != null) {
boolean isDeclared = !var.isTypeInferred();
isLocallyInferred = (var != getDeclaredVar(scope, qualifiedName));
if (isDeclared || isLocallyInferred) {
propertyType = varType;
}
}
}
if (propertyType == null && objType != null) {
JSType foundType = objType.findPropertyType(propName);
if (foundType != null) {
propertyType = foundType;
}
}
if (propertyType != null && objType != null) {
JSType restrictedObjType = objType.restrictByNotNullOrUndefined();
if (!restrictedObjType.getTemplateTypeMap().isEmpty()
&& propertyType.hasAnyTemplateTypes()) {
TemplateTypeMap typeMap = restrictedObjType.getTemplateTypeMap();
TemplateTypeMapReplacer replacer = new TemplateTypeMapReplacer(
registry, typeMap);
propertyType = propertyType.visit(replacer);
}
}
if ((propertyType == null || propertyType.isUnknownType())
&& qualifiedName != null) {
// If we find this node in the registry, then we can infer its type.
ObjectType regType = ObjectType.cast(
registry.getType(scope.getDeclarationScope(), qualifiedName));
if (regType != null) {
propertyType = regType.getConstructor();
}
}
if (propertyType == null) {
return unknownType;
} else if (propertyType.isEquivalentTo(unknownType) && isLocallyInferred) {
// If the type has been checked in this scope,
// then use CHECKED_UNKNOWN_TYPE instead to indicate that.
return getNativeType(CHECKED_UNKNOWN_TYPE);
} else {
return propertyType;
}
}
private BooleanOutcomePair traverseOr(Node n, FlowScope scope) {
return traverseShortCircuitingBinOp(n, scope);
}
private BooleanOutcomePair traverseShortCircuitingBinOp(
Node n, FlowScope scope) {
checkArgument(n.isAnd() || n.isOr());
boolean nIsAnd = n.isAnd();
Node left = n.getFirstChild();
Node right = n.getLastChild();
// type the left node
BooleanOutcomePair leftOutcome = traverseWithinShortCircuitingBinOp(left, scope);
JSType leftType = left.getJSType();
// reverse abstract interpret the left node to produce the correct
// scope in which to verify the right node
FlowScope rightScope =
reverseInterpreter.getPreciserScopeKnowingConditionOutcome(
left, leftOutcome.getOutcomeFlowScope(left.getToken(), nIsAnd), nIsAnd);
// type the right node
BooleanOutcomePair rightOutcome = traverseWithinShortCircuitingBinOp(right, rightScope);
JSType rightType = right.getJSType();
JSType type;
BooleanOutcomePair outcome;
if (leftType != null && rightType != null) {
leftType = leftType.getRestrictedTypeGivenToBooleanOutcome(!nIsAnd);
if (leftOutcome.toBooleanOutcomes == BooleanLiteralSet.get(!nIsAnd)) {
// Either n is && and lhs is false, or n is || and lhs is true.
// Use the restricted left type; the right side never gets evaluated.
type = leftType;
outcome = leftOutcome;
} else {
// Use the join of the restricted left type knowing the outcome of the
// ToBoolean predicate and of the right type.
type = leftType.getLeastSupertype(rightType);
outcome = new BooleanOutcomePair(
joinBooleanOutcomes(nIsAnd,
leftOutcome.toBooleanOutcomes, rightOutcome.toBooleanOutcomes),
joinBooleanOutcomes(nIsAnd,
leftOutcome.booleanValues, rightOutcome.booleanValues),
leftOutcome.getJoinedFlowScope(),
rightOutcome.getJoinedFlowScope());
}
// Exclude the boolean type if the literal set is empty because a boolean
// can never actually be returned.
if (outcome.booleanValues == BooleanLiteralSet.EMPTY
&& getNativeType(BOOLEAN_TYPE).isSubtypeOf(type)) {
// Exclusion only makes sense for a union type.
if (type.isUnionType()) {
type = type.toMaybeUnionType().getRestrictedUnion(
getNativeType(BOOLEAN_TYPE));
}
}
} else {
type = null;
outcome = new BooleanOutcomePair(
BooleanLiteralSet.BOTH, BooleanLiteralSet.BOTH,
leftOutcome.getJoinedFlowScope(),
rightOutcome.getJoinedFlowScope());
}
n.setJSType(type);
return outcome;
}
private BooleanOutcomePair traverseWithinShortCircuitingBinOp(
Node n, FlowScope scope) {
switch (n.getToken()) {
case AND:
return traverseAnd(n, scope);
case OR:
return traverseOr(n, scope);
default:
scope = traverse(n, scope);
return newBooleanOutcomePair(n.getJSType(), scope);
}
}
private FlowScope traverseAwait(Node await, FlowScope scope) {
scope = traverseChildren(await, scope);
Node expr = await.getFirstChild();
JSType exprType = getJSType(expr);
await.setJSType(Promises.getResolvedType(registry, exprType));
return scope;
}
private static BooleanLiteralSet joinBooleanOutcomes(
boolean isAnd, BooleanLiteralSet left, BooleanLiteralSet right) {
// A truthy value on the lhs of an {@code &&} can never make it to the
// result. Same for a falsy value on the lhs of an {@code ||}.
// Hence the intersection.
return right.union(left.intersection(BooleanLiteralSet.get(!isAnd)));
}
/**
* When traversing short-circuiting binary operations, we need to keep track
* of two sets of boolean literals:
* 1. {@code toBooleanOutcomes}: boolean literals as converted from any types,
* 2. {@code booleanValues}: boolean literals from just boolean types.
*/
private final class BooleanOutcomePair {
final BooleanLiteralSet toBooleanOutcomes;
final BooleanLiteralSet booleanValues;
// The scope if only half of the expression executed, when applicable.
final FlowScope leftScope;
// The scope when the whole expression executed.
final FlowScope rightScope;
// The scope when we don't know how much of the expression is executed.
FlowScope joinedScope = null;
BooleanOutcomePair(
BooleanLiteralSet toBooleanOutcomes, BooleanLiteralSet booleanValues,
FlowScope leftScope, FlowScope rightScope) {
this.toBooleanOutcomes = toBooleanOutcomes;
this.booleanValues = booleanValues;
this.leftScope = leftScope;
this.rightScope = rightScope;
}
/**
* Gets the safe estimated scope without knowing if all of the
* subexpressions will be evaluated.
*/
FlowScope getJoinedFlowScope() {
if (joinedScope == null) {
if (leftScope == rightScope) {
joinedScope = rightScope;
} else {
joinedScope = join(leftScope, rightScope);
}
}
return joinedScope;
}
/**
* Gets the outcome scope if we do know the outcome of the entire
* expression.
*/
FlowScope getOutcomeFlowScope(Token nodeType, boolean outcome) {
if ((nodeType == Token.AND && outcome) || (nodeType == Token.OR && !outcome)) {
// We know that the whole expression must have executed.
return rightScope;
} else {
return getJoinedFlowScope();
}
}
}
private BooleanOutcomePair newBooleanOutcomePair(
JSType jsType, FlowScope flowScope) {
if (jsType == null) {
return new BooleanOutcomePair(
BooleanLiteralSet.BOTH, BooleanLiteralSet.BOTH, flowScope, flowScope);
}
return new BooleanOutcomePair(
jsType.getPossibleToBooleanOutcomes(),
registry.getNativeType(BOOLEAN_TYPE).isSubtypeOf(jsType)
? BooleanLiteralSet.BOTH
: BooleanLiteralSet.EMPTY,
flowScope,
flowScope);
}
@CheckReturnValue
private FlowScope redeclareSimpleVar(FlowScope scope, Node nameNode, JSType varType) {
checkState(nameNode.isName(), nameNode);
String varName = nameNode.getString();
if (varType == null) {
varType = getNativeType(JSTypeNative.UNKNOWN_TYPE);
}
if (isUnflowable(getDeclaredVar(scope, varName))) {
return scope;
}
return scope.inferSlotType(varName, varType);
}
private boolean isUnflowable(TypedVar v) {
return v != null
&& v.isLocal()
&& v.isMarkedEscaped()
// It's OK to flow a variable in the scope where it's escaped.
&& v.getScope().getClosestContainerScope() == containerScope;
}
/**
* This method gets the JSType from the Node argument and verifies that it is
* present.
*/
private JSType getJSType(Node n) {
JSType jsType = n.getJSType();
if (jsType == null) {
// TODO(nicksantos): This branch indicates a compiler bug, not worthy of
// halting the compilation but we should log this and analyze to track
// down why it happens. This is not critical and will be resolved over
// time as the type checker is extended.
return unknownType;
} else {
return jsType;
}
}
private JSType getNativeType(JSTypeNative typeId) {
return registry.getNativeType(typeId);
}
private static TypedVar getDeclaredVar(FlowScope scope, String name) {
return ((TypedScope) scope.getDeclarationScope()).getVar(name);
}
}
| Remove the targetType parameter of TypeInference#updateScopeForAssign
It's very trivial to calculate from the target parameter, and removing the parameter makes the method signature easier to understand.
-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=208136798
| src/com/google/javascript/jscomp/TypeInference.java | Remove the targetType parameter of TypeInference#updateScopeForAssign | <ide><path>rc/com/google/javascript/jscomp/TypeInference.java
<ide> import java.util.Map.Entry;
<ide> import java.util.Set;
<ide> import javax.annotation.CheckReturnValue;
<add>import javax.annotation.Nullable;
<ide>
<ide> /**
<ide> * Type inference within a script node or a function body, using the data-flow
<ide> JSType newType =
<ide> registry.createUnionType(
<ide> getJSType(astParameter).restrictByNotUndefined(), getJSType(defaultValue));
<del> entryFlowScope =
<del> updateScopeForAssignment(
<del> entryFlowScope, astParameter, getJSType(astParameter), newType);
<add> entryFlowScope = updateScopeForAssignment(entryFlowScope, astParameter, newType);
<ide> }
<ide> }
<ide> }
<ide> informed = traverseDestructuringPattern(item, informed, newType);
<ide> } else {
<ide> informed = traverse(item, informed);
<del> informed = updateScopeForAssignment(informed, item, item.getJSType(), newType);
<add> informed = updateScopeForAssignment(informed, item, newType);
<ide> }
<ide> }
<ide> newScope = informed;
<ide> } else {
<ide> scope = traverseChildren(n, scope);
<ide>
<del> JSType targetType = target.getJSType();
<ide> JSType valueType = getJSType(value);
<ide> n.setJSType(valueType);
<ide>
<del> return updateScopeForAssignment(scope, target, targetType, valueType);
<add> return updateScopeForAssignment(scope, target, valueType);
<ide> }
<ide> }
<ide>
<ide> Node left = n.getFirstChild();
<ide> scope = traverseChildren(n, scope);
<ide>
<del> JSType leftType = left.getJSType();
<ide> n.setJSType(resultType);
<ide>
<ide> // The lhs is both an input and an output, so don't update the input type here.
<del> return updateScopeForAssignment(scope, left, leftType, resultType, null);
<add> return updateScopeForAssignment(scope, left, resultType, null);
<ide> }
<ide>
<ide> private static boolean isInExternFile(Node n) {
<ide> }
<ide> }
<ide>
<add> /**
<add> * Calls {@link #updateScopeForAssignment(FlowScope, Node, JSType, Node)} and updates the given
<add> * `target` node with the given `resultType` if it's a name or getprop.
<add> */
<add> @CheckReturnValue
<add> private FlowScope updateScopeForAssignment(FlowScope scope, Node target, JSType resultType) {
<add> return updateScopeForAssignment(scope, target, resultType, target);
<add> }
<add>
<add> /**
<add> * Updates the scope according to the result of an assignment.
<add> *
<add> * @param target the node being assigned to, e.g. `a.b` in `a.b = 3;`
<add> * @param resultType the type being assigned to `target`, e.g. `number` in `a.b = 3;`
<add> * @param updateNode a node to update with the `resultType`. must be either `target` or null.
<add> */
<ide> @CheckReturnValue
<ide> private FlowScope updateScopeForAssignment(
<del> FlowScope scope, Node target, JSType targetType, JSType resultType) {
<del> return updateScopeForAssignment(scope, target, targetType, resultType, target);
<del> }
<del>
<del> /** Updates the scope according to the result of an assignment. */
<del> @CheckReturnValue
<del> private FlowScope updateScopeForAssignment(
<del> FlowScope scope, Node target, JSType targetType, JSType resultType, Node updateNode) {
<add> FlowScope scope, Node target, JSType resultType, @Nullable Node updateNode) {
<ide> checkNotNull(resultType);
<ide> checkState(updateNode == null || updateNode == target);
<add> JSType targetType = target.getJSType();
<ide>
<ide> Node right = NodeUtil.getRValueOfLValue(target);
<ide> if (isPossibleMixinApplication(target, right)) {
<ide> // declare in the scope
<ide> JSType targetType = target.inferType();
<ide> targetType = targetType != null ? targetType : getNativeType(UNKNOWN_TYPE);
<del> scope = updateScopeForAssignment(scope, targetNode, targetNode.getJSType(), targetType);
<add> scope = updateScopeForAssignment(scope, targetNode, targetType);
<ide> }
<ide> }
<ide> // put the `inferred type` of a pattern on it, to make it easier to do typechecking
<ide> JSType type = n.getJSType();
<ide> if (value != null) {
<ide> scope = traverse(value, scope);
<del> return updateScopeForAssignment(
<del> scope, n, n.getJSType() /* could be null */, getJSType(value));
<add> return updateScopeForAssignment(scope, n, getJSType(value));
<ide> } else if (n.getParent().isLet()) {
<ide> // Whenever we see a LET, we're guaranteed it's not yet in the scope, and we don't need to
<ide> // worry about it being from an outer scope. In this case, it has no child, so the actual
<ide> // TODO(sdh): I would have thought that #updateScopeForTypeChange would handle using the
<ide> // declared type correctly, but for some reason it doesn't so we handle it here.
<ide> JSType resultType = type != null ? type : getNativeType(VOID_TYPE);
<del> scope = updateScopeForAssignment(scope, n, type, resultType);
<add> scope = updateScopeForAssignment(scope, n, resultType);
<ide> type = resultType;
<ide> } else {
<ide> StaticTypedSlot var = scope.getSlot(varName);
<ide> if (n.isAssignAdd()) {
<ide> // TODO(johnlenz): this should not update the type of the lhs as that is use as a
<ide> // input and need to be preserved for type checking.
<del> // Instead call this overload `updateScopeForAssignment(scope, left, leftType, type, null);`
<del> scope = updateScopeForAssignment(scope, left, leftType, type);
<add> // Instead call this overload `updateScopeForAssignment(scope, left, type, null);`
<add> scope = updateScopeForAssignment(scope, left, type);
<ide> }
<ide>
<ide> return scope; |
|
Java | apache-2.0 | f18330f3836dc481e13a21df2781eaf44856be30 | 0 | kevinconaway/storm,erikdw/storm,kishorvpatil/incubator-storm,pczb/storm,kevinconaway/storm,knusbaum/incubator-storm,srishtyagrawal/storm,hmcl/storm-apache,pczb/storm,erikdw/storm,0x726d77/storm,hmcl/storm-apache,srdo/storm,Crim/storm,ujfjhz/storm,0x726d77/storm,sakanaou/storm,hmcc/storm,srishtyagrawal/storm,hmcl/storm-apache,srdo/storm,0x726d77/storm,kevinconaway/storm,0x726d77/storm,ujfjhz/storm,F30/storm,hmcl/storm-apache,kevinconaway/storm,kishorvpatil/incubator-storm,F30/storm,pczb/storm,kevpeek/storm,hmcc/storm,knusbaum/incubator-storm,kevpeek/storm,hmcc/storm,sakanaou/storm,F30/storm,sakanaou/storm,ujfjhz/storm,knusbaum/incubator-storm,hmcc/storm,kevinconaway/storm,0x726d77/storm,0x726d77/storm,ujfjhz/storm,knusbaum/incubator-storm,srdo/storm,kevpeek/storm,kishorvpatil/incubator-storm,knusbaum/incubator-storm,srdo/storm,ujfjhz/storm,srishtyagrawal/storm,knusbaum/incubator-storm,knusbaum/incubator-storm,Crim/storm,hmcl/storm-apache,srdo/storm,erikdw/storm,hmcc/storm,Crim/storm,srishtyagrawal/storm,srishtyagrawal/storm,Crim/storm,kevpeek/storm,ujfjhz/storm,erikdw/storm,hmcl/storm-apache,erikdw/storm,sakanaou/storm,erikdw/storm,kevinconaway/storm,F30/storm,F30/storm,kishorvpatil/incubator-storm,pczb/storm,F30/storm,kishorvpatil/incubator-storm,sakanaou/storm,hmcc/storm,Crim/storm,srishtyagrawal/storm,srdo/storm,pczb/storm,kevinconaway/storm,kevpeek/storm,0x726d77/storm,hmcl/storm-apache,srishtyagrawal/storm,sakanaou/storm,kishorvpatil/incubator-storm,F30/storm,pczb/storm,pczb/storm,kevpeek/storm,erikdw/storm,ujfjhz/storm,Crim/storm,kishorvpatil/incubator-storm,srdo/storm,Crim/storm,kevpeek/storm,hmcc/storm,sakanaou/storm | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.storm.daemon.supervisor;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.storm.DaemonConfig;
import org.apache.storm.cluster.IStormClusterState;
import org.apache.storm.cluster.VersionedData;
import org.apache.storm.daemon.supervisor.Slot.MachineState;
import org.apache.storm.daemon.supervisor.Slot.TopoProfileAction;
import org.apache.storm.event.EventManager;
import org.apache.storm.generated.Assignment;
import org.apache.storm.generated.ExecutorInfo;
import org.apache.storm.generated.LocalAssignment;
import org.apache.storm.generated.NodeInfo;
import org.apache.storm.generated.ProfileRequest;
import org.apache.storm.generated.WorkerResources;
import org.apache.storm.localizer.ILocalizer;
import org.apache.storm.scheduler.ISupervisor;
import org.apache.storm.utils.LocalState;
import org.apache.storm.utils.Time;
import org.apache.storm.utils.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ReadClusterState implements Runnable, AutoCloseable {
private static final Logger LOG = LoggerFactory.getLogger(ReadClusterState.class);
private final Map<String, Object> superConf;
private final IStormClusterState stormClusterState;
private final EventManager syncSupEventManager;
private final AtomicReference<Map<String, VersionedData<Assignment>>> assignmentVersions;
private final Map<Integer, Slot> slots = new HashMap<>();
private final AtomicInteger readRetry = new AtomicInteger(0);
private final String assignmentId;
private final ISupervisor iSuper;
private final ILocalizer localizer;
private final ContainerLauncher launcher;
private final String host;
private final LocalState localState;
private final AtomicReference<Map<Long, LocalAssignment>> cachedAssignments;
public ReadClusterState(Supervisor supervisor) throws Exception {
this.superConf = supervisor.getConf();
this.stormClusterState = supervisor.getStormClusterState();
this.syncSupEventManager = supervisor.getEventManger();
this.assignmentVersions = new AtomicReference<>(new HashMap<>());
this.assignmentId = supervisor.getAssignmentId();
this.iSuper = supervisor.getiSupervisor();
this.localizer = supervisor.getAsyncLocalizer();
this.host = supervisor.getHostName();
this.localState = supervisor.getLocalState();
this.cachedAssignments = supervisor.getCurrAssignment();
this.launcher = ContainerLauncher.make(superConf, assignmentId, supervisor.getSharedContext());
@SuppressWarnings("unchecked")
List<Number> ports = (List<Number>)superConf.get(DaemonConfig.SUPERVISOR_SLOTS_PORTS);
for (Number port: ports) {
slots.put(port.intValue(), mkSlot(port.intValue()));
}
try {
Collection<String> workers = SupervisorUtils.supervisorWorkerIds(superConf);
for (Slot slot: slots.values()) {
String workerId = slot.getWorkerId();
if (workerId != null) {
workers.remove(workerId);
}
}
if (!workers.isEmpty()) {
supervisor.killWorkers(workers, launcher);
}
} catch (Exception e) {
LOG.warn("Error trying to clean up old workers", e);
}
//All the slots/assignments should be recovered now, so we can clean up anything that we don't expect to be here
try {
localizer.cleanupUnusedTopologies();
} catch (Exception e) {
LOG.warn("Error trying to clean up old topologies", e);
}
for (Slot slot: slots.values()) {
slot.start();
}
}
private Slot mkSlot(int port) throws Exception {
return new Slot(localizer, superConf, launcher, host, port,
localState, stormClusterState, iSuper, cachedAssignments);
}
@Override
public synchronized void run() {
try {
Runnable syncCallback = new EventManagerPushCallback(this, syncSupEventManager);
List<String> stormIds = stormClusterState.assignments(syncCallback);
Map<String, VersionedData<Assignment>> assignmentsSnapshot =
getAssignmentsSnapshot(stormClusterState, stormIds, assignmentVersions.get(), syncCallback);
Map<Integer, LocalAssignment> allAssignments =
readAssignments(assignmentsSnapshot);
if (allAssignments == null) {
//Something odd happened try again later
return;
}
Map<String, List<ProfileRequest>> topoIdToProfilerActions = getProfileActions(stormClusterState, stormIds);
HashSet<Integer> assignedPorts = new HashSet<>();
LOG.debug("Synchronizing supervisor");
LOG.debug("All assignment: {}", allAssignments);
LOG.debug("Topology Ids -> Profiler Actions {}", topoIdToProfilerActions);
for (Integer port: allAssignments.keySet()) {
if (iSuper.confirmAssigned(port)) {
assignedPorts.add(port);
}
}
HashSet<Integer> allPorts = new HashSet<>(assignedPorts);
allPorts.addAll(slots.keySet());
Map<Integer, Set<TopoProfileAction>> filtered = new HashMap<>();
for (Entry<String, List<ProfileRequest>> entry: topoIdToProfilerActions.entrySet()) {
String topoId = entry.getKey();
if (entry.getValue() != null) {
for (ProfileRequest req: entry.getValue()) {
NodeInfo ni = req.get_nodeInfo();
if (host.equals(ni.get_node())) {
Long port = ni.get_port().iterator().next();
Set<TopoProfileAction> actions = filtered.get(port.intValue());
if (actions == null) {
actions = new HashSet<>();
filtered.put(port.intValue(), actions);
}
actions.add(new TopoProfileAction(topoId, req));
}
}
}
}
for (Integer port: allPorts) {
Slot slot = slots.get(port);
if (slot == null) {
slot = mkSlot(port);
slots.put(port, slot);
slot.start();
}
slot.setNewAssignment(allAssignments.get(port));
slot.addProfilerActions(filtered.get(port));
}
} catch (Exception e) {
LOG.error("Failed to Sync Supervisor", e);
throw new RuntimeException(e);
}
}
protected Map<String, VersionedData<Assignment>> getAssignmentsSnapshot(IStormClusterState stormClusterState, List<String> topoIds,
Map<String, VersionedData<Assignment>> localAssignmentVersion, Runnable callback) throws Exception {
Map<String, VersionedData<Assignment>> updateAssignmentVersion = new HashMap<>();
for (String topoId : topoIds) {
Integer recordedVersion = -1;
Integer version = stormClusterState.assignmentVersion(topoId, callback);
VersionedData<Assignment> locAssignment = localAssignmentVersion.get(topoId);
if (locAssignment != null) {
recordedVersion = locAssignment.getVersion();
}
if (version == null) {
// ignore
} else if (version.equals(recordedVersion)) {
updateAssignmentVersion.put(topoId, locAssignment);
} else {
VersionedData<Assignment> assignmentVersion = stormClusterState.assignmentInfoWithVersion(topoId, callback);
updateAssignmentVersion.put(topoId, assignmentVersion);
}
}
return updateAssignmentVersion;
}
protected Map<String, List<ProfileRequest>> getProfileActions(IStormClusterState stormClusterState, List<String> stormIds) throws Exception {
Map<String, List<ProfileRequest>> ret = new HashMap<String, List<ProfileRequest>>();
for (String stormId : stormIds) {
List<ProfileRequest> profileRequests = stormClusterState.getTopologyProfileRequests(stormId);
ret.put(stormId, profileRequests);
}
return ret;
}
protected Map<Integer, LocalAssignment> readAssignments(Map<String, VersionedData<Assignment>> assignmentsSnapshot) {
try {
Map<Integer, LocalAssignment> portLA = new HashMap<>();
for (Map.Entry<String, VersionedData<Assignment>> assignEntry : assignmentsSnapshot.entrySet()) {
String topoId = assignEntry.getKey();
Assignment assignment = assignEntry.getValue().getData();
Map<Integer, LocalAssignment> portTasks = readMyExecutors(topoId, assignmentId, assignment);
for (Map.Entry<Integer, LocalAssignment> entry : portTasks.entrySet()) {
Integer port = entry.getKey();
LocalAssignment la = entry.getValue();
if (!portLA.containsKey(port)) {
portLA.put(port, la);
} else {
throw new RuntimeException("Should not have multiple topologies assigned to one port "
+ port + " " + la + " " + portLA);
}
}
}
readRetry.set(0);
return portLA;
} catch (RuntimeException e) {
if (readRetry.get() > 2) {
throw e;
} else {
readRetry.addAndGet(1);
}
LOG.warn("{} : retrying {} of 3", e.getMessage(), readRetry.get());
return null;
}
}
protected Map<Integer, LocalAssignment> readMyExecutors(String topoId, String assignmentId, Assignment assignment) {
Map<Integer, LocalAssignment> portTasks = new HashMap<>();
Map<Long, WorkerResources> slotsResources = new HashMap<>();
Map<NodeInfo, WorkerResources> nodeInfoWorkerResourcesMap = assignment.get_worker_resources();
if (nodeInfoWorkerResourcesMap != null) {
for (Map.Entry<NodeInfo, WorkerResources> entry : nodeInfoWorkerResourcesMap.entrySet()) {
if (entry.getKey().get_node().equals(assignmentId)) {
Set<Long> ports = entry.getKey().get_port();
for (Long port : ports) {
slotsResources.put(port, entry.getValue());
}
}
}
}
boolean hasShared = false;
double amountShared = 0.0;
if (assignment.is_set_total_shared_off_heap()) {
Double d = assignment.get_total_shared_off_heap().get(assignmentId);
if (d != null) {
amountShared = d;
hasShared = true;
}
}
Map<List<Long>, NodeInfo> executorNodePort = assignment.get_executor_node_port();
if (executorNodePort != null) {
for (Map.Entry<List<Long>, NodeInfo> entry : executorNodePort.entrySet()) {
if (entry.getValue().get_node().equals(assignmentId)) {
for (Long port : entry.getValue().get_port()) {
LocalAssignment localAssignment = portTasks.get(port.intValue());
if (localAssignment == null) {
List<ExecutorInfo> executors = new ArrayList<>();
localAssignment = new LocalAssignment(topoId, executors);
if (slotsResources.containsKey(port)) {
localAssignment.set_resources(slotsResources.get(port));
}
if (hasShared) {
localAssignment.set_total_node_shared(amountShared);
}
if (assignment.is_set_owner()) {
localAssignment.set_owner(assignment.get_owner());
}
portTasks.put(port.intValue(), localAssignment);
}
List<ExecutorInfo> executorInfoList = localAssignment.get_executors();
executorInfoList.add(new ExecutorInfo(entry.getKey().get(0).intValue(), entry.getKey().get(entry.getKey().size() - 1).intValue()));
}
}
}
}
return portTasks;
}
private static final long WARN_MILLIS = 1_000; //Initial timeout 1 second. Workers commit suicide after this
private static final long ERROR_MILLIS = 60_000; //1 min. This really means something is wrong. Even on a very slow node
public static final UniFunc<Slot> DEFAULT_ON_ERROR_TIMEOUT = (slot) -> {
throw new IllegalStateException("It took over " + ERROR_MILLIS + "ms to shut down slot " + slot);
};
public static final UniFunc<Slot> DEFAULT_ON_WARN_TIMEOUT = (slot) -> LOG.warn("It has taken {}ms so far and {} is still not shut down.", WARN_MILLIS, slot);
public static final UniFunc<Slot> THREAD_DUMP_ON_ERROR = (slot) -> {
LOG.warn("Shutdown of slot {} appears to be stuck\n{}", slot, Utils.threadDump());
DEFAULT_ON_ERROR_TIMEOUT.call(slot);
};
public synchronized void shutdownAllWorkers(UniFunc<Slot> onWarnTimeout, UniFunc<Slot> onErrorTimeout) {
for (Slot slot: slots.values()) {
LOG.info("Setting {} assignment to null", slot);
slot.setNewAssignment(null);
}
if (onWarnTimeout == null) {
onWarnTimeout = DEFAULT_ON_WARN_TIMEOUT;
}
if (onErrorTimeout == null) {
onErrorTimeout = DEFAULT_ON_ERROR_TIMEOUT;
}
long startTime = Time.currentTimeMillis();
Exception exp = null;
for (Slot slot: slots.values()) {
LOG.info("Waiting for {} to be EMPTY, currently {}", slot, slot.getMachineState());
try {
while (slot.getMachineState() != MachineState.EMPTY) {
long timeSpentMillis = Time.currentTimeMillis() - startTime;
if (timeSpentMillis > ERROR_MILLIS) {
onErrorTimeout.call(slot);
}
if (timeSpentMillis > WARN_MILLIS) {
onWarnTimeout.call(slot);
}
if (Time.isSimulating()) {
Time.advanceTime(100);
}
Thread.sleep(100);
}
} catch (Exception e) {
LOG.error("Error trying to shutdown workers in {}", slot, e);
exp = e;
}
}
if (exp != null) {
if (exp instanceof RuntimeException) {
throw (RuntimeException)exp;
}
throw new RuntimeException(exp);
}
}
@Override
public void close() {
for (Slot slot: slots.values()) {
try {
slot.close();
} catch (Exception e) {
LOG.error("Error trying to shutdown {}", slot, e);
}
}
}
}
| storm-server/src/main/java/org/apache/storm/daemon/supervisor/ReadClusterState.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.storm.daemon.supervisor;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.storm.DaemonConfig;
import org.apache.storm.cluster.IStormClusterState;
import org.apache.storm.cluster.VersionedData;
import org.apache.storm.daemon.supervisor.Slot.MachineState;
import org.apache.storm.daemon.supervisor.Slot.TopoProfileAction;
import org.apache.storm.event.EventManager;
import org.apache.storm.generated.Assignment;
import org.apache.storm.generated.ExecutorInfo;
import org.apache.storm.generated.LocalAssignment;
import org.apache.storm.generated.NodeInfo;
import org.apache.storm.generated.ProfileRequest;
import org.apache.storm.generated.WorkerResources;
import org.apache.storm.localizer.ILocalizer;
import org.apache.storm.scheduler.ISupervisor;
import org.apache.storm.utils.LocalState;
import org.apache.storm.utils.Time;
import org.apache.storm.utils.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ReadClusterState implements Runnable, AutoCloseable {
private static final Logger LOG = LoggerFactory.getLogger(ReadClusterState.class);
private final Map<String, Object> superConf;
private final IStormClusterState stormClusterState;
private final EventManager syncSupEventManager;
private final AtomicReference<Map<String, VersionedData<Assignment>>> assignmentVersions;
private final Map<Integer, Slot> slots = new HashMap<>();
private final AtomicInteger readRetry = new AtomicInteger(0);
private final String assignmentId;
private final ISupervisor iSuper;
private final ILocalizer localizer;
private final ContainerLauncher launcher;
private final String host;
private final LocalState localState;
private final IStormClusterState clusterState;
private final AtomicReference<Map<Long, LocalAssignment>> cachedAssignments;
public ReadClusterState(Supervisor supervisor) throws Exception {
this.superConf = supervisor.getConf();
this.stormClusterState = supervisor.getStormClusterState();
this.syncSupEventManager = supervisor.getEventManger();
this.assignmentVersions = new AtomicReference<>(new HashMap<>());
this.assignmentId = supervisor.getAssignmentId();
this.iSuper = supervisor.getiSupervisor();
this.localizer = supervisor.getAsyncLocalizer();
this.host = supervisor.getHostName();
this.localState = supervisor.getLocalState();
this.clusterState = supervisor.getStormClusterState();
this.cachedAssignments = supervisor.getCurrAssignment();
this.launcher = ContainerLauncher.make(superConf, assignmentId, supervisor.getSharedContext());
@SuppressWarnings("unchecked")
List<Number> ports = (List<Number>)superConf.get(DaemonConfig.SUPERVISOR_SLOTS_PORTS);
for (Number port: ports) {
slots.put(port.intValue(), mkSlot(port.intValue()));
}
try {
Collection<String> workers = SupervisorUtils.supervisorWorkerIds(superConf);
for (Slot slot: slots.values()) {
String workerId = slot.getWorkerId();
if (workerId != null) {
workers.remove(workerId);
}
}
if (!workers.isEmpty()) {
supervisor.killWorkers(workers, launcher);
}
} catch (Exception e) {
LOG.warn("Error trying to clean up old workers", e);
}
//All the slots/assignments should be recovered now, so we can clean up anything that we don't expect to be here
try {
localizer.cleanupUnusedTopologies();
} catch (Exception e) {
LOG.warn("Error trying to clean up old topologies", e);
}
for (Slot slot: slots.values()) {
slot.start();
}
}
private Slot mkSlot(int port) throws Exception {
return new Slot(localizer, superConf, launcher, host, port,
localState, clusterState, iSuper, cachedAssignments);
}
@Override
public synchronized void run() {
try {
Runnable syncCallback = new EventManagerPushCallback(this, syncSupEventManager);
List<String> stormIds = stormClusterState.assignments(syncCallback);
Map<String, VersionedData<Assignment>> assignmentsSnapshot =
getAssignmentsSnapshot(stormClusterState, stormIds, assignmentVersions.get(), syncCallback);
Map<Integer, LocalAssignment> allAssignments =
readAssignments(assignmentsSnapshot);
if (allAssignments == null) {
//Something odd happened try again later
return;
}
Map<String, List<ProfileRequest>> topoIdToProfilerActions = getProfileActions(stormClusterState, stormIds);
HashSet<Integer> assignedPorts = new HashSet<>();
LOG.debug("Synchronizing supervisor");
LOG.debug("All assignment: {}", allAssignments);
LOG.debug("Topology Ids -> Profiler Actions {}", topoIdToProfilerActions);
for (Integer port: allAssignments.keySet()) {
if (iSuper.confirmAssigned(port)) {
assignedPorts.add(port);
}
}
HashSet<Integer> allPorts = new HashSet<>(assignedPorts);
allPorts.addAll(slots.keySet());
Map<Integer, Set<TopoProfileAction>> filtered = new HashMap<>();
for (Entry<String, List<ProfileRequest>> entry: topoIdToProfilerActions.entrySet()) {
String topoId = entry.getKey();
if (entry.getValue() != null) {
for (ProfileRequest req: entry.getValue()) {
NodeInfo ni = req.get_nodeInfo();
if (host.equals(ni.get_node())) {
Long port = ni.get_port().iterator().next();
Set<TopoProfileAction> actions = filtered.get(port.intValue());
if (actions == null) {
actions = new HashSet<>();
filtered.put(port.intValue(), actions);
}
actions.add(new TopoProfileAction(topoId, req));
}
}
}
}
for (Integer port: allPorts) {
Slot slot = slots.get(port);
if (slot == null) {
slot = mkSlot(port);
slots.put(port, slot);
slot.start();
}
slot.setNewAssignment(allAssignments.get(port));
slot.addProfilerActions(filtered.get(port));
}
} catch (Exception e) {
LOG.error("Failed to Sync Supervisor", e);
throw new RuntimeException(e);
}
}
protected Map<String, VersionedData<Assignment>> getAssignmentsSnapshot(IStormClusterState stormClusterState, List<String> topoIds,
Map<String, VersionedData<Assignment>> localAssignmentVersion, Runnable callback) throws Exception {
Map<String, VersionedData<Assignment>> updateAssignmentVersion = new HashMap<>();
for (String topoId : topoIds) {
Integer recordedVersion = -1;
Integer version = stormClusterState.assignmentVersion(topoId, callback);
VersionedData<Assignment> locAssignment = localAssignmentVersion.get(topoId);
if (locAssignment != null) {
recordedVersion = locAssignment.getVersion();
}
if (version == null) {
// ignore
} else if (version.equals(recordedVersion)) {
updateAssignmentVersion.put(topoId, locAssignment);
} else {
VersionedData<Assignment> assignmentVersion = stormClusterState.assignmentInfoWithVersion(topoId, callback);
updateAssignmentVersion.put(topoId, assignmentVersion);
}
}
return updateAssignmentVersion;
}
protected Map<String, List<ProfileRequest>> getProfileActions(IStormClusterState stormClusterState, List<String> stormIds) throws Exception {
Map<String, List<ProfileRequest>> ret = new HashMap<String, List<ProfileRequest>>();
for (String stormId : stormIds) {
List<ProfileRequest> profileRequests = stormClusterState.getTopologyProfileRequests(stormId);
ret.put(stormId, profileRequests);
}
return ret;
}
protected Map<Integer, LocalAssignment> readAssignments(Map<String, VersionedData<Assignment>> assignmentsSnapshot) {
try {
Map<Integer, LocalAssignment> portLA = new HashMap<>();
for (Map.Entry<String, VersionedData<Assignment>> assignEntry : assignmentsSnapshot.entrySet()) {
String topoId = assignEntry.getKey();
Assignment assignment = assignEntry.getValue().getData();
Map<Integer, LocalAssignment> portTasks = readMyExecutors(topoId, assignmentId, assignment);
for (Map.Entry<Integer, LocalAssignment> entry : portTasks.entrySet()) {
Integer port = entry.getKey();
LocalAssignment la = entry.getValue();
if (!portLA.containsKey(port)) {
portLA.put(port, la);
} else {
throw new RuntimeException("Should not have multiple topologies assigned to one port "
+ port + " " + la + " " + portLA);
}
}
}
readRetry.set(0);
return portLA;
} catch (RuntimeException e) {
if (readRetry.get() > 2) {
throw e;
} else {
readRetry.addAndGet(1);
}
LOG.warn("{} : retrying {} of 3", e.getMessage(), readRetry.get());
return null;
}
}
protected Map<Integer, LocalAssignment> readMyExecutors(String topoId, String assignmentId, Assignment assignment) {
Map<Integer, LocalAssignment> portTasks = new HashMap<>();
Map<Long, WorkerResources> slotsResources = new HashMap<>();
Map<NodeInfo, WorkerResources> nodeInfoWorkerResourcesMap = assignment.get_worker_resources();
if (nodeInfoWorkerResourcesMap != null) {
for (Map.Entry<NodeInfo, WorkerResources> entry : nodeInfoWorkerResourcesMap.entrySet()) {
if (entry.getKey().get_node().equals(assignmentId)) {
Set<Long> ports = entry.getKey().get_port();
for (Long port : ports) {
slotsResources.put(port, entry.getValue());
}
}
}
}
boolean hasShared = false;
double amountShared = 0.0;
if (assignment.is_set_total_shared_off_heap()) {
Double d = assignment.get_total_shared_off_heap().get(assignmentId);
if (d != null) {
amountShared = d;
hasShared = true;
}
}
Map<List<Long>, NodeInfo> executorNodePort = assignment.get_executor_node_port();
if (executorNodePort != null) {
for (Map.Entry<List<Long>, NodeInfo> entry : executorNodePort.entrySet()) {
if (entry.getValue().get_node().equals(assignmentId)) {
for (Long port : entry.getValue().get_port()) {
LocalAssignment localAssignment = portTasks.get(port.intValue());
if (localAssignment == null) {
List<ExecutorInfo> executors = new ArrayList<>();
localAssignment = new LocalAssignment(topoId, executors);
if (slotsResources.containsKey(port)) {
localAssignment.set_resources(slotsResources.get(port));
}
if (hasShared) {
localAssignment.set_total_node_shared(amountShared);
}
if (assignment.is_set_owner()) {
localAssignment.set_owner(assignment.get_owner());
}
portTasks.put(port.intValue(), localAssignment);
}
List<ExecutorInfo> executorInfoList = localAssignment.get_executors();
executorInfoList.add(new ExecutorInfo(entry.getKey().get(0).intValue(), entry.getKey().get(entry.getKey().size() - 1).intValue()));
}
}
}
}
return portTasks;
}
private static final long WARN_MILLIS = 1_000; //Initial timeout 1 second. Workers commit suicide after this
private static final long ERROR_MILLIS = 60_000; //1 min. This really means something is wrong. Even on a very slow node
public static final UniFunc<Slot> DEFAULT_ON_ERROR_TIMEOUT = (slot) -> {
throw new IllegalStateException("It took over " + ERROR_MILLIS + "ms to shut down slot " + slot);
};
public static final UniFunc<Slot> DEFAULT_ON_WARN_TIMEOUT = (slot) -> LOG.warn("It has taken {}ms so far and {} is still not shut down.", WARN_MILLIS, slot);
public static final UniFunc<Slot> THREAD_DUMP_ON_ERROR = (slot) -> {
LOG.warn("Shutdown of slot {} appears to be stuck\n{}", slot, Utils.threadDump());
DEFAULT_ON_ERROR_TIMEOUT.call(slot);
};
public synchronized void shutdownAllWorkers(UniFunc<Slot> onWarnTimeout, UniFunc<Slot> onErrorTimeout) {
for (Slot slot: slots.values()) {
LOG.info("Setting {} assignment to null", slot);
slot.setNewAssignment(null);
}
if (onWarnTimeout == null) {
onWarnTimeout = DEFAULT_ON_WARN_TIMEOUT;
}
if (onErrorTimeout == null) {
onErrorTimeout = DEFAULT_ON_ERROR_TIMEOUT;
}
long startTime = Time.currentTimeMillis();
Exception exp = null;
for (Slot slot: slots.values()) {
LOG.info("Waiting for {} to be EMPTY, currently {}", slot, slot.getMachineState());
try {
while (slot.getMachineState() != MachineState.EMPTY) {
long timeSpentMillis = Time.currentTimeMillis() - startTime;
if (timeSpentMillis > ERROR_MILLIS) {
onErrorTimeout.call(slot);
}
if (timeSpentMillis > WARN_MILLIS) {
onWarnTimeout.call(slot);
}
if (Time.isSimulating()) {
Time.advanceTime(100);
}
Thread.sleep(100);
}
} catch (Exception e) {
LOG.error("Error trying to shutdown workers in {}", slot, e);
exp = e;
}
}
if (exp != null) {
if (exp instanceof RuntimeException) {
throw (RuntimeException)exp;
}
throw new RuntimeException(exp);
}
}
@Override
public void close() {
for (Slot slot: slots.values()) {
try {
slot.close();
} catch (Exception e) {
LOG.error("Error trying to shutdown {}", slot, e);
}
}
}
}
| Quick fix: remove duplicated IStormClusterState object in ReadClusterState.java
| storm-server/src/main/java/org/apache/storm/daemon/supervisor/ReadClusterState.java | Quick fix: remove duplicated IStormClusterState object in ReadClusterState.java | <ide><path>torm-server/src/main/java/org/apache/storm/daemon/supervisor/ReadClusterState.java
<ide> private final ContainerLauncher launcher;
<ide> private final String host;
<ide> private final LocalState localState;
<del> private final IStormClusterState clusterState;
<ide> private final AtomicReference<Map<Long, LocalAssignment>> cachedAssignments;
<ide>
<ide> public ReadClusterState(Supervisor supervisor) throws Exception {
<ide> this.localizer = supervisor.getAsyncLocalizer();
<ide> this.host = supervisor.getHostName();
<ide> this.localState = supervisor.getLocalState();
<del> this.clusterState = supervisor.getStormClusterState();
<ide> this.cachedAssignments = supervisor.getCurrAssignment();
<ide>
<ide> this.launcher = ContainerLauncher.make(superConf, assignmentId, supervisor.getSharedContext());
<ide>
<ide> private Slot mkSlot(int port) throws Exception {
<ide> return new Slot(localizer, superConf, launcher, host, port,
<del> localState, clusterState, iSuper, cachedAssignments);
<add> localState, stormClusterState, iSuper, cachedAssignments);
<ide> }
<ide>
<ide> @Override |
|
JavaScript | mit | 8a12baf1588bba505b2a321481ce5022322d39a7 | 0 | Bacra/seajs-combo-express | var path = require('path');
var crypto = require('crypto');
var underscore = require('underscore');
var send = require('send');
var debug = require('debug')('seajs-combo-express:main');
var SendStream = require('./send');
var doCache = require('./cache');
var defaults = {
cachePath : '',
separator : '\n',
root : path.dirname(module.parent.parent.filename),
maxage : 0,
comboSyntax : ["??", ","],
parseFilename: function(url) {
return crypto.createHash('sha1').update(url).digest('hex')+'.js';
}
};
module.exports = function(config) {
if (typeof config == 'string') {
config = {root: config};
}
config = underscore.extend({}, defaults, config);
config.root = path.normalize(config.root);
return function(req, res, next) {
var sender = new SendStream(req, res, config);
var rs = sender.check();
if (rs === false) {
return next();
} else if (rs === true) {
return;
}
if (config.cachePath) {
// width cache
var file = config.cachePath+'/'+config.parseFilename(req.url);
debug('dist file name: %s', file);
if (doCache(req, res, file, sender, config) === false) {
debug('no cahce file ready: %s', file);
} else {
return;
}
}
sender.on('error', function(err) {
debug('combo err', err);
})
.combo();
}
};
| lib/main.js | var path = require('path');
var crypto = require('crypto');
var underscore = require('underscore');
var send = require('send');
var debug = require('debug')('seajs-combo-express:main');
var SendStream = require('./send');
var doCache = require('./cache');
var defaults = {
cachePath : '',
separator : '\n',
root : path.dirname(module.parent.parent.filename),
maxage : 0,
comboSyntax : ["??", ","],
parseFilename: function(url) {
return crypto.createHash('sha1').update(url).digest('hex')+'.js';
}
};
module.exports = function(config) {
if (typeof config == 'string') {
config = {root: config};
}
config = underscore.extend({}, config, defaults);
config.root = path.normalize(config.root);
return function(req, res, next) {
var sender = new SendStream(req, res, config);
var rs = sender.check();
if (rs === false) {
return next();
} else if (rs === true) {
return;
}
if (config.cachePath) {
// width cache
var file = config.cachePath+'/'+config.parseFilename(req.url);
debug('dist file name: %s', file);
if (doCache(req, res, file, sender, config) === false) {
debug('no cahce file ready: %s', file);
} else {
return;
}
}
sender.combo();
}
};
| Fix: emit error
Fix: config use default
| lib/main.js | Fix: emit error Fix: config use default | <ide><path>ib/main.js
<ide> config = {root: config};
<ide> }
<ide>
<del> config = underscore.extend({}, config, defaults);
<add> config = underscore.extend({}, defaults, config);
<ide> config.root = path.normalize(config.root);
<ide>
<ide> return function(req, res, next) {
<ide> }
<ide> }
<ide>
<del> sender.combo();
<add> sender.on('error', function(err) {
<add> debug('combo err', err);
<add> })
<add> .combo();
<ide> }
<ide> }; |
|
Java | apache-2.0 | error: pathspec 'Plugins/VarModel/Model/src/de/uni_hildesheim/sse/model/varModel/rewrite/modifier/ImportRegExNameFilter.java' did not match any file(s) known to git
| 2921d98f628d1a13c740cbfe637731e74ca8f7da | 1 | SSEHUB/EASyProducer,SSEHUB/EASyProducer,SSEHUB/EASyProducer | /*
* Copyright 2009-2015 University of Hildesheim, Software Systems Engineering
*
* 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 de.uni_hildesheim.sse.model.varModel.rewrite.modifier;
import de.uni_hildesheim.sse.model.varModel.ProjectImport;
import de.uni_hildesheim.sse.model.varModel.rewrite.RewriteContext;
/**
* Import filter based on a <a href="https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html">
* Java regular expression</a>.
* @author El-Sharkawy
*
*/
public class ImportRegExNameFilter implements IProjectImportFilter {
private String regexFilter;
private boolean whitelist;
/**
* Default constructor for this class.
* @param regexFilter The regular expression which shall be used for filtering.
* @param whitelist <tt>true</tt> the given names will be kept and all others will be filtered out (whitelist
* filtering), <tt>false</tt> the given names will be filtered out and all others will be kept
* (blacklist filtering).
*/
public ImportRegExNameFilter(String regexFilter, boolean whitelist) {
this.regexFilter = regexFilter;
this.whitelist = whitelist;
}
@Override
public ProjectImport handleImport(ProjectImport pImport, RewriteContext context) {
if (pImport.getName().matches(regexFilter) ^ whitelist) {
pImport = null;
}
return pImport;
}
}
| Plugins/VarModel/Model/src/de/uni_hildesheim/sse/model/varModel/rewrite/modifier/ImportRegExNameFilter.java | Added new ProjectImportFilter | Plugins/VarModel/Model/src/de/uni_hildesheim/sse/model/varModel/rewrite/modifier/ImportRegExNameFilter.java | Added new ProjectImportFilter | <ide><path>lugins/VarModel/Model/src/de/uni_hildesheim/sse/model/varModel/rewrite/modifier/ImportRegExNameFilter.java
<add>/*
<add> * Copyright 2009-2015 University of Hildesheim, Software Systems Engineering
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>package de.uni_hildesheim.sse.model.varModel.rewrite.modifier;
<add>
<add>import de.uni_hildesheim.sse.model.varModel.ProjectImport;
<add>import de.uni_hildesheim.sse.model.varModel.rewrite.RewriteContext;
<add>
<add>/**
<add> * Import filter based on a <a href="https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html">
<add> * Java regular expression</a>.
<add> * @author El-Sharkawy
<add> *
<add> */
<add>public class ImportRegExNameFilter implements IProjectImportFilter {
<add>
<add> private String regexFilter;
<add> private boolean whitelist;
<add>
<add> /**
<add> * Default constructor for this class.
<add> * @param regexFilter The regular expression which shall be used for filtering.
<add> * @param whitelist <tt>true</tt> the given names will be kept and all others will be filtered out (whitelist
<add> * filtering), <tt>false</tt> the given names will be filtered out and all others will be kept
<add> * (blacklist filtering).
<add> */
<add> public ImportRegExNameFilter(String regexFilter, boolean whitelist) {
<add> this.regexFilter = regexFilter;
<add> this.whitelist = whitelist;
<add> }
<add>
<add> @Override
<add> public ProjectImport handleImport(ProjectImport pImport, RewriteContext context) {
<add> if (pImport.getName().matches(regexFilter) ^ whitelist) {
<add> pImport = null;
<add> }
<add>
<add> return pImport;
<add> }
<add>} |
|
Java | apache-2.0 | e14b54ce0717d0ca62afc2956166a473354e0061 | 0 | Team-CMPUT301F13T12/301-Project |
package ualberta.g12.adventurecreator.test;
import android.test.ActivityInstrumentationTestCase2;
import junit.framework.TestCase;
import ualberta.g12.adventurecreator.controllers.FragmentController;
import ualberta.g12.adventurecreator.controllers.StoryListController;
import ualberta.g12.adventurecreator.data.Fragment;
import ualberta.g12.adventurecreator.data.OfflineIOHelper;
import ualberta.g12.adventurecreator.data.Story;
import ualberta.g12.adventurecreator.data.StoryList;
import ualberta.g12.adventurecreator.views.FragmentEditActivity;
import ualberta.g12.adventurecreator.views.MainActivity;
import java.util.List;
/**
* These test cases test that the StoryList controller behave to meet the needed requirements.
* Function that will be tested are: addStory, setStory, and createBlankStory().
* The storyList controller is made of getteres and setteres that control all variables
* From the storyList.
*/
public class StoryListControllerTestCases extends ActivityInstrumentationTestCase2<MainActivity> {
private FragmentController fc;
private Fragment sf;
public StoryListControllerTestCases(){
super(MainActivity.class);
}
public StoryListControllerTestCases(Class<MainActivity> activityClass) {
super(MainActivity.class);
}
private StoryListController slc;
private StoryList sl;
private List<Story> stories;
@Override
protected void setUp() throws Exception {
super.setUp();
sl = new StoryList();
slc = new StoryListController(sl, null);
}
public void testSetUp() {
assertNotNull("StoryList was null.", sl);
assertNotNull("StoryListController was null", sl);
}
/**
* Creates a new story to the story list
*/
public void testAddStory() {
// add a story to our storyList
sl = new StoryList();
slc = new StoryListController(sl, null);
int oldSize = sl.getAllStories().size();
Story s = new Story("Book", "Dan Dude");
slc.addStory(s);
assertTrue("StoryList size didn't increase", oldSize < sl.getAllStories().size());
}
/**
* tests the getStoryAtPos function to test if story details can be retrieved
*/
public void testGetStoryWithObject() {
// add a story to our storyList
sl = new StoryList();
slc = new StoryListController(sl, null);
Story s = new Story("Book", "Dan Dude");
slc.addStory(s);
Story s2 = sl.getStoryAtPos(0);
assertTrue("Stories don't have same titles", s.getTitle().equals(s2.getTitle()));
assertTrue("Stories don't have same authors", s.getAuthor().equals(s2.getAuthor()));
}
/**
* tests the getTitle function, to see if a title is received
*/
public void testGetStoryWithTitle() {
// add a story to our storyList
sl = new StoryList();
slc = new StoryListController(sl, null);
Story s = new Story("Book", "Dan Dude");
slc.addStory(s);
String s2 = sl.getStoryAtPos(0).getTitle();
String s3 = sl.getStoryAtPos(0).getAuthor();
assertTrue("Stories don't have same titles", s.getTitle().equals(s2));
assertTrue("Stories don't have same authors", s.getAuthor().equals(s3));
}
/**
* tests to see whether a story set in a new position takes its place in the story list
*/
public void testSetStory() {
// add a story to our storyList
sl = new StoryList();
slc = new StoryListController(sl, null);
Story s = new Story("Book", "Dan Dude");
slc.addStory(s);
String author = sl.getStoryAtPos(0).getAuthor();
assertTrue(sl.getStoryAtPos(0).getAuthor().equals(author));
Story s2 = new Story("Bok", "Dude Dan");
slc.setStory(s2, 0);
assertTrue(sl.getStoryAtPos(0).getAuthor().equals(author));
}
/**
* tests the getStoryAtPos function which should return a certain story from a
* specific position in the storylist
*/
public void testGetStoryAtPos() {
// add a story to our storyList
sl = new StoryList();
slc = new StoryListController(sl, null);
Story s = new Story("Book", "Dan Dude");
slc.addStory(s);;
String author = sl.getStoryAtPos(0).getAuthor();
assertTrue(sl.getStoryAtPos(0).getAuthor().equals(author));
Story s2 = sl.getStoryAtPos(0);
assertTrue(s2.equals(s));
}
/**
* Tests whether a blank story (story with no parameters) can be made
*/
public void testCreateBlankStory() {
// add a story to our storyList
sl = new StoryList();
slc = new StoryListController(sl, null);
assertTrue(sl.getAllStories().size() == 0);
slc.createBlankStory();
assertTrue(sl.getAllStories().size() == 1);
}
/**
* test if the initialized screen with no stories does in fact return no stories
*/
public void testGetInitialListOfStories() {
sl = new StoryList();
slc = new StoryListController(sl, null);
assertNotNull("Inital story list is null", sl);
assertNotNull("Initial story list controller is null", slc);
assertNotNull(sl.getAllStories());
assertTrue("Initial list of stories wasn't 0", sl.getAllStories().size() == 0);
}
/**
* tests if new stories can be added to the story list with the addStory function
**/
public void testAddStoriesToList() {
Story s = new Story("A Dance With Dragons", "George R.R. Martin");
int oldSize = sl.getAllStories().size();
slc.addStory(s);
stories = sl.getAllStories();
assertTrue("Size of list of stories didn't increase when we added one",
oldSize < stories.size());
oldSize = stories.size();
s = new Story("A Game of Thrones", "George R.R. Martin");
slc.addStory(s);
stories = sl.getAllStories();
assertTrue("Size of list of stories didn't increase when we added a story",
oldSize < stories.size());
}
/**
* tests if by using the setStory function, more stories can be added to the storylist
*/
public void testSetStory2() {
Story s = new Story("The Winds of Winter", "George R.R. Martin");
Story s1 = new Story("A Storm of Swords", "George R.R. Martin");
Story s2 = new Story("A Clash of Kings", "George R.R. Martin");
slc.addStory(s);
slc.addStory(s1);
slc.addStory(s2);
int size = sl.getAllStories().size();
int index = size - 1;
assertTrue("We have zero stories in our story list", size > 0);
Story s3 = new Story("Book!", "Author??");
slc.setStory(s3, index);
assertTrue("The name of the book didn't change", sl.getAllStories().get(index)
.getTitle().equals(s3.getTitle()));
assertTrue("The author of the book didn't change", sl.getAllStories().get(index)
.getAuthor().equals(s3.getAuthor()));
}
}
| test-test/src/ualberta/g12/adventurecreator/test/StoryListControllerTestCases.java |
package ualberta.g12.adventurecreator.test;
import android.test.ActivityInstrumentationTestCase2;
import junit.framework.TestCase;
import ualberta.g12.adventurecreator.controllers.FragmentController;
import ualberta.g12.adventurecreator.controllers.StoryListController;
import ualberta.g12.adventurecreator.data.Fragment;
import ualberta.g12.adventurecreator.data.Story;
import ualberta.g12.adventurecreator.data.StoryList;
import ualberta.g12.adventurecreator.views.FragmentEditActivity;
import ualberta.g12.adventurecreator.views.MainActivity;
import java.util.List;
public class StoryListControllerTestCases extends ActivityInstrumentationTestCase2<MainActivity> {
private FragmentController fc;
private Fragment sf;
public StoryListControllerTestCases(){
super(MainActivity.class);
}
public StoryListControllerTestCases(Class<MainActivity> activityClass) {
super(MainActivity.class);
}
private StoryListController slc;
private StoryList sl;
private List<Story> stories;
@Override
protected void setUp() throws Exception {
super.setUp();
sl = new StoryList();
slc = new StoryListController(sl, null);
}
public void testSetUp() {
assertNotNull("StoryList was null.", sl);
assertNotNull("StoryListController was null", sl);
}
public void testAddStory() {
// add a story to our storyList
sl = new StoryList();
slc = new StoryListController(sl, null);
int oldSize = sl.getAllStories().size();
Story s = new Story("Book", "Dan Dude");
slc.addStory(s);
assertTrue("StoryList size didn't increase", oldSize < sl.getAllStories().size());
}
public void testGetStoryWithObject() {
// add a story to our storyList
sl = new StoryList();
slc = new StoryListController(sl, null);
Story s = new Story("Book", "Dan Dude");
slc.addStory(s);
Story s2 = sl.getStoryAtPos(0);
assertTrue("Stories don't have same titles", s.getTitle().equals(s2.getTitle()));
assertTrue("Stories don't have same authors", s.getAuthor().equals(s2.getAuthor()));
}
public void testGetStoryWithTitle() {
// add a story to our storyList
sl = new StoryList();
slc = new StoryListController(sl, null);
Story s = new Story("Book", "Dan Dude");
slc.addStory(s);
String s2 = sl.getStoryAtPos(0).getTitle();
String s3 = sl.getStoryAtPos(0).getAuthor();
assertTrue("Stories don't have same titles", s.getTitle().equals(s2));
assertTrue("Stories don't have same authors", s.getAuthor().equals(s3));
}
// tests setting a story
public void testSetStory() {
// add a story to our storyList
sl = new StoryList();
slc = new StoryListController(sl, null);
Story s = new Story("Book", "Dan Dude");
slc.addStory(s);
String author = sl.getStoryAtPos(0).getAuthor();
assertTrue(sl.getStoryAtPos(0).getAuthor().equals(author));
Story s2 = new Story("Bok", "Dude Dan");
slc.setStory(s2, 0);
assertTrue(sl.getStoryAtPos(0).getAuthor().equals(author));
}
// testing getting a story at Position
public void testGetStoryAtPos() {
// add a story to our storyList
sl = new StoryList();
slc = new StoryListController(sl, null);
Story s = new Story("Book", "Dan Dude");
slc.addStory(s);;
String author = sl.getStoryAtPos(0).getAuthor();
assertTrue(sl.getStoryAtPos(0).getAuthor().equals(author));
Story s2 = sl.getStoryAtPos(0);
assertTrue(s2.equals(s));
}
// testing getting a story at Position
public void testCreateBlankStory() {
// add a story to our storyList
sl = new StoryList();
slc = new StoryListController(sl, null);
assertTrue(sl.getAllStories().size() == 0);
slc.createBlankStory();
assertTrue(sl.getAllStories().size() == 1);
}
public void testGetInitialListOfStories() {
sl = new StoryList();
slc = new StoryListController(sl, null);
assertNotNull("Inital story list is null", sl);
assertNotNull("Initial story list controller is null", slc);
assertNotNull(sl.getAllStories());
assertTrue("Initial list of stories wasn't 0", sl.getAllStories().size() == 0);
}
public void testAddStoriesToList() {
Story s = new Story("A Dance With Dragons", "George R.R. Martin");
int oldSize = sl.getAllStories().size();
slc.addStory(s);
stories = sl.getAllStories();
assertTrue("Size of list of stories didn't increase when we added one",
oldSize < stories.size());
oldSize = stories.size();
s = new Story("A Game of Thrones", "George R.R. Martin");
slc.addStory(s);
stories = sl.getAllStories();
assertTrue("Size of list of stories didn't increase when we added a story",
oldSize < stories.size());
}
public void testSetStory2() {
Story s = new Story("The Winds of Winter", "George R.R. Martin");
Story s1 = new Story("A Storm of Swords", "George R.R. Martin");
Story s2 = new Story("A Clash of Kings", "George R.R. Martin");
slc.addStory(s);
slc.addStory(s1);
slc.addStory(s2);
int size = sl.getAllStories().size();
int index = size - 1;
assertTrue("We have zero stories in our story list", size > 0);
Story s3 = new Story("Book!", "Author??");
slc.setStory(s3, index);
assertTrue("The name of the book didn't change", sl.getAllStories().get(index)
.getTitle().equals(s3.getTitle()));
assertTrue("The author of the book didn't change", sl.getAllStories().get(index)
.getAuthor().equals(s3.getAuthor()));
}
}
| more docs
| test-test/src/ualberta/g12/adventurecreator/test/StoryListControllerTestCases.java | more docs | <ide><path>est-test/src/ualberta/g12/adventurecreator/test/StoryListControllerTestCases.java
<ide> import ualberta.g12.adventurecreator.controllers.FragmentController;
<ide> import ualberta.g12.adventurecreator.controllers.StoryListController;
<ide> import ualberta.g12.adventurecreator.data.Fragment;
<add>import ualberta.g12.adventurecreator.data.OfflineIOHelper;
<ide> import ualberta.g12.adventurecreator.data.Story;
<ide> import ualberta.g12.adventurecreator.data.StoryList;
<ide> import ualberta.g12.adventurecreator.views.FragmentEditActivity;
<ide>
<ide> import java.util.List;
<ide>
<add>/**
<add> * These test cases test that the StoryList controller behave to meet the needed requirements.
<add> * Function that will be tested are: addStory, setStory, and createBlankStory().
<add> * The storyList controller is made of getteres and setteres that control all variables
<add> * From the storyList.
<add> */
<add>
<ide> public class StoryListControllerTestCases extends ActivityInstrumentationTestCase2<MainActivity> {
<ide> private FragmentController fc;
<ide> private Fragment sf;
<ide> assertNotNull("StoryListController was null", sl);
<ide> }
<ide>
<add> /**
<add> * Creates a new story to the story list
<add> */
<ide> public void testAddStory() {
<ide>
<ide> // add a story to our storyList
<ide> }
<ide>
<ide>
<add> /**
<add> * tests the getStoryAtPos function to test if story details can be retrieved
<add> */
<ide> public void testGetStoryWithObject() {
<ide>
<ide> // add a story to our storyList
<ide> assertTrue("Stories don't have same authors", s.getAuthor().equals(s2.getAuthor()));
<ide> }
<ide>
<add> /**
<add> * tests the getTitle function, to see if a title is received
<add> */
<ide> public void testGetStoryWithTitle() {
<ide>
<ide> // add a story to our storyList
<ide> assertTrue("Stories don't have same authors", s.getAuthor().equals(s3));
<ide> }
<ide>
<del> // tests setting a story
<add> /**
<add> * tests to see whether a story set in a new position takes its place in the story list
<add> */
<ide> public void testSetStory() {
<ide>
<ide> // add a story to our storyList
<ide>
<ide> }
<ide>
<del> // testing getting a story at Position
<add> /**
<add> * tests the getStoryAtPos function which should return a certain story from a
<add> * specific position in the storylist
<add> */
<ide> public void testGetStoryAtPos() {
<ide> // add a story to our storyList
<ide> sl = new StoryList();
<ide>
<ide> }
<ide>
<del> // testing getting a story at Position
<add> /**
<add> * Tests whether a blank story (story with no parameters) can be made
<add> */
<ide> public void testCreateBlankStory() {
<ide>
<ide> // add a story to our storyList
<ide>
<ide> }
<ide>
<add> /**
<add> * test if the initialized screen with no stories does in fact return no stories
<add> */
<ide> public void testGetInitialListOfStories() {
<ide> sl = new StoryList();
<ide> slc = new StoryListController(sl, null);
<ide> assertTrue("Initial list of stories wasn't 0", sl.getAllStories().size() == 0);
<ide> }
<ide>
<add> /**
<add> * tests if new stories can be added to the story list with the addStory function
<add> **/
<ide> public void testAddStoriesToList() {
<ide> Story s = new Story("A Dance With Dragons", "George R.R. Martin");
<ide> int oldSize = sl.getAllStories().size();
<ide> oldSize < stories.size());
<ide> }
<ide>
<add> /**
<add> * tests if by using the setStory function, more stories can be added to the storylist
<add> */
<ide> public void testSetStory2() {
<ide> Story s = new Story("The Winds of Winter", "George R.R. Martin");
<ide> Story s1 = new Story("A Storm of Swords", "George R.R. Martin"); |
|
Java | lgpl-2.1 | 1df3b8ae40c3bf878ea687b39734398dcda10296 | 0 | liujed/polyglot-eclipse,blue-systems-group/project.maybe.polyglot,xcv58/polyglot,xcv58/polyglot,xcv58/polyglot,liujed/polyglot-eclipse,xcv58/polyglot,liujed/polyglot-eclipse,blue-systems-group/project.maybe.polyglot,blue-systems-group/project.maybe.polyglot,liujed/polyglot-eclipse,blue-systems-group/project.maybe.polyglot | package jltools.frontend;
import jltools.ast.*;
import jltools.util.*;
/** A pass which runs a visitor. */
public class VisitorPass extends AbstractPass
{
Job job;
NodeVisitor v;
public VisitorPass(Job job) {
this(job, null);
}
public VisitorPass(Job job, NodeVisitor v) {
this.job = job;
this.v = v;
}
public void visitor(NodeVisitor v) {
this.v = v;
}
public NodeVisitor visitor() {
return v;
}
public boolean run() {
Node ast = job.ast();
if (ast == null) {
throw new InternalCompilerError("Null AST: did the parser run?");
}
if (v.begin()) {
ErrorQueue q = job.compiler().errorQueue();
int nErrsBefore = q.errorCount();
ast = ast.visit(v);
v.finish();
int nErrsAfter = q.errorCount();
job.ast(ast);
return (nErrsBefore == nErrsAfter);
// because, if they're equal, no new errors occured,
// so the run was successful.
}
return false;
}
public String toString() {
return v.getClass().getName() + "(" + job + ")";
}
}
| src/polyglot/frontend/VisitorPass.java | package jltools.frontend;
import jltools.ast.*;
import jltools.util.*;
/** A pass which runs a visitor. */
public class VisitorPass extends AbstractPass
{
Job job;
NodeVisitor v;
public VisitorPass(Job job) {
this(job, null);
}
public VisitorPass(Job job, NodeVisitor v) {
this.job = job;
this.v = v;
}
public void visitor(NodeVisitor v) {
this.v = v;
}
public NodeVisitor visitor() {
return v;
}
public boolean run() {
Node ast = job.ast();
if (ast == null) {
throw new InternalCompilerError("Null AST: did the parser run?");
}
ErrorQueue q = job.compiler().errorQueue();
int nErrsBefore = q.errorCount();
ast = ast.visit(v);
v.finish();
int nErrsAfter = q.errorCount();
job.ast(ast);
return (nErrsBefore == nErrsAfter);
// because, if they're equal, no new errors occured,
// so the run was successful.
}
public String toString() {
return v.getClass().getName() + "(" + job + ")";
}
}
| Call NodeVisitor.begin() before visiting ast.
| src/polyglot/frontend/VisitorPass.java | Call NodeVisitor.begin() before visiting ast. | <ide><path>rc/polyglot/frontend/VisitorPass.java
<ide> throw new InternalCompilerError("Null AST: did the parser run?");
<ide> }
<ide>
<del> ErrorQueue q = job.compiler().errorQueue();
<del> int nErrsBefore = q.errorCount();
<add> if (v.begin()) {
<add> ErrorQueue q = job.compiler().errorQueue();
<add> int nErrsBefore = q.errorCount();
<ide>
<del> ast = ast.visit(v);
<del> v.finish();
<add> ast = ast.visit(v);
<add> v.finish();
<ide>
<del> int nErrsAfter = q.errorCount();
<add> int nErrsAfter = q.errorCount();
<ide>
<del> job.ast(ast);
<add> job.ast(ast);
<ide>
<del> return (nErrsBefore == nErrsAfter);
<del> // because, if they're equal, no new errors occured,
<del> // so the run was successful.
<add> return (nErrsBefore == nErrsAfter);
<add> // because, if they're equal, no new errors occured,
<add> // so the run was successful.
<add> }
<add>
<add> return false;
<ide> }
<ide>
<ide> public String toString() { |
|
Java | bsd-3-clause | 6ccad59b73a46e0b41de88be03f61dd1647148e5 | 0 | fabricebouye/gw2-web-api-mapping,fabricebouye/gw2-web-api-mapping | /*
* Copyright (C) 2015 Fabrice Bouyé
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the BSD license. See the LICENSE file for details.
*/
package api.web.gw2.mapping.v2.skins;
import java.util.Arrays;
import java.util.Optional;
/**
* Utility class for skins.
* @author Fabrice Bouyé
*/
public enum SkinsUtils {
/**
* The unique instance of this class.
*/
INSTANCE;
/**
* Gets the skin type for given value.
* @param value The source value.
* @return A {@code SkinType} instance, never {@code null}.
* <br>If no corresponding value is found, {@code SkinType.UNKNOWN} is returned.
* @see SkinType
*/
public static SkinType findSkinType(final String value) {
final Optional<SkinType> resultOptional = Arrays.stream(SkinType.values())
.filter(toTest -> value != null && value.equalsIgnoreCase(toTest.value))
.findFirst();
final SkinType result = resultOptional.isPresent() ? resultOptional.get() : SkinType.UNKNOWN;
return result;
}
/**
* Gets the skin flag for given value.
* @param value The source value.
* @return A {@code SkinFlag} instance, never {@code null}.
* <br>If no corresponding value is found, {@code SkinFlag.UNKNOWN} is returned.
* @see SkinFlag
*/
public static SkinFlag findSkinFlag(final String value) {
final Optional<SkinFlag> resultOptional = Arrays.stream(SkinFlag.values())
.filter(toTest -> value != null && value.equalsIgnoreCase(toTest.value))
.findFirst();
final SkinFlag result = resultOptional.isPresent() ? resultOptional.get() : SkinFlag.UNKNOWN;
return result;
}
/**
* Gets the skin armor type for given value.
* @param value The source value.
* @return A {@code SkinArmorType} instance, never {@code null}.
* <br>If no corresponding value is found, {@code SkinArmorType.UNKNOWN} is returned.
* @see SkinArmorType
*/
public static SkinArmorType findSkinArmorType(final String value) {
final Optional<SkinArmorType> resultOptional = Arrays.stream(SkinArmorType.values())
.filter(toTest -> value != null && value.equalsIgnoreCase(toTest.value))
.findFirst();
final SkinArmorType result = resultOptional.isPresent() ? resultOptional.get() : SkinArmorType.UNKNOWN;
return result;
}
/**
* Gets the skin weapon type for given value.
* @param value The source value.
* @return A {@code SkinWeaponType} instance, never {@code null}.
* <br>If no corresponding value is found, {@code SkinWeaponType.UNKNOWN} is returned.
* @see SkinWeaponType
*/
public static SkinWeaponType findSkinWeaponType(final String value) {
final Optional<SkinWeaponType> resultOptional = Arrays.stream(SkinWeaponType.values())
.filter(toTest -> value != null && value.equalsIgnoreCase(toTest.value))
.findFirst();
final SkinWeaponType result = resultOptional.isPresent() ? resultOptional.get() : SkinWeaponType.UNKNOWN;
return result;
}
/**
* Gets the skin armor weight class for given value.
* @param value The source value.
* @return A {@code SkinArmorWeightClass} instance, never {@code null}.
* <br>If no corresponding value is found, {@code SkinArmorWeightClass.UNKNOWN} is returned.
* @see SkinArmorWeightClass
*/
public static SkinArmorWeightClass findSkinArmorWeightClass(final String value) {
final Optional<SkinArmorWeightClass> resultOptional = Arrays.stream(SkinArmorWeightClass.values())
.filter(toTest -> value != null && value.equalsIgnoreCase(toTest.value))
.findFirst();
final SkinArmorWeightClass result = resultOptional.isPresent() ? resultOptional.get() : SkinArmorWeightClass.UNKNOWN;
return result;
}
/**
* Gets the skin damage type for given value.
* @param value The source value.
* @return A {@code SkinWeaponDamageType} instance, never {@code null}.
* <br>If no corresponding value is found, {@code SkinWeaponDamageType.UNKNOWN} is returned.
* @see SkinWeaponDamageType
*/
public static SkinWeaponDamageType findSkinWeaponDamageType(final String value) {
final Optional<SkinWeaponDamageType> resultOptional = Arrays.stream(SkinWeaponDamageType.values())
.filter(toTest -> value != null && value.equalsIgnoreCase(toTest.value))
.findFirst();
final SkinWeaponDamageType result = resultOptional.isPresent() ? resultOptional.get() : SkinWeaponDamageType.UNKNOWN;
return result;
}
}
| src/api/web/gw2/mapping/v2/skins/SkinsUtils.java | /*
* Copyright (C) 2015 Fabrice Bouyé
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the BSD license. See the LICENSE file for details.
*/
package api.web.gw2.mapping.v2.skins;
import java.util.Arrays;
import java.util.Optional;
/**
* Utility class for skins.
* @author Fabrice Bouyé
*/
public enum SkinsUtils {
/**
* The unique instance of this class.
*/
INSTANCE;
/**
* Gets the skin type for given value.
* @param value The source value.
* @return A {@code SkinType} instance, never {@code null}.
* <br>If no corresponding value is found, {@code SkinType.UNKNOWN} is returned.
* @see SkinType
*/
public static SkinType findSkinType(final String value) {
final Optional<SkinType> resultOptional = Arrays.stream(SkinType.values())
.filter(toTest -> value != null && value.equalsIgnoreCase(toTest.value))
.findFirst();
final SkinType result = resultOptional.isPresent() ? resultOptional.get() : SkinType.UNKNOWN;
return result;
}
/**
* Gets the skin armor type for given value.
* @param value The source value.
* @return A {@code SkinArmorType} instance, never {@code null}.
* <br>If no corresponding value is found, {@code SkinArmorType.UNKNOWN} is returned.
* @see SkinArmorType
*/
public static SkinArmorType findSkinArmorType(final String value) {
final Optional<SkinArmorType> resultOptional = Arrays.stream(SkinArmorType.values())
.filter(toTest -> value != null && value.equalsIgnoreCase(toTest.value))
.findFirst();
final SkinArmorType result = resultOptional.isPresent() ? resultOptional.get() : SkinArmorType.UNKNOWN;
return result;
}
/**
* Gets the skin weapon type for given value.
* @param value The source value.
* @return A {@code SkinWeaponType} instance, never {@code null}.
* <br>If no corresponding value is found, {@code SkinWeaponType.UNKNOWN} is returned.
* @see SkinWeaponType
*/
public static SkinWeaponType findSkinWeaponType(final String value) {
final Optional<SkinWeaponType> resultOptional = Arrays.stream(SkinWeaponType.values())
.filter(toTest -> value != null && value.equalsIgnoreCase(toTest.value))
.findFirst();
final SkinWeaponType result = resultOptional.isPresent() ? resultOptional.get() : SkinWeaponType.UNKNOWN;
return result;
}
/**
* Gets the skin armor weight class for given value.
* @param value The source value.
* @return A {@code SkinArmorWeightClass} instance, never {@code null}.
* <br>If no corresponding value is found, {@code SkinArmorWeightClass.UNKNOWN} is returned.
* @see SkinArmorWeightClass
*/
public static SkinArmorWeightClass findSkinArmorWeightClass(final String value) {
final Optional<SkinArmorWeightClass> resultOptional = Arrays.stream(SkinArmorWeightClass.values())
.filter(toTest -> value != null && value.equalsIgnoreCase(toTest.value))
.findFirst();
final SkinArmorWeightClass result = resultOptional.isPresent() ? resultOptional.get() : SkinArmorWeightClass.UNKNOWN;
return result;
}
/**
* Gets the skin damage type for given value.
* @param value The source value.
* @return A {@code SkinWeaponDamageType} instance, never {@code null}.
* <br>If no corresponding value is found, {@code SkinWeaponDamageType.UNKNOWN} is returned.
* @see SkinWeaponDamageType
*/
public static SkinWeaponDamageType findSkinWeaponDamageType(final String value) {
final Optional<SkinWeaponDamageType> resultOptional = Arrays.stream(SkinWeaponDamageType.values())
.filter(toTest -> value != null && value.equalsIgnoreCase(toTest.value))
.findFirst();
final SkinWeaponDamageType result = resultOptional.isPresent() ? resultOptional.get() : SkinWeaponDamageType.UNKNOWN;
return result;
}
}
| Added factory method for v2/skins/SkinFlag.
| src/api/web/gw2/mapping/v2/skins/SkinsUtils.java | Added factory method for v2/skins/SkinFlag. | <ide><path>rc/api/web/gw2/mapping/v2/skins/SkinsUtils.java
<ide> .filter(toTest -> value != null && value.equalsIgnoreCase(toTest.value))
<ide> .findFirst();
<ide> final SkinType result = resultOptional.isPresent() ? resultOptional.get() : SkinType.UNKNOWN;
<add> return result;
<add> }
<add>
<add> /**
<add> * Gets the skin flag for given value.
<add> * @param value The source value.
<add> * @return A {@code SkinFlag} instance, never {@code null}.
<add> * <br>If no corresponding value is found, {@code SkinFlag.UNKNOWN} is returned.
<add> * @see SkinFlag
<add> */
<add> public static SkinFlag findSkinFlag(final String value) {
<add> final Optional<SkinFlag> resultOptional = Arrays.stream(SkinFlag.values())
<add> .filter(toTest -> value != null && value.equalsIgnoreCase(toTest.value))
<add> .findFirst();
<add> final SkinFlag result = resultOptional.isPresent() ? resultOptional.get() : SkinFlag.UNKNOWN;
<ide> return result;
<ide> }
<ide> |
|
Java | mit | e405cef5416c2f01a5b2bc438d32905791b9c036 | 0 | kocsenc/enterprise,kocsenc/enterprise,kocsenc/enterprise,kocsenc/enterprise | package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpStatus;
import utility.DBUtility;
import domain.User;
public class UserService {
private Connection connection;
public UserService() {
connection = DBUtility.getConnection();
}
public List<User> getAllUsers() {
List<User> users = new ArrayList<User>();
try {
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery("select * from User");
while (rs.next()) {
int uid = rs.getInt("uid");
String name = rs.getString("uname");
Double wallet = rs.getDouble("wallet");
String email = rs.getString("email");
User user = new User(uid,name,wallet,email);
users.add(user);
}
} catch (SQLException e) {
e.printStackTrace();
}
return users;
}
public User getUser(int id){
User user = null;
try{
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery("select * from User WHERE uid = " + id);
while (rs.next()) {
int uid = rs.getInt("uid");
String name = rs.getString("uname");
Double wallet = rs.getDouble("wallet");
String email = rs.getString("email");
user = new User(uid, name, wallet, email);
}
} catch (SQLException e) {
e.printStackTrace();
}
return user;
}
public List<User> getFriends(int id) {
List<User> users = new ArrayList<User>();
try {
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery("select * from Friends where friend1 = " + id + " or friend2 = " + id);
while (rs.next()) {
int uid1 = rs.getInt("friend1");
int uid2 = rs.getInt("friend2");
int friendID = 0;
//check which user is not you
if (uid1 == id) {
friendID = uid2;
} else {
friendID = uid1;
}
//Get user object from database, put it in list
Statement userStatement = connection.createStatement();
ResultSet userRS = userStatement.executeQuery("select * from User where uid = " + friendID);
while(userRS.next()) {
String name = userRS.getString("uname");
Double wallet = userRS.getDouble("wallet");
String email = userRS.getString("email");
User user = new User(friendID, name, wallet, email);
if (users.contains(user) == false) {
users.add(user);
}
}
}
} catch (SQLException e){
e.printStackTrace();
}
return users;
}
public List<User> getTrustedFriends(int id) {
List<User> users = new ArrayList<User>();
try {
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery("select * from Friends where friend1 = " + id + "or friend2 = " + id + "and trust = 1");
while (rs.next()) {
int uid1 = rs.getInt("friend1");
int uid2 = rs.getInt("friend2");
int friendID = 0;
//check which user is not you
if (uid1 == id) {
friendID = uid2;
} else {
friendID = uid1;
}
//Get user object from database, put it in list
Statement userStatement = connection.createStatement();
ResultSet userRS = userStatement.executeQuery("select * from User where uid = " + friendID);
String name = rs.getString("uname");
Double wallet = rs.getDouble("wallet");
String email = rs.getString("email");
User user = new User(friendID, name, wallet, email);
if (users.contains(user) == false) {
users.add(user);
}
}
} catch (SQLException e){
e.printStackTrace();
}
return users;
}
public ResponseEntity<String> addFriend(int id, int friend_id) throws SQLException{
PreparedStatement addFriendStatement = null;
try{
//connection.setAutoCommit(false);
String addFriendString = "INSERT INTO F_Req VALUES(NULL, ?, ?, false)";
addFriendStatement = connection.prepareStatement(addFriendString);
addFriendStatement.setInt(1, id);
addFriendStatement.setInt(2, friend_id);
addFriendStatement.executeUpdate();
} catch (SQLException e){
return new ResponseEntity<String>(HttpStatus.INTERNAL_SERVER_ERROR);
} finally {
if (addFriendStatement != null) {
addFriendStatement.close();
//connection.setAutoCommit(true);
return new ResponseEntity<String>(HttpStatus.CREATED);
}
//connection.setAutoCommit(true);
return new ResponseEntity<String>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
public ResponseEntity<String> trustFriend(int id, int friend_id) throws SQLException{
PreparedStatement trustFriendStatement = null;
try{
//connection.setAutoCommit(false);
String trustFriendString = "INSERT INTO F_Req VALUES(NULL, ?, ?, true)";
trustFriendStatement = connection.prepareStatement(trustFriendString);
trustFriendStatement.setInt(1, id);
trustFriendStatement.setInt(2, friend_id);
trustFriendStatement.executeUpdate();
} catch (SQLException e){
return new ResponseEntity<String>(HttpStatus.INTERNAL_SERVER_ERROR);
} finally {
if (trustFriendStatement != null) {
trustFriendStatement.close();
return new ResponseEntity<String>(HttpStatus.CREATED);
}
//connection.setAutoCommit(true);
return new ResponseEntity<String>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
public ResponseEntity<String> register(User user) throws SQLException{
PreparedStatement registerStatement = null;
try{
Statement IDstatement = connection.createStatement();
ResultSet rs = IDstatement.executeQuery("select * from User where email = " + user.getEmail());
int id = 0;
while (rs.next()) {
id = rs.getInt("uid");
}
if(id != 0){
return new ResponseEntity<String>(HttpStatus.CONFLICT);
}
else{
//connection.setAutoCommit(false);
String registerString = "INSERT INTO User VALUES(?, NULL, ?, test, 0.00)";
registerStatement = connection.prepareStatement(registerString);
registerStatement.setString(1, user.getName());
registerStatement.setString(2, user.getEmail());
registerStatement.executeUpdate();
}
} catch (SQLException e){
return new ResponseEntity<String>(HttpStatus.INTERNAL_SERVER_ERROR);
} finally {
if (registerStatement != null) {
registerStatement.close();
return new ResponseEntity<String>(HttpStatus.CREATED);
}
//connection.setAutoCommit(true);
return new ResponseEntity<String>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
} | api/src/main/java/dao/UserService.java | package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpStatus;
import utility.DBUtility;
import domain.User;
public class UserService {
private Connection connection;
public UserService() {
connection = DBUtility.getConnection();
}
public List<User> getAllUsers() {
List<User> users = new ArrayList<User>();
try {
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery("select * from User");
while (rs.next()) {
int uid = rs.getInt("uid");
String name = rs.getString("uname");
Double wallet = rs.getDouble("wallet");
String email = rs.getString("email");
User user = new User(uid,name,wallet,email);
users.add(user);
}
} catch (SQLException e) {
e.printStackTrace();
}
return users;
}
public User getUser(int id){
User user = null;
try{
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery("select * from User WHERE uid = " + id);
while (rs.next()) {
int uid = rs.getInt("uid");
String name = rs.getString("uname");
Double wallet = rs.getDouble("wallet");
String email = rs.getString("email");
user = new User(uid, name, wallet, email);
}
} catch (SQLException e) {
e.printStackTrace();
}
return user;
}
public List<User> getFriends(int id) {
List<User> users = new ArrayList<User>();
try {
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery("select * from Friends where friend1 = " + id + "or friend2 = " + id);
while (rs.next()) {
int uid1 = rs.getInt("friend1");
int uid2 = rs.getInt("friend2");
int friendID = 0;
//check which user is not you
if (uid1 == id) {
friendID = uid2;
} else {
friendID = uid1;
}
//Get user object from database, put it in list
Statement userStatement = connection.createStatement();
ResultSet userRS = userStatement.executeQuery("select * from User where uid = " + friendID);
String name = rs.getString("uname");
Double wallet = rs.getDouble("wallet");
String email = rs.getString("email");
User user = new User(friendID, name, wallet, email);
if (users.contains(user) == false) {
users.add(user);
}
}
} catch (SQLException e){
e.printStackTrace();
}
return users;
}
public List<User> getTrustedFriends(int id) {
List<User> users = new ArrayList<User>();
try {
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery("select * from Friends where friend1 = " + id + "or friend2 = " + id + "and trust = 1");
while (rs.next()) {
int uid1 = rs.getInt("friend1");
int uid2 = rs.getInt("friend2");
int friendID = 0;
//check which user is not you
if (uid1 == id) {
friendID = uid2;
} else {
friendID = uid1;
}
//Get user object from database, put it in list
Statement userStatement = connection.createStatement();
ResultSet userRS = userStatement.executeQuery("select * from User where uid = " + friendID);
String name = rs.getString("uname");
Double wallet = rs.getDouble("wallet");
String email = rs.getString("email");
User user = new User(friendID, name, wallet, email);
if (users.contains(user) == false) {
users.add(user);
}
}
} catch (SQLException e){
e.printStackTrace();
}
return users;
}
public ResponseEntity<String> addFriend(int id, int friend_id) throws SQLException{
PreparedStatement addFriendStatement = null;
try{
//connection.setAutoCommit(false);
String addFriendString = "INSERT INTO F_Req VALUES(NULL, ?, ?, false)";
addFriendStatement = connection.prepareStatement(addFriendString);
addFriendStatement.setInt(1, id);
addFriendStatement.setInt(2, friend_id);
addFriendStatement.executeUpdate();
} catch (SQLException e){
return new ResponseEntity<String>(HttpStatus.INTERNAL_SERVER_ERROR);
} finally {
if (addFriendStatement != null) {
addFriendStatement.close();
//connection.setAutoCommit(true);
return new ResponseEntity<String>(HttpStatus.CREATED);
}
//connection.setAutoCommit(true);
return new ResponseEntity<String>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
public ResponseEntity<String> trustFriend(int id, int friend_id) throws SQLException{
PreparedStatement trustFriendStatement = null;
try{
//connection.setAutoCommit(false);
String trustFriendString = "INSERT INTO F_Req VALUES(NULL, ?, ?, true)";
trustFriendStatement = connection.prepareStatement(trustFriendString);
trustFriendStatement.setInt(1, id);
trustFriendStatement.setInt(2, friend_id);
trustFriendStatement.executeUpdate();
} catch (SQLException e){
return new ResponseEntity<String>(HttpStatus.INTERNAL_SERVER_ERROR);
} finally {
if (trustFriendStatement != null) {
trustFriendStatement.close();
return new ResponseEntity<String>(HttpStatus.CREATED);
}
//connection.setAutoCommit(true);
return new ResponseEntity<String>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
public ResponseEntity<String> register(User user) throws SQLException{
PreparedStatement registerStatement = null;
try{
Statement IDstatement = connection.createStatement();
ResultSet rs = IDstatement.executeQuery("select * from User where email = " + user.getEmail());
int id = 0;
while (rs.next()) {
id = rs.getInt("uid");
}
if(id != 0){
return new ResponseEntity<String>(HttpStatus.CONFLICT);
}
else{
//connection.setAutoCommit(false);
String registerString = "INSERT INTO User VALUES(?, NULL, ?, test, 0.00)";
registerStatement = connection.prepareStatement(registerString);
registerStatement.setString(1, user.getName());
registerStatement.setString(2, user.getEmail());
registerStatement.executeUpdate();
}
} catch (SQLException e){
return new ResponseEntity<String>(HttpStatus.INTERNAL_SERVER_ERROR);
} finally {
if (registerStatement != null) {
registerStatement.close();
return new ResponseEntity<String>(HttpStatus.CREATED);
}
//connection.setAutoCommit(true);
return new ResponseEntity<String>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
} | fixed get friends
| api/src/main/java/dao/UserService.java | fixed get friends | <ide><path>pi/src/main/java/dao/UserService.java
<ide> List<User> users = new ArrayList<User>();
<ide> try {
<ide> Statement statement = connection.createStatement();
<del> ResultSet rs = statement.executeQuery("select * from Friends where friend1 = " + id + "or friend2 = " + id);
<add> ResultSet rs = statement.executeQuery("select * from Friends where friend1 = " + id + " or friend2 = " + id);
<add> while (rs.next()) {
<add> int uid1 = rs.getInt("friend1");
<add> int uid2 = rs.getInt("friend2");
<add> int friendID = 0;
<add>
<add> //check which user is not you
<add> if (uid1 == id) {
<add> friendID = uid2;
<add> } else {
<add> friendID = uid1;
<add> }
<add>
<add> //Get user object from database, put it in list
<add> Statement userStatement = connection.createStatement();
<add> ResultSet userRS = userStatement.executeQuery("select * from User where uid = " + friendID);
<add> while(userRS.next()) {
<add> String name = userRS.getString("uname");
<add> Double wallet = userRS.getDouble("wallet");
<add> String email = userRS.getString("email");
<add> User user = new User(friendID, name, wallet, email);
<add> if (users.contains(user) == false) {
<add> users.add(user);
<add> }
<add> }
<add> }
<add> } catch (SQLException e){
<add> e.printStackTrace();
<add> }
<add>
<add> return users;
<add>}
<add>
<add>
<add>public List<User> getTrustedFriends(int id) {
<add> List<User> users = new ArrayList<User>();
<add> try {
<add> Statement statement = connection.createStatement();
<add> ResultSet rs = statement.executeQuery("select * from Friends where friend1 = " + id + "or friend2 = " + id + "and trust = 1");
<ide> while (rs.next()) {
<ide> int uid1 = rs.getInt("friend1");
<ide> int uid2 = rs.getInt("friend2");
<ide> return users;
<ide> }
<ide>
<del>
<del>public List<User> getTrustedFriends(int id) {
<del> List<User> users = new ArrayList<User>();
<del> try {
<del> Statement statement = connection.createStatement();
<del> ResultSet rs = statement.executeQuery("select * from Friends where friend1 = " + id + "or friend2 = " + id + "and trust = 1");
<del> while (rs.next()) {
<del> int uid1 = rs.getInt("friend1");
<del> int uid2 = rs.getInt("friend2");
<del> int friendID = 0;
<del>
<del> //check which user is not you
<del> if (uid1 == id) {
<del> friendID = uid2;
<del> } else {
<del> friendID = uid1;
<del> }
<del>
<del> //Get user object from database, put it in list
<del> Statement userStatement = connection.createStatement();
<del> ResultSet userRS = userStatement.executeQuery("select * from User where uid = " + friendID);
<del> String name = rs.getString("uname");
<del> Double wallet = rs.getDouble("wallet");
<del> String email = rs.getString("email");
<del> User user = new User(friendID, name, wallet, email);
<del> if (users.contains(user) == false) {
<del> users.add(user);
<del> }
<del> }
<del> } catch (SQLException e){
<del> e.printStackTrace();
<del> }
<del>
<del> return users;
<del>}
<del>
<ide> public ResponseEntity<String> addFriend(int id, int friend_id) throws SQLException{
<ide> PreparedStatement addFriendStatement = null;
<ide> try{ |
|
Java | agpl-3.0 | 27404aeae1bf02c59c3b639934de3261872845ed | 0 | torakiki/sejda | /*
* Copyright 2018 by Eduard Weissmann ([email protected]).
*
* This file is part of the Sejda source code
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.sejda.impl.sambox.component;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.sejda.impl.sambox.util.PageLabelUtils;
import org.sejda.model.outline.CatalogPageLabelsPolicy;
import org.sejda.sambox.pdmodel.PDDocument;
import org.sejda.sambox.pdmodel.common.PDPageLabelRange;
import org.sejda.sambox.pdmodel.common.PDPageLabels;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Merges multiple /Catalog /PageLabels definitions, from multiple docs, into one.
*/
public class CatalogPageLabelsMerger {
private static final Logger LOG = LoggerFactory.getLogger(CatalogPageLabelsMerger.class);
private int totalPages = 0;
private PDPageLabels mergedPageLabels = new PDPageLabels();
private final CatalogPageLabelsPolicy policy;
public CatalogPageLabelsMerger(CatalogPageLabelsPolicy policy) {
this.policy = policy;
if (policy == CatalogPageLabelsPolicy.DISCARD) {
mergedPageLabels = null;
}
}
public void add(PDDocument doc, Set<Integer> pagesToImport) {
if (policy == CatalogPageLabelsPolicy.DISCARD) {
return;
}
try {
PDPageLabels docLabels = doc.getDocumentCatalog().getPageLabels();
if (docLabels == null) {
docLabels = new PDPageLabels();
}
if (pagesToImport.size() < doc.getNumberOfPages()) {
// not all pages are being imported
// first update doc's page labels and remove pages not being imported
List<Integer> pagesToRemove = computePagesToRemove(doc, pagesToImport);
docLabels = PageLabelUtils.removePages(docLabels, pagesToRemove, doc.getNumberOfPages());
}
for (Map.Entry<Integer, PDPageLabelRange> entry : docLabels.getLabels().entrySet()) {
PDPageLabelRange range = entry.getValue();
// the page index in the original doc
int pageIndex = entry.getKey();
// new page index: old page index + number of pages we merged so far (from other docs)
int newPageIndex = pageIndex + totalPages;
// Hmm, handle start (logicalPage)? This would probably be wrong for Intro (romans) + Chapter 1 (arabic)
// but might be right for Chapter 1 (arabic) + Chapter 2 (arabic)
// not sure what to do, defer for later
// if(range.hasStart()) {
// range.setStart(range.getStart() + totalPages);
// }
mergedPageLabels.setLabelItem(newPageIndex, range);
}
} catch (Exception ex) {
LOG.warn("An error occurred retrieving /PageLabels of document {}, will not be merged", doc);
} finally {
// always advance the total number of pages
totalPages += pagesToImport.size();
}
}
private static List<Integer> computePagesToRemove(PDDocument doc, Set<Integer> pagesToImport) {
if (doc.getNumberOfPages() == pagesToImport.size()) {
return new ArrayList<>();
}
List<Integer> pagesToRemove = new ArrayList<>();
for (int i = 1; i <= doc.getNumberOfPages(); i++) {
if (!pagesToImport.contains(i)) {
pagesToRemove.add(i);
}
}
return pagesToRemove;
}
public boolean hasPageLabels() {
return mergedPageLabels != null;
}
public PDPageLabels getMergedPageLabels() {
return mergedPageLabels;
}
}
| sejda-sambox/src/main/java/org/sejda/impl/sambox/component/CatalogPageLabelsMerger.java | /*
* Copyright 2018 by Eduard Weissmann ([email protected]).
*
* This file is part of the Sejda source code
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.sejda.impl.sambox.component;
import org.sejda.impl.sambox.util.PageLabelUtils;
import org.sejda.model.outline.CatalogPageLabelsPolicy;
import org.sejda.sambox.pdmodel.PDDocument;
import org.sejda.sambox.pdmodel.common.PDPageLabelRange;
import org.sejda.sambox.pdmodel.common.PDPageLabels;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.*;
/**
* Merges multiple /Catalog /PageLabels definitions, from multiple docs, into one.
*/
public class CatalogPageLabelsMerger {
private static final Logger LOG = LoggerFactory.getLogger(CatalogPageLabelsMerger.class);
private int totalPages = 0;
private PDPageLabels mergedPageLabels = new PDPageLabels();
private final CatalogPageLabelsPolicy policy;
public CatalogPageLabelsMerger(CatalogPageLabelsPolicy policy) {
this.policy = policy;
if(policy == CatalogPageLabelsPolicy.DISCARD) {
mergedPageLabels = null;
}
}
public void add(PDDocument doc, Set<Integer> pagesToImport) {
if(policy == CatalogPageLabelsPolicy.DISCARD) {
return;
}
try {
PDPageLabels docLabels = doc.getDocumentCatalog().getPageLabels();
if(docLabels == null) {
docLabels = new PDPageLabels();
}
if(pagesToImport.size() < doc.getNumberOfPages()) {
// not all pages are being imported
// first update doc's page labels and remove pages not being imported
List<Integer> pagesToRemove = computePagesToRemove(doc, pagesToImport);
docLabels = PageLabelUtils.removePages(docLabels, pagesToRemove, doc.getNumberOfPages());
}
for(Map.Entry<Integer, PDPageLabelRange> entry: docLabels.getLabels().entrySet()){
PDPageLabelRange range = entry.getValue();
// the page index in the original doc
int pageIndex = entry.getKey();
// new page index: old page index + number of pages we merged so far (from other docs)
int newPageIndex = pageIndex + totalPages;
// Hmm, handle start (logicalPage)? This would probably be wrong for Intro (romans) + Chapter 1 (arabic)
// but might be right for Chapter 1 (arabic) + Chapter 2 (arabic)
// not sure what to do, defer for later
// if(range.hasStart()) {
// range.setStart(range.getStart() + totalPages);
//}
mergedPageLabels.setLabelItem(newPageIndex, range);
}
} catch (Exception ex) {
LOG.warn("An error occurred retrieving /PageLabels of document {}, will not be merged", doc);
} finally {
// always advance the total number of pages
totalPages += pagesToImport.size();
}
}
private static List<Integer> computePagesToRemove(PDDocument doc, Set<Integer> pagesToImport) {
if(doc.getNumberOfPages() == pagesToImport.size()) {
return new ArrayList<>();
}
List<Integer> pagesToRemove = new ArrayList<>();
for(int i = 1; i <= doc.getNumberOfPages(); i++) {
if(!pagesToImport.contains(i)) {
pagesToRemove.add(i);
}
}
return pagesToRemove;
}
public boolean hasPageLabels() {
return mergedPageLabels != null;
}
public PDPageLabels getMergedPageLabels() {
return mergedPageLabels;
}
}
| fixed imports
| sejda-sambox/src/main/java/org/sejda/impl/sambox/component/CatalogPageLabelsMerger.java | fixed imports | <ide><path>ejda-sambox/src/main/java/org/sejda/impl/sambox/component/CatalogPageLabelsMerger.java
<ide>
<ide> package org.sejda.impl.sambox.component;
<ide>
<add>import java.util.ArrayList;
<add>import java.util.List;
<add>import java.util.Map;
<add>import java.util.Set;
<add>
<ide> import org.sejda.impl.sambox.util.PageLabelUtils;
<ide> import org.sejda.model.outline.CatalogPageLabelsPolicy;
<ide> import org.sejda.sambox.pdmodel.PDDocument;
<ide> import org.sejda.sambox.pdmodel.common.PDPageLabels;
<ide> import org.slf4j.Logger;
<ide> import org.slf4j.LoggerFactory;
<del>
<del>import java.io.IOException;
<del>import java.util.*;
<ide>
<ide> /**
<ide> * Merges multiple /Catalog /PageLabels definitions, from multiple docs, into one.
<ide> public CatalogPageLabelsMerger(CatalogPageLabelsPolicy policy) {
<ide> this.policy = policy;
<ide>
<del> if(policy == CatalogPageLabelsPolicy.DISCARD) {
<add> if (policy == CatalogPageLabelsPolicy.DISCARD) {
<ide> mergedPageLabels = null;
<ide> }
<ide> }
<ide>
<ide> public void add(PDDocument doc, Set<Integer> pagesToImport) {
<del> if(policy == CatalogPageLabelsPolicy.DISCARD) {
<add> if (policy == CatalogPageLabelsPolicy.DISCARD) {
<ide> return;
<ide> }
<ide>
<ide> try {
<ide> PDPageLabels docLabels = doc.getDocumentCatalog().getPageLabels();
<del> if(docLabels == null) {
<add> if (docLabels == null) {
<ide> docLabels = new PDPageLabels();
<ide> }
<ide>
<del> if(pagesToImport.size() < doc.getNumberOfPages()) {
<add> if (pagesToImport.size() < doc.getNumberOfPages()) {
<ide> // not all pages are being imported
<ide> // first update doc's page labels and remove pages not being imported
<ide> List<Integer> pagesToRemove = computePagesToRemove(doc, pagesToImport);
<ide> docLabels = PageLabelUtils.removePages(docLabels, pagesToRemove, doc.getNumberOfPages());
<ide> }
<ide>
<del> for(Map.Entry<Integer, PDPageLabelRange> entry: docLabels.getLabels().entrySet()){
<add> for (Map.Entry<Integer, PDPageLabelRange> entry : docLabels.getLabels().entrySet()) {
<ide> PDPageLabelRange range = entry.getValue();
<ide>
<ide> // the page index in the original doc
<ide> // but might be right for Chapter 1 (arabic) + Chapter 2 (arabic)
<ide> // not sure what to do, defer for later
<ide> // if(range.hasStart()) {
<del> // range.setStart(range.getStart() + totalPages);
<del> //}
<add> // range.setStart(range.getStart() + totalPages);
<add> // }
<ide>
<ide> mergedPageLabels.setLabelItem(newPageIndex, range);
<ide> }
<ide> }
<ide>
<ide> private static List<Integer> computePagesToRemove(PDDocument doc, Set<Integer> pagesToImport) {
<del> if(doc.getNumberOfPages() == pagesToImport.size()) {
<add> if (doc.getNumberOfPages() == pagesToImport.size()) {
<ide> return new ArrayList<>();
<ide> }
<ide>
<ide> List<Integer> pagesToRemove = new ArrayList<>();
<del> for(int i = 1; i <= doc.getNumberOfPages(); i++) {
<del> if(!pagesToImport.contains(i)) {
<add> for (int i = 1; i <= doc.getNumberOfPages(); i++) {
<add> if (!pagesToImport.contains(i)) {
<ide> pagesToRemove.add(i);
<ide> }
<ide> } |
|
JavaScript | mit | 3f54e3b52634ab384d4afbfe72860c635cde70b7 | 0 | muhammadghazali/ghanoz-json,muhammadghazali/ghanoz-json | /**
* A middleware to expose the MongoDB connection
*/
var MongoClient = require('mongodb').MongoClient;
var mongoUtils = require('./../utils/db/mongo');
var openedDb = null;
/**
* Connect to MongoDB
*
* @param {Function} cb callback function
*/
function connect (cb) {
MongoClient.connect(mongoUtils.mongoURL, {
auto_reconnect: true,
poolSize: 100
}, function (err, db) {
if (err)
cb(err);
else if (db)
cb(null, db);
});
}
/**
* Get MongoDB connection
*
* @param {Object} req HTTP request object
* @param {Object} res HTTP response object
* @param {Function} next callback function
*/
function getDbConnection (req, res, next) {
connect(function (err, db) {
if (err)
res.send(500, 'Sorry, internal Error, please try again later');
else {
openedDb = db;
req.mongodb = db;
next();
}
});
}
/**
* Attach MongoDB connection
*
* @param {Object} req HTTP request object
* @param {Function} next callback function
*/
function passDbConnection (req, next) {
req.mongodb = openedDb;
next();
}
// expose the middleware
module.exports.mongoConnection = function () {
return function (req, res, next) {
if (openedDb === null) {
getDbConnection(req, res, next);
} else {
passDbConnection(req, next);
}
};
}; | app/middlewares/mongoconnection.js | /**
* A middleware to expose the MongoDB connection
*/
var MongoClient = require('mongodb').MongoClient;
var mongoUtils = require('./../utils/db/mongo');
var openedDb = null;
/**
* Connect to MongoDB
*
* @param {Function} cb callback function
*/
function connect (cb) {
MongoClient.connect(mongoUtils.mongoURL, {
auto_reconnect: true,
poolSize: 100
}, function (err, db) {
if (err)
cb(err);
else if (db)
cb(null, db);
});
}
// expose the middleware
module.exports.mongoConnection = function () {
return function (req, res, next) {
if (openedDb === null) {
connect(function (err, db) {
if (err)
res.send(500, 'Sorry, internal Error, please try again later');
else {
openedDb = db;
req.mongodb = db;
next();
}
});
} else {
req.mongodb = openedDb;
next();
}
};
}; | Passed the incoming arguments
| app/middlewares/mongoconnection.js | Passed the incoming arguments | <ide><path>pp/middlewares/mongoconnection.js
<ide> });
<ide> }
<ide>
<add>/**
<add> * Get MongoDB connection
<add> *
<add> * @param {Object} req HTTP request object
<add> * @param {Object} res HTTP response object
<add> * @param {Function} next callback function
<add> */
<add>function getDbConnection (req, res, next) {
<add>
<add> connect(function (err, db) {
<add> if (err)
<add> res.send(500, 'Sorry, internal Error, please try again later');
<add> else {
<add> openedDb = db;
<add> req.mongodb = db;
<add> next();
<add> }
<add> });
<add>}
<add>
<add>/**
<add> * Attach MongoDB connection
<add> *
<add> * @param {Object} req HTTP request object
<add> * @param {Function} next callback function
<add> */
<add>function passDbConnection (req, next) {
<add> req.mongodb = openedDb;
<add> next();
<add>}
<add>
<ide> // expose the middleware
<ide> module.exports.mongoConnection = function () {
<ide>
<ide> return function (req, res, next) {
<ide> if (openedDb === null) {
<del> connect(function (err, db) {
<del> if (err)
<del> res.send(500, 'Sorry, internal Error, please try again later');
<del> else {
<del> openedDb = db;
<del> req.mongodb = db;
<del> next();
<del> }
<del> });
<add> getDbConnection(req, res, next);
<ide> } else {
<del> req.mongodb = openedDb;
<del> next();
<add> passDbConnection(req, next);
<ide> }
<ide> };
<ide> }; |
|
JavaScript | agpl-3.0 | 61b538633f24776ff45d8e2c4b98a1e186451de3 | 0 | ONLYOFFICE/sdkjs,ONLYOFFICE/sdkjs,ONLYOFFICE/sdkjs,ONLYOFFICE/sdkjs,ONLYOFFICE/sdkjs | /*
* (c) Copyright Ascensio System SIA 2010-2019
*
* This program is a free software product. You can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License (AGPL)
* version 3 as published by the Free Software Foundation. In accordance with
* Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
* that Ascensio System SIA expressly excludes the warranty of non-infringement
* of any third-party rights.
*
* This program is distributed WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For
* details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
*
* You can contact Ascensio System SIA at 20A-12 Ernesta Birznieka-Upisha
* street, Riga, Latvia, EU, LV-1050.
*
* The interactive user interfaces in modified source and object code versions
* of the Program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU AGPL version 3.
*
* Pursuant to Section 7(b) of the License you must retain the original Product
* logo when distributing the program. Pursuant to Section 7(e) we decline to
* grant you any rights under trademark law for use of our trademarks.
*
* All the Product's GUI elements, including illustrations and icon sets, as
* well as technical writing content are licensed under the terms of the
* Creative Commons Attribution-ShareAlike 4.0 International. See the License
* terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
*
*/
"use strict";
(/**
* @param {Window} window
* @param {undefined} undefined
*/
function(window, undefined) {
/*
* Import
* -----------------------------------------------------------------------------
*/
var c_oAscFormatPainterState = AscCommon.c_oAscFormatPainterState;
var AscBrowser = AscCommon.AscBrowser;
var CColor = AscCommon.CColor;
var cBoolLocal = AscCommon.cBoolLocal;
var History = AscCommon.History;
var asc = window["Asc"];
var asc_applyFunction = AscCommonExcel.applyFunction;
var asc_round = asc.round;
var asc_typeof = asc.typeOf;
var asc_CMM = AscCommonExcel.asc_CMouseMoveData;
var asc_CPrintPagesData = AscCommonExcel.CPrintPagesData;
var c_oTargetType = AscCommonExcel.c_oTargetType;
var c_oAscError = asc.c_oAscError;
var c_oAscCleanOptions = asc.c_oAscCleanOptions;
var c_oAscSelectionDialogType = asc.c_oAscSelectionDialogType;
var c_oAscMouseMoveType = asc.c_oAscMouseMoveType;
var c_oAscPopUpSelectorType = asc.c_oAscPopUpSelectorType;
var c_oAscAsyncAction = asc.c_oAscAsyncAction;
var c_oAscFontRenderingModeType = asc.c_oAscFontRenderingModeType;
var c_oAscAsyncActionType = asc.c_oAscAsyncActionType;
var g_clipboardExcel = AscCommonExcel.g_clipboardExcel;
function WorkbookCommentsModel(handlers, aComments) {
this.workbook = {handlers: handlers};
this.aComments = aComments;
}
WorkbookCommentsModel.prototype.getId = function() {
return null;
};
WorkbookCommentsModel.prototype.getMergedByCell = function() {
return null;
};
function WorksheetViewSettings() {
this.header = {
style: [// Header colors
{ // kHeaderDefault
background: new CColor(241, 241, 241), border: new CColor(213, 213, 213), color: new CColor(54, 54, 54)
}, { // kHeaderActive
background: new CColor(193, 193, 193), border: new CColor(146, 146, 146), color: new CColor(54, 54, 54)
}, { // kHeaderHighlighted
background: new CColor(223, 223, 223), border: new CColor(175, 175, 175), color: new CColor(101, 106, 112)
}], cornerColor: new CColor(193, 193, 193)
};
this.cells = {
defaultState: {
background: new CColor(255, 255, 255), border: new CColor(202, 202, 202)
}, padding: -1 /*px horizontal padding*/
};
this.activeCellBorderColor = new CColor(72, 121, 92);
this.activeCellBorderColor2 = new CColor(255, 255, 255, 1);
this.findFillColor = new CColor(255, 238, 128, 1);
// Цвет закрепленных областей
this.frozenColor = new CColor(105, 119, 62, 1);
// Число знаков для математической информации
this.mathMaxDigCount = 9;
var cnv = document.createElement("canvas");
cnv.width = 2;
cnv.height = 2;
var ctx = cnv.getContext("2d");
ctx.clearRect(0, 0, 2, 2);
ctx.fillStyle = "#000";
ctx.fillRect(0, 0, 1, 1);
ctx.fillRect(1, 1, 1, 1);
this.ptrnLineDotted1 = ctx.createPattern(cnv, "repeat");
this.halfSelection = false;
return this;
}
/**
* Widget for displaying and editing Workbook object
* -----------------------------------------------------------------------------
* @param {AscCommonExcel.Workbook} model Workbook
* @param {AscCommonExcel.asc_CEventsController} controller Events controller
* @param {HandlersList} handlers Events handlers for WorkbookView events
* @param {Element} elem Container element
* @param {Element} inputElem Input element for top line editor
* @param {Object} Api
* @param {CCollaborativeEditing} collaborativeEditing
* @param {c_oAscFontRenderingModeType} fontRenderingMode
*
* @constructor
* @memberOf Asc
*/
function WorkbookView(model, controller, handlers, elem, inputElem, Api, collaborativeEditing, fontRenderingMode) {
this.defaults = {
scroll: {
widthPx: 14, heightPx: 14
}, worksheetView: new WorksheetViewSettings()
};
this.model = model;
this.enableKeyEvents = true;
this.controller = controller;
this.handlers = handlers;
this.wsViewHandlers = null;
this.element = elem;
this.input = inputElem;
this.Api = Api;
this.collaborativeEditing = collaborativeEditing;
this.lastSendInfoRange = null;
this.oSelectionInfo = null;
this.canUpdateAfterShiftUp = false; // Нужно ли обновлять информацию после отпускания Shift
this.keepType = false;
this.timerId = null;
this.timerEnd = false;
//----- declaration -----
this.isInit = false;
this.canvas = undefined;
this.canvasOverlay = undefined;
this.canvasGraphic = undefined;
this.canvasGraphicOverlay = undefined;
this.wsActive = -1;
this.wsMustDraw = false; // Означает, что мы выставили активный, но не отрисовали его
this.wsViews = [];
this.cellEditor = undefined;
this.fontRenderingMode = null;
this.lockDraw = false; // Lock отрисовки на некоторое время
this.isCellEditMode = false;
this.isShowComments = true;
this.isShowSolved = true;
this.formulasList = []; // Список всех формул
this.lastFPos = -1; // Последняя позиция формулы
this.lastFNameLength = ''; // Последний кусок формулы
this.skipHelpSelector = false; // Пока true - не показываем окно подсказки
// Константы для подстановке формулы (что не нужно добавлять скобки)
this.arrExcludeFormulas = [];
this.fReplaceCallback = null; // Callback для замены текста
// Фонт, который выставлен в DrawingContext, он должен быть один на все DrawingContext-ы
this.m_oFont = AscCommonExcel.g_oDefaultFormat.Font.clone();
// Теперь у нас 2 FontManager-а на весь документ + 1 для автофигур (а не на каждом листе свой)
this.fmgrGraphics = []; // FontManager for draw (1 для обычного + 1 для поворотного текста)
this.fmgrGraphics.push(new AscFonts.CFontManager({mode:"cell"})); // Для обычного
this.fmgrGraphics.push(new AscFonts.CFontManager({mode:"cell"})); // Для поворотного
this.fmgrGraphics.push(new AscFonts.CFontManager()); // Для автофигур
this.fmgrGraphics.push(new AscFonts.CFontManager({mode:"cell"})); // Для измерений
this.fmgrGraphics[0].Initialize(true); // IE memory enable
this.fmgrGraphics[1].Initialize(true); // IE memory enable
this.fmgrGraphics[2].Initialize(true); // IE memory enable
this.fmgrGraphics[3].Initialize(true); // IE memory enable
this.buffers = {};
this.drawingCtx = undefined;
this.overlayCtx = undefined;
this.drawingGraphicCtx = undefined;
this.overlayGraphicCtx = undefined;
this.shapeCtx = null;
this.shapeOverlayCtx = null;
this.mainGraphics = undefined;
this.stringRender = undefined;
this.trackOverlay = null;
this.autoShapeTrack = null;
this.stateFormatPainter = c_oAscFormatPainterState.kOff;
this.rangeFormatPainter = null;
this.selectionDialogMode = false;
this.dialogAbsName = false;
this.dialogSheetName = false;
this.copyActiveSheet = -1;
this.lastActiveSheet = -1;
// Комментарии для всего документа
this.cellCommentator = null;
// Флаг о подписке на эвенты о смене позиции документа (скролл) для меню
this.isDocumentPlaceChangedEnabled = false;
// Максимальная ширина числа из 0,1,2...,9, померенная в нормальном шрифте(дефалтовый для книги) в px(целое)
// Ecma-376 Office Open XML Part 1, пункт 18.3.1.13
this.maxDigitWidth = 0;
//-----------------------
this.MobileTouchManager = null;
this.defNameAllowCreate = true;
this._init(fontRenderingMode);
this.autoCorrectStore = null;//объект для хранения параметров иконки авторазвертывания таблиц
this.cutIdSheet = null;
return this;
}
WorkbookView.prototype._init = function(fontRenderingMode) {
var self = this;
// Init font managers rendering
// Изначально мы инициализируем c_oAscFontRenderingModeType.hintingAndSubpixeling
this.setFontRenderingMode(fontRenderingMode, /*isInit*/true);
// add style
var _head = document.getElementsByTagName('head')[0];
var style0 = document.createElement('style');
style0.type = 'text/css';
style0.innerHTML = ".block_elem { position:absolute;padding:0;margin:0; }";
_head.appendChild(style0);
// create canvas
if (null != this.element) {
this.element.innerHTML = '<div id="ws-canvas-outer">\
<canvas id="ws-canvas"></canvas>\
<canvas id="ws-canvas-overlay"></canvas>\
<canvas id="ws-canvas-graphic"></canvas>\
<canvas id="ws-canvas-graphic-overlay"></canvas>\
<canvas id="id_target_cursor" class="block_elem" width="1" height="1"\
style="width:2px;height:13px;display:none;z-index:9;"></canvas>\
</div>';
this.canvas = document.getElementById("ws-canvas");
this.canvasOverlay = document.getElementById("ws-canvas-overlay");
this.canvasGraphic = document.getElementById("ws-canvas-graphic");
this.canvasGraphicOverlay = document.getElementById("ws-canvas-graphic-overlay");
}
this.buffers.main = new asc.DrawingContext({
canvas: this.canvas, units: 0/*px*/, fmgrGraphics: this.fmgrGraphics, font: this.m_oFont
});
this.buffers.overlay = new asc.DrawingContext({
canvas: this.canvasOverlay, units: 0/*px*/, fmgrGraphics: this.fmgrGraphics, font: this.m_oFont
});
this.buffers.mainGraphic = new asc.DrawingContext({
canvas: this.canvasGraphic, units: 0/*px*/, fmgrGraphics: this.fmgrGraphics, font: this.m_oFont
});
this.buffers.overlayGraphic = new asc.DrawingContext({
canvas: this.canvasGraphicOverlay, units: 0/*px*/, fmgrGraphics: this.fmgrGraphics, font: this.m_oFont
});
this.drawingCtx = this.buffers.main;
this.overlayCtx = this.buffers.overlay;
this.drawingGraphicCtx = this.buffers.mainGraphic;
this.overlayGraphicCtx = this.buffers.overlayGraphic;
this.shapeCtx = new AscCommon.CGraphics();
this.shapeOverlayCtx = new AscCommon.CGraphics();
this.mainGraphics = new AscCommon.CGraphics();
this.trackOverlay = new AscCommon.COverlay();
this.trackOverlay.IsCellEditor = true;
this.autoShapeTrack = new AscCommon.CAutoshapeTrack();
this.shapeCtx.m_oAutoShapesTrack = this.autoShapeTrack;
this.shapeCtx.m_oFontManager = this.fmgrGraphics[2];
this.shapeOverlayCtx.m_oFontManager = this.fmgrGraphics[2];
this.mainGraphics.m_oFontManager = this.fmgrGraphics[0];
// Обновляем размеры (чуть ниже, потому что должны быть проинициализированы ctx)
this._canResize();
this.stringRender = new AscCommonExcel.StringRender(this.buffers.main);
// Мерить нужно только со 100% и один раз для всего документа
this._calcMaxDigitWidth();
if (!window["NATIVE_EDITOR_ENJINE"]) {
// initialize events controller
this.controller.init(this, this.element, /*this.canvasOverlay*/ this.canvasGraphicOverlay, /*handlers*/{
"resize": function () {
self.resize.apply(self, arguments);
}, "initRowsCount": function () {
self._onInitRowsCount.apply(self, arguments);
}, "initColsCount": function () {
self._onInitColsCount.apply(self, arguments);
}, "scrollY": function () {
self._onScrollY.apply(self, arguments);
}, "scrollX": function () {
self._onScrollX.apply(self, arguments);
}, "changeSelection": function () {
self._onChangeSelection.apply(self, arguments);
}, "changeSelectionDone": function () {
self._onChangeSelectionDone.apply(self, arguments);
}, "changeSelectionRightClick": function () {
self._onChangeSelectionRightClick.apply(self, arguments);
}, "selectionActivePointChanged": function () {
self._onSelectionActivePointChanged.apply(self, arguments);
}, "updateWorksheet": function () {
self._onUpdateWorksheet.apply(self, arguments);
}, "resizeElement": function () {
self._onResizeElement.apply(self, arguments);
}, "resizeElementDone": function () {
self._onResizeElementDone.apply(self, arguments);
}, "changeFillHandle": function () {
self._onChangeFillHandle.apply(self, arguments);
}, "changeFillHandleDone": function () {
self._onChangeFillHandleDone.apply(self, arguments);
}, "moveRangeHandle": function () {
self._onMoveRangeHandle.apply(self, arguments);
}, "moveRangeHandleDone": function () {
self._onMoveRangeHandleDone.apply(self, arguments);
}, "moveResizeRangeHandle": function () {
self._onMoveResizeRangeHandle.apply(self, arguments);
}, "moveResizeRangeHandleDone": function () {
self._onMoveResizeRangeHandleDone.apply(self, arguments);
}, "editCell": function () {
self._onEditCell.apply(self, arguments);
}, "stopCellEditing": function () {
return self._onStopCellEditing.apply(self, arguments);
}, "isRestrictionComments": function () {
return self.Api.isRestrictionComments();
}, "empty": function () {
self._onEmpty.apply(self, arguments);
}, "canEnterCellRange": function () {
self.cellEditor.setFocus(false);
var ret = self.cellEditor.canEnterCellRange();
ret ? self.cellEditor.activateCellRange() : true;
return ret;
}, "enterCellRange": function () {
self.lockDraw = true;
self.skipHelpSelector = true;
self.cellEditor.setFocus(false);
self.getWorksheet().enterCellRange(self.cellEditor);
self.skipHelpSelector = false;
self.lockDraw = false;
}, "undo": function () {
self.undo.apply(self, arguments);
}, "redo": function () {
self.redo.apply(self, arguments);
}, "mouseDblClick": function () {
self._onMouseDblClick.apply(self, arguments);
}, "showNextPrevWorksheet": function () {
self._onShowNextPrevWorksheet.apply(self, arguments);
}, "setFontAttributes": function () {
self._onSetFontAttributes.apply(self, arguments);
}, "setCellFormat": function () {
self._onSetCellFormat.apply(self, arguments);
}, "selectColumnsByRange": function () {
self._onSelectColumnsByRange.apply(self, arguments);
}, "selectRowsByRange": function () {
self._onSelectRowsByRange.apply(self, arguments);
}, "save": function () {
self.Api.asc_Save();
}, "showCellEditorCursor": function () {
self._onShowCellEditorCursor.apply(self, arguments);
}, "print": function () {
self.Api.onPrint();
}, "addFunction": function () {
self.insertInCellEditor.apply(self, arguments);
}, "canvasClick": function () {
self.enableKeyEventsHandler(true);
}, "autoFiltersClick": function () {
self._onAutoFiltersClick.apply(self, arguments);
}, "commentCellClick": function () {
self._onCommentCellClick.apply(self, arguments);
}, "isGlobalLockEditCell": function () {
return self.collaborativeEditing.getGlobalLockEditCell();
}, "updateSelectionName": function () {
self._onUpdateSelectionName.apply(self, arguments);
}, "stopFormatPainter": function () {
self._onStopFormatPainter.apply(self, arguments);
}, "groupRowClick": function () {
return self._onGroupRowClick.apply(self, arguments);
},
// Shapes
"graphicObjectMouseDown": function () {
self._onGraphicObjectMouseDown.apply(self, arguments);
}, "graphicObjectMouseMove": function () {
self._onGraphicObjectMouseMove.apply(self, arguments);
}, "graphicObjectMouseUp": function () {
self._onGraphicObjectMouseUp.apply(self, arguments);
}, "graphicObjectMouseUpEx": function () {
self._onGraphicObjectMouseUpEx.apply(self, arguments);
}, "graphicObjectWindowKeyDown": function () {
return self._onGraphicObjectWindowKeyDown.apply(self, arguments);
}, "graphicObjectWindowKeyPress": function () {
return self._onGraphicObjectWindowKeyPress.apply(self, arguments);
}, "getGraphicsInfo": function () {
return self._onGetGraphicsInfo.apply(self, arguments);
}, "updateSelectionShape": function () {
return self._onUpdateSelectionShape.apply(self, arguments);
}, "canReceiveKeyPress": function () {
return self.getWorksheet().objectRender.controller.canReceiveKeyPress();
}, "stopAddShape": function () {
self.getWorksheet().objectRender.controller.checkEndAddShape();
},
// Frozen anchor
"moveFrozenAnchorHandle": function () {
self._onMoveFrozenAnchorHandle.apply(self, arguments);
}, "moveFrozenAnchorHandleDone": function () {
self._onMoveFrozenAnchorHandleDone.apply(self, arguments);
},
// AutoComplete
"showAutoComplete": function () {
self.showAutoComplete.apply(self, arguments);
}, "onContextMenu": function (event) {
self.handlers.trigger("asc_onContextMenu", event);
},
// DataValidation
"onDataValidation": function () {
if (self.oSelectionInfo && self.oSelectionInfo.dataValidation) {
self.handlers.trigger("asc_onValidationListMenu", self.oSelectionInfo.dataValidation.getListValues(self.model.getActiveWs()));
}
},
// FormatPainter
'isFormatPainter': function () {
return self.stateFormatPainter;
},
//calculate
'calculate': function () {
self.calculate.apply(self, arguments);
},
'changeFormatTableInfo': function () {
var table = self.getSelectionInfo().formatTableInfo;
return table && self.changeFormatTableInfo(table.tableName, Asc.c_oAscChangeTableStyleInfo.rowTotal, !table.lastRow);
},
//special paste
"hideSpecialPasteOptions": function () {
self.handlers.trigger("hideSpecialPasteOptions");
}
});
if (this.input && this.input.addEventListener) {
this.input.addEventListener("focus", function () {
self.input.isFocused = true;
if (!self.canEdit()) {
return;
}
self._onStopFormatPainter();
self.controller.setStrictClose(true);
self.cellEditor.callTopLineMouseup = true;
if (!self.getCellEditMode() && !self.controller.isFillHandleMode) {
self._onEditCell(/*isFocus*/true);
}
}, false);
this.input.addEventListener('keydown', function (event) {
if (self.isCellEditMode) {
self.handlers.trigger('asc_onInputKeyDown', event);
if (!event.defaultPrevented) {
self.cellEditor._onWindowKeyDown(event, true);
}
}
}, false);
}
this.Api.onKeyDown = function (event) {
self.controller._onWindowKeyDown(event);
if (self.isCellEditMode) {
self.cellEditor._onWindowKeyDown(event, false);
}
};
this.Api.onKeyPress = function (event) {
self.controller._onWindowKeyPress(event);
if (self.isCellEditMode) {
self.cellEditor._onWindowKeyPress(event);
}
};
this.Api.onKeyUp = function (event) {
self.controller._onWindowKeyUp(event);
if (self.isCellEditMode) {
self.cellEditor._onWindowKeyUp(event);
}
};
this.Api.Begin_CompositeInput = function () {
var oWSView = self.getWorksheet();
if (oWSView && oWSView.isSelectOnShape) {
if (oWSView.objectRender) {
oWSView.objectRender.Begin_CompositeInput();
}
return;
}
if (!self.isCellEditMode) {
self._onEditCell(false, true, undefined, true, function () {
self.cellEditor.Begin_CompositeInput();
});
} else {
self.cellEditor.Begin_CompositeInput();
}
};
this.Api.Replace_CompositeText = function (arrCharCodes) {
var oWSView = self.getWorksheet();
if(oWSView && oWSView.isSelectOnShape){
if(oWSView.objectRender){
oWSView.objectRender.Replace_CompositeText(arrCharCodes);
}
return;
}
if (self.isCellEditMode) {
self.cellEditor.Replace_CompositeText(arrCharCodes);
}
};
this.Api.End_CompositeInput = function () {
var oWSView = self.getWorksheet();
if(oWSView && oWSView.isSelectOnShape){
if(oWSView.objectRender){
oWSView.objectRender.End_CompositeInput();
}
return;
}
if (self.isCellEditMode) {
self.cellEditor.End_CompositeInput();
}
};
this.Api.Set_CursorPosInCompositeText = function (nPos) {
var oWSView = self.getWorksheet();
if(oWSView && oWSView.isSelectOnShape){
if(oWSView.objectRender){
oWSView.objectRender.Set_CursorPosInCompositeText(nPos);
}
return;
}
if (self.isCellEditMode) {
self.cellEditor.Set_CursorPosInCompositeText(nPos);
}
};
this.Api.Get_CursorPosInCompositeText = function () {
var res = 0;
var oWSView = self.getWorksheet();
if(oWSView && oWSView.isSelectOnShape){
if(oWSView.objectRender){
res = oWSView.objectRender.Get_CursorPosInCompositeText();
}
}
else if (self.isCellEditMode) {
res = self.cellEditor.Get_CursorPosInCompositeText();
}
return res;
};
this.Api.Get_MaxCursorPosInCompositeText = function () {
var res = 0; var oWSView = self.getWorksheet();
if(oWSView && oWSView.isSelectOnShape){
if(oWSView.objectRender){
res = oWSView.objectRender.Get_CursorPosInCompositeText();
}
}
else if (self.isCellEditMode) {
res = self.cellEditor.Get_MaxCursorPosInCompositeText();
}
return res;
};
this.Api.AddTextWithPr = function (familyName, arrCharCodes) {
var ws = self.getWorksheet();
if (ws && ws.isSelectOnShape) {
var textPr = new CTextPr();
textPr.RFonts = new CRFonts();
textPr.RFonts.Set_All(familyName, -1);
ws.objectRender.controller.addTextWithPr(new AscCommon.CUnicodeStringEmulator(arrCharCodes), textPr, true);
return;
}
if (!self.isCellEditMode) {
self._onEditCell(undefined, undefined, undefined, false, function () {
self.cellEditor.setTextStyle('fn', familyName);
self.cellEditor._addCharCodes(arrCharCodes);
});
} else {
self.cellEditor.setTextStyle('fn', familyName);
self.cellEditor._addCharCodes(arrCharCodes);
}
};
this.Api.beginInlineDropTarget = function (event) {
if (!self.controller.isMoveRangeMode) {
self.controller.isMoveRangeMode = true;
self.getWorksheet().dragAndDropRange = new Asc.Range(0, 0, 0, 0);
}
self.controller._onMouseMove(event);
};
this.Api.endInlineDropTarget = function (event) {
self.controller.isMoveRangeMode = false;
var ws = self.getWorksheet();
var newSelection = ws.activeMoveRange.clone();
ws._cleanSelectionMoveRange();
ws.dragAndDropRange = null;
self._onSetSelection(newSelection);
};
this.Api.isEnabledDropTarget = function () {
return !self.isCellEditMode;
};
AscCommon.InitBrowserInputContext(this.Api, "id_target_cursor");
this.model.dependencyFormulas.calcTree();
}
this.cellEditor =
new AscCommonExcel.CellEditor(this.element, this.input, this.fmgrGraphics, this.m_oFont, /*handlers*/{
"closed": function () {
self._onCloseCellEditor.apply(self, arguments);
}, "updated": function () {
self.Api.checkLastWork();
self._onUpdateCellEditor.apply(self, arguments);
}, "gotFocus": function (hasFocus) {
self.controller.setFocus(!hasFocus);
}, "updateFormulaEditMod": function () {
self.controller.setFormulaEditMode.apply(self.controller, arguments);
var ws = self.getWorksheet();
if (ws) {
if (!self.lockDraw) {
ws.cleanSelection();
}
for (var i in self.wsViews) {
self.wsViews[i].cleanFormulaRanges();
}
// ws.cleanFormulaRanges();
ws.setFormulaEditMode.apply(ws, arguments);
}
}, "updateEditorState": function (state) {
self.handlers.trigger("asc_onEditCell", state);
}, "isGlobalLockEditCell": function () {
return self.collaborativeEditing.getGlobalLockEditCell();
}, "updateFormulaEditModEnd": function () {
if (!self.lockDraw) {
self.getWorksheet().updateSelection();
}
}, "newRange": function (range, ws) {
if (!ws) {
self.getWorksheet().addFormulaRange(range);
} else {
self.getWorksheet(self.model.getWorksheetIndexByName(ws)).addFormulaRange(range);
}
}, "existedRange": function (range, ws) {
var editRangeSheet = ws ? self.model.getWorksheetIndexByName(ws) : self.lastActiveSheet;
if (-1 === editRangeSheet || editRangeSheet === self.wsActive) {
self.getWorksheet().activeFormulaRange(range);
} else {
self.getWorksheet(editRangeSheet).removeFormulaRange(range);
self.getWorksheet().addFormulaRange(range);
}
}, "updateUndoRedoChanged": function (bCanUndo, bCanRedo) {
self.handlers.trigger("asc_onCanUndoChanged", bCanUndo);
self.handlers.trigger("asc_onCanRedoChanged", bCanRedo);
}, "applyCloseEvent": function () {
self.controller._onWindowKeyDown.apply(self.controller, arguments);
}, "canEdit": function () {
return self.canEdit();
}, "getFormulaRanges": function () {
return (self.cellFormulaEnterWSOpen || self.getWorksheet()).getFormulaRanges();
}, "isActive": function () {
return self.isActive();
}, "getSelectionDialogMode": function () {
return self.selectionDialogMode;
}, "getCellFormulaEnterWSOpen": function () {
return self.cellFormulaEnterWSOpen;
}, "getActiveWS": function () {
return self.getWorksheet().model;
}, "setStrictClose": function (val) {
self.controller.setStrictClose(val);
}, "updateEditorSelectionInfo": function (info) {
self.handlers.trigger("asc_onEditorSelectionChanged", info);
}, "onContextMenu": function (event) {
self.handlers.trigger("asc_onContextMenu", event);
}, "updatedEditableFunction": function (fName) {
self.handlers.trigger("asc_onFormulaInfo", fName);
}
}, this.defaults.worksheetView.cells.padding);
this.wsViewHandlers = new AscCommonExcel.asc_CHandlersList(/*handlers*/{
"getViewMode": function () {
return self.Api.getViewMode();
}, "isRestrictionComments": function () {
return self.Api.isRestrictionComments();
}, "reinitializeScroll": function (type) {
self._onScrollReinitialize(type);
}, "selectionChanged": function () {
self._onWSSelectionChanged();
}, "selectionNameChanged": function () {
self._onSelectionNameChanged.apply(self, arguments);
}, "selectionMathInfoChanged": function () {
self._onSelectionMathInfoChanged.apply(self, arguments);
}, 'onFilterInfo': function (countFilter, countRecords) {
self.handlers.trigger("asc_onFilterInfo", countFilter, countRecords);
}, "onErrorEvent": function (errorId, level) {
self.handlers.trigger("asc_onError", errorId, level);
}, "slowOperation": function (isStart) {
(isStart ? self.Api.sync_StartAction : self.Api.sync_EndAction).call(self.Api,
c_oAscAsyncActionType.BlockInteraction, c_oAscAsyncAction.SlowOperation);
}, "setAutoFiltersDialog": function (arrVal) {
self.handlers.trigger("asc_onSetAFDialog", arrVal);
}, "selectionRangeChanged": function (val) {
self.handlers.trigger("asc_onSelectionRangeChanged", val);
}, "onRenameCellTextEnd": function (countFind, countReplace) {
self.handlers.trigger("asc_onRenameCellTextEnd", countFind, countReplace);
}, 'onStopFormatPainter': function () {
self._onStopFormatPainter();
}, 'getRangeFormatPainter': function () {
return self.rangeFormatPainter;
}, "onDocumentPlaceChanged": function () {
self._onDocumentPlaceChanged();
}, "updateSheetViewSettings": function () {
self.handlers.trigger("asc_onUpdateSheetViewSettings");
}, "onScroll": function (d) {
self.controller.scroll(d);
}, "getLockDefNameManagerStatus": function () {
return self.defNameAllowCreate;
}, 'isActive': function () {
return self.isActive();
}, "drawMobileSelection": function (color) {
if (self.MobileTouchManager) {
self.MobileTouchManager.CheckSelect(self.trackOverlay, color);
}
}, "showSpecialPasteOptions": function (val) {
self.handlers.trigger("asc_onShowSpecialPasteOptions", val);
if (!window['AscCommon'].g_specialPasteHelper.showSpecialPasteButton) {
window['AscCommon'].g_specialPasteHelper.showSpecialPasteButton = true;
}
}, 'checkLastWork': function () {
self.Api.checkLastWork();
}, "toggleAutoCorrectOptions": function (bIsShow, val) {
self.toggleAutoCorrectOptions(bIsShow, val);
}, "selectSearchingResults": function () {
return self.Api.selectSearchingResults;
}, "getMainGraphics": function () {
return self.mainGraphics;
}, "cleanCutData": function (bDrawSelection, bCleanBuffer) {
self.cleanCutData(bDrawSelection, bCleanBuffer);
}
});
this.model.handlers.add("cleanCellCache", function(wsId, oRanges, skipHeight) {
var ws = self.getWorksheetById(wsId, true);
if (ws) {
ws.updateRanges(oRanges, skipHeight);
}
});
this.model.handlers.add("changeWorksheetUpdate", function(wsId, val) {
var ws = self.getWorksheetById(wsId);
if (ws) {
ws.changeWorksheet("update", val);
}
});
this.model.handlers.add("showWorksheet", function(wsId) {
var wsModel = self.model.getWorksheetById(wsId), index;
if (wsModel) {
index = wsModel.getIndex();
self.showWorksheet(index, true);
}
});
this.model.handlers.add("setSelection", function() {
self._onSetSelection.apply(self, arguments);
});
this.model.handlers.add("getSelectionState", function() {
return self._onGetSelectionState.apply(self);
});
this.model.handlers.add("setSelectionState", function() {
self._onSetSelectionState.apply(self, arguments);
});
this.model.handlers.add("reInit", function() {
self.reInit.apply(self, arguments);
});
this.model.handlers.add("drawWS", function() {
self.drawWS.apply(self, arguments);
});
this.model.handlers.add("showDrawingObjects", function() {
self.onShowDrawingObjects.apply(self, arguments);
});
this.model.handlers.add("setCanUndo", function(bCanUndo) {
self.handlers.trigger("asc_onCanUndoChanged", bCanUndo);
});
this.model.handlers.add("setCanRedo", function(bCanRedo) {
self.handlers.trigger("asc_onCanRedoChanged", bCanRedo);
});
this.model.handlers.add("setDocumentModified", function(bIsModified) {
self.Api.onUpdateDocumentModified(bIsModified);
});
this.model.handlers.add("updateWorksheetByModel", function() {
self.updateWorksheetByModel.apply(self, arguments);
});
this.model.handlers.add("undoRedoAddRemoveRowCols", function(sheetId, type, range, bUndo) {
if (true === bUndo) {
if (AscCH.historyitem_Worksheet_AddRows === type) {
self.collaborativeEditing.removeRowsRange(sheetId, range.clone(true));
self.collaborativeEditing.undoRows(sheetId, range.r2 - range.r1 + 1);
} else if (AscCH.historyitem_Worksheet_RemoveRows === type) {
self.collaborativeEditing.addRowsRange(sheetId, range.clone(true));
self.collaborativeEditing.undoRows(sheetId, range.r2 - range.r1 + 1);
} else if (AscCH.historyitem_Worksheet_AddCols === type) {
self.collaborativeEditing.removeColsRange(sheetId, range.clone(true));
self.collaborativeEditing.undoCols(sheetId, range.c2 - range.c1 + 1);
} else if (AscCH.historyitem_Worksheet_RemoveCols === type) {
self.collaborativeEditing.addColsRange(sheetId, range.clone(true));
self.collaborativeEditing.undoCols(sheetId, range.c2 - range.c1 + 1);
}
} else {
if (AscCH.historyitem_Worksheet_AddRows === type) {
self.collaborativeEditing.addRowsRange(sheetId, range.clone(true));
self.collaborativeEditing.addRows(sheetId, range.r1, range.r2 - range.r1 + 1);
} else if (AscCH.historyitem_Worksheet_RemoveRows === type) {
self.collaborativeEditing.removeRowsRange(sheetId, range.clone(true));
self.collaborativeEditing.removeRows(sheetId, range.r1, range.r2 - range.r1 + 1);
} else if (AscCH.historyitem_Worksheet_AddCols === type) {
self.collaborativeEditing.addColsRange(sheetId, range.clone(true));
self.collaborativeEditing.addCols(sheetId, range.c1, range.c2 - range.c1 + 1);
} else if (AscCH.historyitem_Worksheet_RemoveCols === type) {
self.collaborativeEditing.removeColsRange(sheetId, range.clone(true));
self.collaborativeEditing.removeCols(sheetId, range.c1, range.c2 - range.c1 + 1);
}
}
});
this.model.handlers.add("undoRedoHideSheet", function(sheetId) {
self.showWorksheet(sheetId);
// Посылаем callback об изменении списка листов
self.Api.sheetsChanged();
});
this.model.handlers.add("updateSelection", function () {
if (!self.lockDraw) {
self.getWorksheet().updateSelection();
}
});
this.handlers.add("asc_onLockDefNameManager", function(reason) {
self.defNameAllowCreate = !(reason == Asc.c_oAscDefinedNameReason.LockDefNameManager);
});
this.handlers.add('addComment', function (id, data) {
self._onWSSelectionChanged();
self.handlers.trigger('asc_onAddComment', id, data);
});
this.handlers.add('removeComment', function (id) {
self._onWSSelectionChanged();
self.handlers.trigger('asc_onRemoveComment', id);
});
this.handlers.add('hiddenComments', function () {
return !self.isShowComments;
});
this.handlers.add('showSolved', function () {
return self.isShowSolved;
});
this.model.handlers.add("hideSpecialPasteOptions", function() {
self.handlers.trigger("asc_onHideSpecialPasteOptions");
});
this.model.handlers.add("toggleAutoCorrectOptions", function(bIsShow, val) {
self.toggleAutoCorrectOptions(bIsShow, val);
});
this.model.handlers.add("cleanCutData", function(bDrawSelection, bCleanBuffer) {
self.cleanCutData(bDrawSelection, bCleanBuffer);
});
this.model.handlers.add("updateGroupData", function() {
self.updateGroupData();
});
this.cellCommentator = new AscCommonExcel.CCellCommentator({
model: new WorkbookCommentsModel(this.handlers, this.model.aComments),
collaborativeEditing: this.collaborativeEditing,
draw: function() {
},
handlers: {
trigger: function() {
return false;
}
}
});
if (0 < this.model.aComments.length) {
this.handlers.trigger("asc_onAddComments", this.model.aComments);
}
this.initFormulasList();
this.fReplaceCallback = function() {
self._replaceCellTextCallback.apply(self, arguments);
};
return this;
};
WorkbookView.prototype.destroy = function() {
this.controller.destroy();
this.cellEditor.destroy();
return this;
};
WorkbookView.prototype._createWorksheetView = function(wsModel) {
return new AscCommonExcel.WorksheetView(this, wsModel, this.wsViewHandlers, this.buffers, this.stringRender, this.maxDigitWidth, this.collaborativeEditing, this.defaults.worksheetView);
};
WorkbookView.prototype._onSelectionNameChanged = function(name) {
this.handlers.trigger("asc_onSelectionNameChanged", name);
};
WorkbookView.prototype._onSelectionMathInfoChanged = function(info) {
this.handlers.trigger("asc_onSelectionMathChanged", info);
};
// Проверяет, сменили ли мы диапазон (для того, чтобы не отправлять одинаковую информацию о диапазоне)
WorkbookView.prototype._isEqualRange = function(range, isSelectOnShape) {
if (null === this.lastSendInfoRange) {
return false;
}
return this.lastSendInfoRange.isEqual(range) && this.lastSendInfoRangeIsSelectOnShape === isSelectOnShape;
};
WorkbookView.prototype._updateSelectionInfo = function () {
var ws = this.cellFormulaEnterWSOpen ? this.cellFormulaEnterWSOpen : this.getWorksheet();
this.oSelectionInfo = ws.getSelectionInfo();
this.lastSendInfoRange = ws.model.selectionRange.clone();
this.lastSendInfoRangeIsSelectOnShape = ws.getSelectionShape();
};
WorkbookView.prototype._onWSSelectionChanged = function(isSaving) {
this._updateSelectionInfo();
// При редактировании ячейки не нужно пересылать изменения
if (this.input && !this.getCellEditMode() && !this.selectionDialogMode) {
// Сами запретим заходить в строку формул, когда выделен shape
if (this.lastSendInfoRangeIsSelectOnShape) {
this.input.disabled = true;
this.input.value = '';
} else {
this.input.disabled = false;
this.input.value = this.oSelectionInfo.text;
}
}
this.handlers.trigger("asc_onSelectionChanged", this.oSelectionInfo);
this.handlers.trigger("asc_onSelectionEnd");
this._onInputMessage();
if (!isSaving) {
this.Api.cleanSpelling();
}
};
WorkbookView.prototype._onInputMessage = function () {
var title = null, message = null;
var dataValidation = this.oSelectionInfo && this.oSelectionInfo.dataValidation;
if (dataValidation && dataValidation.showInputMessage && !this.model.getActiveWs().getDisablePrompts()) {
title = dataValidation.promptTitle;
message = dataValidation.promt;
}
this.handlers.trigger("asc_onInputMessage", title, message);
};
WorkbookView.prototype._onScrollReinitialize = function (type) {
if (window["NATIVE_EDITOR_ENJINE"] || !type) {
return;
}
var ws = this.getWorksheet();
if (AscCommonExcel.c_oAscScrollType.ScrollHorizontal & type) {
this.controller.reinitScrollX(ws.getFirstVisibleCol(true), ws.getHorizontalScrollRange(), ws.getHorizontalScrollMax());
}
if (AscCommonExcel.c_oAscScrollType.ScrollVertical & type) {
this.controller.reinitScrollY(ws.getFirstVisibleRow(true), ws.getVerticalScrollRange(), ws.getVerticalScrollMax());
}
if (this.Api.isMobileVersion) {
this.MobileTouchManager.Resize();
}
};
WorkbookView.prototype._onInitRowsCount = function () {
var ws = this.getWorksheet();
if (ws._initRowsCount()) {
this._onScrollReinitialize(AscCommonExcel.c_oAscScrollType.ScrollVertical);
}
};
WorkbookView.prototype._onInitColsCount = function () {
var ws = this.getWorksheet();
if (ws._initColsCount()) {
this._onScrollReinitialize(AscCommonExcel.c_oAscScrollType.ScrollHorizontal);
}
};
WorkbookView.prototype._onScrollY = function(pos, initRowsCount) {
var ws = this.getWorksheet();
var delta = asc_round(pos - ws.getFirstVisibleRow(true));
if (delta !== 0) {
ws.scrollVertical(delta, this.cellEditor, initRowsCount);
}
};
WorkbookView.prototype._onScrollX = function(pos, initColsCount) {
var ws = this.getWorksheet();
var delta = asc_round(pos - ws.getFirstVisibleCol(true));
if (delta !== 0) {
ws.scrollHorizontal(delta, this.cellEditor, initColsCount);
}
};
WorkbookView.prototype._onSetSelection = function(range) {
var ws = this.getWorksheet();
ws._endSelectionShape();
ws.setSelection(range);
};
WorkbookView.prototype._onGetSelectionState = function() {
var res = null;
var ws = this.getWorksheet(null, true);
if (ws && AscCommon.isRealObject(ws.objectRender) && AscCommon.isRealObject(ws.objectRender.controller)) {
res = ws.objectRender.controller.getSelectionState();
}
return (res && res[0] && res[0].focus) ? res : null;
};
WorkbookView.prototype._onSetSelectionState = function(state) {
if (null !== state) {
var ws = this.getWorksheetById(state[0].worksheetId);
if (ws && ws.objectRender && ws.objectRender.controller) {
ws.objectRender.controller.setSelectionState(state);
ws.setSelectionShape(true);
ws._scrollToRange(ws.objectRender.getSelectedDrawingsRange());
ws.objectRender.showDrawingObjectsEx(true);
ws.objectRender.controller.updateOverlay();
ws.objectRender.controller.updateSelectionState();
}
// Селектим после выставления состояния
}
};
WorkbookView.prototype._onChangeSelection = function (isStartPoint, dc, dr, isCoord, isCtrl, callback) {
var ws = this.getWorksheet();
var t = this;
var d = isStartPoint ? ws.changeSelectionStartPoint(dc, dr, isCoord, isCtrl) :
ws.changeSelectionEndPoint(dc, dr, isCoord, isCoord && this.keepType);
if (!isCoord && !isStartPoint) {
// Выделение с зажатым shift
this.canUpdateAfterShiftUp = true;
}
this.keepType = isCoord;
if (isCoord && !this.timerEnd && this.timerId === null) {
this.timerId = setTimeout(function () {
var arrClose = [];
arrClose.push(new asc_CMM({type: c_oAscMouseMoveType.None}));
t.handlers.trigger("asc_onMouseMove", arrClose);
t._onUpdateCursor(AscCommonExcel.kCurCells);
t.timerId = null;
t.timerEnd = true;
},1000);
}
asc_applyFunction(callback, d);
};
// Окончание выделения
WorkbookView.prototype._onChangeSelectionDone = function(x, y, event) {
if (this.timerId !== null) {
clearTimeout(this.timerId);
this.timerId = null;
}
this.keepType = false;
if (this.selectionDialogMode) {
return;
}
var ws = this.getWorksheet();
ws.changeSelectionDone();
this._onSelectionNameChanged(ws.getSelectionName(/*bRangeText*/false));
// Проверим, нужно ли отсылать информацию о ячейке
var ar = ws.model.selectionRange.getLast();
var isSelectOnShape = ws.getSelectionShape();
if (!this._isEqualRange(ws.model.selectionRange, isSelectOnShape)) {
this._onWSSelectionChanged();
this._onSelectionMathInfoChanged(ws.getSelectionMathInfo());
}
// Нужно очистить поиск
this.model.cleanFindResults();
var ct = ws.getCursorTypeFromXY(x, y);
if (c_oTargetType.Hyperlink === ct.target && !this.controller.isFormulaEditMode) {
// Проверим замерженность
var isHyperlinkClick = false;
if(isSelectOnShape) {
var button = 0;
if(event) {
button = AscCommon.getMouseButton(event);
}
if(button === 0) {
isHyperlinkClick = true;
}
}
else if(ar.isOneCell()) {
isHyperlinkClick = true;
}
else {
var mergedRange = ws.model.getMergedByCell(ar.r1, ar.c1);
if (mergedRange && ar.isEqual(mergedRange)) {
isHyperlinkClick = true;
}
}
if (isHyperlinkClick && !this.timerEnd) {
if (false === ct.hyperlink.hyperlinkModel.getVisited() && !isSelectOnShape) {
ct.hyperlink.hyperlinkModel.setVisited(true);
if (ct.hyperlink.hyperlinkModel.Ref) {
ws._updateRange(ct.hyperlink.hyperlinkModel.Ref.getBBox0());
ws.draw();
}
}
switch (ct.hyperlink.asc_getType()) {
case Asc.c_oAscHyperlinkType.WebLink:
this.handlers.trigger("asc_onHyperlinkClick", ct.hyperlink.asc_getHyperlinkUrl());
break;
case Asc.c_oAscHyperlinkType.RangeLink:
// ToDo надо поправить отрисовку комментария для данной ячейки (с которой уходим)
this.handlers.trigger("asc_onHideComment");
this.Api._asc_setWorksheetRange(ct.hyperlink);
break;
}
}
}
this.timerEnd = false;
};
// Обработка нажатия правой кнопки мыши
WorkbookView.prototype._onChangeSelectionRightClick = function(dc, dr, target) {
var ws = this.getWorksheet();
ws.changeSelectionStartPointRightClick(dc, dr, target);
};
// Обработка движения в выделенной области
WorkbookView.prototype._onSelectionActivePointChanged = function(dc, dr, callback) {
var ws = this.getWorksheet();
var d = ws.changeSelectionActivePoint(dc, dr);
asc_applyFunction(callback, d);
};
WorkbookView.prototype._onUpdateWorksheet = function(x, y, ctrlKey, callback) {
var ws = this.getWorksheet(), ct = undefined;
var arrMouseMoveObjects = []; // Теперь это массив из объектов, над которыми курсор
var t = this;
//ToDo: включить определение target, если находимся в режиме редактирования ячейки.
if (x === undefined && y === undefined) {
ws.cleanHighlightedHeaders();
if (this.timerId === null) {
this.timerId = setTimeout(function () {
var arrClose = [];
arrClose.push(new asc_CMM({type: c_oAscMouseMoveType.None}));
t.handlers.trigger("asc_onMouseMove", arrClose);
t.timerId = null;
}, 1000);
}
} else {
ct = ws.getCursorTypeFromXY(x, y);
ct.coordX = x;
ct.coordY = y;
if (this.timerId !== null) {
clearTimeout(this.timerId);
this.timerId = null;
}
// Отправление эвента об удалении всего листа (именно удалении, т.к. если просто залочен, то не рисуем рамку вокруг)
if (undefined !== ct.userIdAllSheet) {
arrMouseMoveObjects.push(new asc_CMM({
type: c_oAscMouseMoveType.LockedObject,
x: AscCommon.AscBrowser.convertToRetinaValue(ct.lockAllPosLeft),
y: AscCommon.AscBrowser.convertToRetinaValue(ct.lockAllPosTop),
userId: ct.userIdAllSheet,
lockedObjectType: Asc.c_oAscMouseMoveLockedObjectType.Sheet
}));
} else {
// Отправление эвента о залоченности свойств всего листа (только если не удален весь лист)
if (undefined !== ct.userIdAllProps) {
arrMouseMoveObjects.push(new asc_CMM({
type: c_oAscMouseMoveType.LockedObject,
x: AscCommon.AscBrowser.convertToRetinaValue(ct.lockAllPosLeft),
y: AscCommon.AscBrowser.convertToRetinaValue(ct.lockAllPosTop),
userId: ct.userIdAllProps,
lockedObjectType: Asc.c_oAscMouseMoveLockedObjectType.TableProperties
}));
}
}
// Отправление эвента о наведении на залоченный объект
if (undefined !== ct.userId) {
arrMouseMoveObjects.push(new asc_CMM({
type: c_oAscMouseMoveType.LockedObject,
x: AscCommon.AscBrowser.convertToRetinaValue(ct.lockRangePosLeft),
y: AscCommon.AscBrowser.convertToRetinaValue(ct.lockRangePosTop),
userId: ct.userId,
lockedObjectType: Asc.c_oAscMouseMoveLockedObjectType.Range
}));
}
// Проверяем комментарии ячейки
if (ct.commentIndexes) {
arrMouseMoveObjects.push(new asc_CMM({
type: c_oAscMouseMoveType.Comment,
x: ct.commentCoords.dLeftPX,
reverseX: ct.commentCoords.dReverseLeftPX,
y: ct.commentCoords.dTopPX,
aCommentIndexes: ct.commentIndexes
}));
}
// Проверяем гиперссылку
if (ct.target === c_oTargetType.Hyperlink) {
if (!ctrlKey) {
arrMouseMoveObjects.push(new asc_CMM({
type: c_oAscMouseMoveType.Hyperlink,
x: AscCommon.AscBrowser.convertToRetinaValue(x),
y: AscCommon.AscBrowser.convertToRetinaValue(y),
hyperlink: ct.hyperlink
}));
} else {
ct.cursor = AscCommonExcel.kCurCells;
}
}
// проверяем фильтр
if (ct.target === c_oTargetType.FilterObject) {
if (ct.isPivot) {
//необходимо сгенерировать объект AutoFiltersOptions
} else {
var filterObj = ws.af_setDialogProp(ct.idFilter, true);
if(filterObj) {
arrMouseMoveObjects.push(new asc_CMM({
type: c_oAscMouseMoveType.Filter,
x: AscCommon.AscBrowser.convertToRetinaValue(x),
y: AscCommon.AscBrowser.convertToRetinaValue(y),
filter: filterObj
}));
}
}
}
/* Проверяем, может мы на никаком объекте (такая схема оказалась приемлимой
* для отдела разработки приложений)
*/
if (0 === arrMouseMoveObjects.length) {
// Отправляем эвент, что мы ни на какой области
arrMouseMoveObjects.push(new asc_CMM({type: c_oAscMouseMoveType.None}));
}
// Отсылаем эвент с объектами
this.handlers.trigger("asc_onMouseMove", arrMouseMoveObjects);
if (ct.target === c_oTargetType.MoveRange && ctrlKey && ct.cursor === "move") {
ct.cursor = "copy";
}
this._onUpdateCursor(ct.cursor);
if (ct.target === c_oTargetType.ColumnHeader || ct.target === c_oTargetType.RowHeader) {
ws.drawHighlightedHeaders(ct.col, ct.row);
} else {
ws.cleanHighlightedHeaders();
}
}
asc_applyFunction(callback, ct);
};
WorkbookView.prototype._onUpdateCursor = function (cursor) {
var newHtmlCursor = AscCommon.g_oHtmlCursor.value(cursor);
if (this.element.style.cursor !== newHtmlCursor) {
this.element.style.cursor = newHtmlCursor;
}
};
WorkbookView.prototype._onResizeElement = function(target, x, y) {
var arrMouseMoveObjects = [];
if (target.target === c_oTargetType.ColumnResize) {
arrMouseMoveObjects.push(this.getWorksheet().drawColumnGuides(target.col, x, y, target.mouseX));
} else if (target.target === c_oTargetType.RowResize) {
arrMouseMoveObjects.push(this.getWorksheet().drawRowGuides(target.row, x, y, target.mouseY));
}
/* Проверяем, может мы на никаком объекте (такая схема оказалась приемлимой
* для отдела разработки приложений)
*/
if (0 === arrMouseMoveObjects.length) {
// Отправляем эвент, что мы ни на какой области
arrMouseMoveObjects.push(new asc_CMM({type: c_oAscMouseMoveType.None}));
}
// Отсылаем эвент с объектами
this.handlers.trigger("asc_onMouseMove", arrMouseMoveObjects);
};
WorkbookView.prototype._onResizeElementDone = function(target, x, y, isResizeModeMove) {
var ws = this.getWorksheet();
if (isResizeModeMove) {
if (target.target === c_oTargetType.ColumnResize) {
ws.changeColumnWidth(target.col, x, target.mouseX);
} else if (target.target === c_oTargetType.RowResize) {
ws.changeRowHeight(target.row, y, target.mouseY);
}
window['AscCommon'].g_specialPasteHelper.SpecialPasteButton_Update_Position();
this._onDocumentPlaceChanged();
}
ws.draw();
// Отсылаем окончание смены размеров (в FF не срабатывало обычное движение)
this.handlers.trigger("asc_onMouseMove", [new asc_CMM({type: c_oAscMouseMoveType.None})]);
};
// Обработка автозаполнения
WorkbookView.prototype._onChangeFillHandle = function(x, y, callback, tableIndex) {
var ws = this.getWorksheet();
var d = ws.changeSelectionFillHandle(x, y, tableIndex);
asc_applyFunction(callback, d);
};
// Обработка окончания автозаполнения
WorkbookView.prototype._onChangeFillHandleDone = function(x, y, ctrlPress) {
var ws = this.getWorksheet();
ws.applyFillHandle(x, y, ctrlPress);
};
// Обработка перемещения диапазона
WorkbookView.prototype._onMoveRangeHandle = function(x, y, callback) {
var ws = this.getWorksheet();
var d = ws.changeSelectionMoveRangeHandle(x, y);
asc_applyFunction(callback, d);
};
// Обработка окончания перемещения диапазона
WorkbookView.prototype._onMoveRangeHandleDone = function(ctrlKey) {
var ws = this.getWorksheet();
ws.applyMoveRangeHandle(ctrlKey);
};
WorkbookView.prototype._onMoveResizeRangeHandle = function(x, y, target, callback) {
var ws = this.getWorksheet();
var d = ws.changeSelectionMoveResizeRangeHandle(x, y, target, this.cellEditor);
asc_applyFunction(callback, d);
};
WorkbookView.prototype._onMoveResizeRangeHandleDone = function(target) {
var ws = this.getWorksheet();
ws.applyMoveResizeRangeHandle(target);
};
// Frozen anchor
WorkbookView.prototype._onMoveFrozenAnchorHandle = function(x, y, target) {
var ws = this.getWorksheet();
ws.drawFrozenGuides(x, y, target);
};
WorkbookView.prototype._onMoveFrozenAnchorHandleDone = function(x, y, target) {
// Закрепляем область
var ws = this.getWorksheet();
ws.applyFrozenAnchor(x, y, target);
};
WorkbookView.prototype.showAutoComplete = function() {
var ws = this.getWorksheet();
var arrValues = ws.getCellAutoCompleteValues(ws.model.selectionRange.activeCell);
this.handlers.trigger('asc_onEntriesListMenu', arrValues);
};
WorkbookView.prototype._onAutoFiltersClick = function(idFilter) {
this.getWorksheet().af_setDialogProp(idFilter);
};
WorkbookView.prototype._onGroupRowClick = function(x, y, target, type) {
return this.getWorksheet().groupRowClick(x, y, target, type);
};
WorkbookView.prototype._onCommentCellClick = function(x, y) {
this.getWorksheet().cellCommentator.showCommentByXY(x, y);
};
WorkbookView.prototype._onUpdateSelectionName = function (forcibly) {
if (this.canUpdateAfterShiftUp || forcibly) {
this.canUpdateAfterShiftUp = false;
var ws = this.getWorksheet();
this._onSelectionNameChanged(ws.getSelectionName(/*bRangeText*/false));
}
};
WorkbookView.prototype._onStopFormatPainter = function() {
if (this.stateFormatPainter) {
this.formatPainter(c_oAscFormatPainterState.kOff);
}
};
// Shapes
WorkbookView.prototype._onGraphicObjectMouseDown = function(e, x, y) {
var ws = this.getWorksheet();
ws.objectRender.graphicObjectMouseDown(e, x, y);
};
WorkbookView.prototype._onGraphicObjectMouseMove = function(e, x, y) {
var ws = this.getWorksheet();
ws.objectRender.graphicObjectMouseMove(e, x, y);
};
WorkbookView.prototype._onGraphicObjectMouseUp = function(e, x, y) {
var ws = this.getWorksheet();
ws.objectRender.graphicObjectMouseUp(e, x, y);
};
WorkbookView.prototype._onGraphicObjectMouseUpEx = function(e, x, y) {
//var ws = this.getWorksheet();
//ws.objectRender.calculateCell(x, y);
};
WorkbookView.prototype._onGraphicObjectWindowKeyDown = function(e) {
var objectRender = this.getWorksheet().objectRender;
return (0 < objectRender.getSelectedGraphicObjects().length) ? objectRender.graphicObjectKeyDown(e) : false;
};
WorkbookView.prototype._onGraphicObjectWindowKeyPress = function(e) {
var objectRender = this.getWorksheet().objectRender;
return (0 < objectRender.getSelectedGraphicObjects().length) ? objectRender.graphicObjectKeyPress(e) : false;
};
WorkbookView.prototype._onGetGraphicsInfo = function(x, y) {
var ws = this.getWorksheet();
return ws.objectRender.checkCursorDrawingObject(x, y);
};
WorkbookView.prototype._onUpdateSelectionShape = function(isSelectOnShape) {
var ws = this.getWorksheet();
return ws.setSelectionShape(isSelectOnShape);
};
// Double click
WorkbookView.prototype._onMouseDblClick = function(x, y, isHideCursor, callback) {
var ws = this.getWorksheet();
var ct = ws.getCursorTypeFromXY(x, y);
if (ct.target === c_oTargetType.ColumnResize || ct.target === c_oTargetType.RowResize) {
if (ct.target === c_oTargetType.ColumnResize) {
ws.autoFitColumnsWidth(ct.col);
} else {
ws.autoFitRowHeight(ct.row, ct.row);
}
asc_applyFunction(callback);
} else {
if (ct.col >= 0 && ct.row >= 0) {
this.controller.setStrictClose(!ws._isCellNullText(ct.col, ct.row));
}
// In view mode or click on column | row | all | frozenMove | drawing object do not process
if (!this.canEdit() || c_oTargetType.ColumnHeader === ct.target || c_oTargetType.RowHeader === ct.target ||
c_oTargetType.Corner === ct.target || c_oTargetType.FrozenAnchorH === ct.target ||
c_oTargetType.FrozenAnchorV === ct.target || ws.objectRender.checkCursorDrawingObject(x, y)) {
asc_applyFunction(callback);
return;
}
// При dbl клике фокус выставляем в зависимости от наличия текста в ячейке
this._onEditCell(/*isFocus*/undefined, /*isClearCell*/undefined, /*isHideCursor*/isHideCursor, /*isQuickInput*/false);
}
};
WorkbookView.prototype._onWindowMouseUpExternal = function (event, x, y) {
this.controller._onWindowMouseUpExternal(event, x, y);
if (this.isCellEditMode) {
this.cellEditor._onWindowMouseUp(event, x, y);
}
};
WorkbookView.prototype._onEditCell = function(isFocus, isClearCell, isHideCursor, isQuickInput, callback) {
var t = this;
// Проверка глобального лока
if (this.collaborativeEditing.getGlobalLock() || this.controller.isResizeMode) {
return;
}
var ws = t.getWorksheet();
var activeCellRange = ws.getActiveCell(0, 0, false);
var selectionRange = ws.model.selectionRange.clone();
var activeWsModel = this.model.getActiveWs();
if (activeWsModel.inPivotTable(activeCellRange)) {
this.handlers.trigger("asc_onError", c_oAscError.ID.LockedCellPivot, c_oAscError.Level.NoCritical);
return;
}
var editFunction = function() {
t.setCellEditMode(true);
t.hideSpecialPasteButton();
ws.openCellEditor(t.cellEditor, /*cursorPos*/undefined, isFocus, isClearCell,
/*isHideCursor*/isHideCursor, /*isQuickInput*/isQuickInput, selectionRange);
t.input.disabled = false;
t.Api.cleanSpelling(true);
// Эвент на обновление состояния редактора
t.cellEditor._updateEditorState();
asc_applyFunction(callback, true);
};
var editLockCallback = function(res) {
if (!res) {
t.setCellEditMode(false);
t.controller.setStrictClose(false);
t.controller.setFormulaEditMode(false);
ws.setFormulaEditMode(false);
t.input.disabled = true;
// Выключаем lock для редактирования ячейки
t.collaborativeEditing.onStopEditCell();
t.cellEditor.close(false);
t._onWSSelectionChanged();
}
};
// Стартуем редактировать ячейку
activeCellRange = ws.expandActiveCellByFormulaArray(activeCellRange);
if (ws._isLockedCells(activeCellRange, /*subType*/null, editLockCallback)) {
editFunction();
}
};
WorkbookView.prototype._onStopCellEditing = function(cancel) {
return this.cellEditor.close(!cancel);
};
WorkbookView.prototype._onCloseCellEditor = function() {
var isCellEditMode = this.getCellEditMode();
this.setCellEditMode(false);
this.controller.setStrictClose(false);
this.controller.setFormulaEditMode(false);
if (-1 !== this.copyActiveSheet) {
var index = this.copyActiveSheet;
this.cellFormulaEnterWSOpen = null;
this.copyActiveSheet = -1;
if (index !== this.wsActive) {
this.showWorksheet(index);
}
}
var ws = this.getWorksheet();
ws.cleanSelection();
for (var i in this.wsViews) {
this.wsViews[i].setFormulaEditMode(false);
this.wsViews[i].cleanFormulaRanges();
}
ws.updateSelectionWithSparklines();
if (isCellEditMode) {
this.handlers.trigger("asc_onEditCell", Asc.c_oAscCellEditorState.editEnd);
}
// Обновляем состояние Undo/Redo
if (!this.cellEditor.getMenuEditorMode()) {
History._sendCanUndoRedo();
}
// Обновляем состояние информации
this._onWSSelectionChanged();
// Закрываем подбор формулы
if (-1 !== this.lastFPos) {
this.handlers.trigger('asc_onFormulaCompleteMenu', null);
this.lastFPos = -1;
this.lastFNameLength = 0;
}
this.handlers.trigger('asc_onFormulaInfo', null);
};
WorkbookView.prototype._onEmpty = function() {
this.getWorksheet().emptySelection(c_oAscCleanOptions.Text);
};
WorkbookView.prototype._onShowNextPrevWorksheet = function(direction) {
// Колличество листов
var countWorksheets = this.model.getWorksheetCount();
// Покажем следующий лист или предыдущий (если больше нет)
var i = this.wsActive + direction, ws;
while (i !== this.wsActive) {
if (0 > i) {
i = countWorksheets - 1;
} else if (i >= countWorksheets) {
i = 0;
}
ws = this.model.getWorksheet(i);
if (!ws.getHidden()) {
this.showWorksheet(i);
return true;
}
i += direction;
}
return false;
};
WorkbookView.prototype._onSetFontAttributes = function(prop) {
var val;
var selectionInfo = this.getWorksheet().getSelectionInfo().asc_getFont();
switch (prop) {
case "b":
val = !(selectionInfo.asc_getBold());
break;
case "i":
val = !(selectionInfo.asc_getItalic());
break;
case "u":
// ToDo для двойного подчеркивания нужно будет немного переделать схему
val = !(selectionInfo.asc_getUnderline());
val = val ? Asc.EUnderline.underlineSingle : Asc.EUnderline.underlineNone;
break;
case "s":
val = !(selectionInfo.asc_getStrikeout());
break;
}
return this.setFontAttributes(prop, val);
};
WorkbookView.prototype._onSetCellFormat = function (prop) {
var info = new Asc.asc_CFormatCellsInfo();
info.asc_setSymbol(AscCommon.g_oDefaultCultureInfo.LCID);
info.asc_setType(Asc.c_oAscNumFormatType.None);
var formats = AscCommon.getFormatCells(info);
this.setCellFormat(formats[prop]);
};
WorkbookView.prototype._onSelectColumnsByRange = function() {
this.getWorksheet()._selectColumnsByRange();
};
WorkbookView.prototype._onSelectRowsByRange = function() {
this.getWorksheet()._selectRowsByRange();
};
WorkbookView.prototype._onShowCellEditorCursor = function() {
// Показываем курсор
if (this.getCellEditMode()) {
this.cellEditor.showCursor();
}
};
WorkbookView.prototype._onDocumentPlaceChanged = function() {
if (this.isDocumentPlaceChangedEnabled) {
this.handlers.trigger("asc_onDocumentPlaceChanged");
}
};
WorkbookView.prototype.getCellStyles = function(width, height) {
return AscCommonExcel.generateStyles(width, height, this.model.CellStyles, this);
};
WorkbookView.prototype.getWorksheetById = function(id, onlyExist) {
var wsModel = this.model.getWorksheetById(id);
if (wsModel) {
return this.getWorksheet(wsModel.getIndex(), onlyExist);
}
return null;
};
/**
* @param {Number} [index]
* @param {Boolean} [onlyExist]
* @return {AscCommonExcel.WorksheetView}
*/
WorkbookView.prototype.getWorksheet = function(index, onlyExist) {
var wb = this.model;
var i = asc_typeof(index) === "number" && index >= 0 ? index : wb.getActive();
var ws = this.wsViews[i];
if (!ws && !onlyExist) {
ws = this.wsViews[i] = this._createWorksheetView(wb.getWorksheet(i));
ws._prepareComments();
ws._prepareDrawingObjects();
}
return ws;
};
WorkbookView.prototype.drawWorksheet = function () {
if (-1 === this.wsActive) {
return this.showWorksheet();
}
var ws = this.getWorksheet();
ws.draw();
ws.objectRender.controller.updateSelectionState();
ws.objectRender.controller.updateOverlay();
this._onScrollReinitialize(AscCommonExcel.c_oAscScrollType.ScrollVertical | AscCommonExcel.c_oAscScrollType.ScrollHorizontal);
};
/**
*
* @param index
* @param [bLockDraw]
* @returns {WorkbookView}
*/
WorkbookView.prototype.showWorksheet = function (index, bLockDraw) {
if (window["NATIVE_EDITOR_ENJINE"] && !window['IS_NATIVE_EDITOR'] && !window['DoctRendererMode']) {
return this;
}
// ToDo disable method for assembly
var ws, wb = this.model;
if (asc_typeof(index) !== "number" || 0 > index) {
index = wb.getActive();
}
if (index === this.wsActive) {
if (!bLockDraw) {
this.drawWorksheet();
}
return this;
}
var tmpWorksheet, selectionRange = null;
// Только если есть активный
if (-1 !== this.wsActive) {
ws = this.getWorksheet();
// Останавливаем ввод данных в редакторе ввода. Если в режиме ввода формул, то продолжаем работать с cellEditor'ом, чтобы можно было
// выбирать ячейки для формулы
if (this.getCellEditMode()) {
if (this.cellEditor && this.cellEditor.formulaIsOperator()) {
this.lastActiveSheet = this.wsActive;
if (!this.cellFormulaEnterWSOpen) {
this.copyActiveSheet = this.wsActive;
this.cellFormulaEnterWSOpen = ws;
} else {
ws.setFormulaEditMode(false);
}
} else {
this._onStopCellEditing();
}
}
// Делаем очистку селекта
ws.cleanSelection();
this.stopTarget(ws);
}
if (this.selectionDialogMode) {
// Когда идет выбор диапазона, то должны на закрываемом листе отменить выбор диапазона
tmpWorksheet = this.getWorksheet();
selectionRange = tmpWorksheet.model.selectionRange.getLast().clone(true);
tmpWorksheet.copySelection(false);
}
if (this.stateFormatPainter) {
// Должны отменить выбор на закрываемом листе
this.getWorksheet().formatPainter(c_oAscFormatPainterState.kOff);
}
if (index !== wb.getActive()) {
wb.setActive(index);
}
this.wsActive = index;
this.wsMustDraw = bLockDraw;
// Посылаем эвент о смене активного листа
this.handlers.trigger("asc_onActiveSheetChanged", this.wsActive);
this.handlers.trigger("asc_onHideComment");
ws = this.getWorksheet(index);
if (this.selectionDialogMode) {
// Когда идет выбор диапазона, то на показываемом листе должны выставить нужный режим
ws.copySelection(true, selectionRange);
this.handlers.trigger("asc_onSelectionRangeChanged", ws.getSelectionRangeValue());
}
// Мы делали resize или меняли zoom, но не перерисовывали данный лист (он был не активный)
if (ws.updateResize && ws.updateZoom) {
ws.changeZoomResize();
} else if (ws.updateResize) {
ws.resize(true, this.cellEditor);
} else if (ws.updateZoom) {
ws.changeZoom(true);
}
this.updateGroupData();
if (this.cellEditor && this.cellFormulaEnterWSOpen) {
if (ws === this.cellFormulaEnterWSOpen) {
this.cellFormulaEnterWSOpen.setFormulaEditMode(true);
this.cellEditor._showCanvas();
} else if (this.getCellEditMode() && this.cellEditor.isFormula()) {
this.cellFormulaEnterWSOpen.setFormulaEditMode(false);
/*скрываем cellEditor, в редактор добавляем %selected sheet name%+"!" */
this.cellEditor._hideCanvas();
ws.cleanSelection();
ws.setFormulaEditMode(true);
}
}
if (!bLockDraw) {
ws.draw();
}
if (this.stateFormatPainter) {
// Должны отменить выбор на закрываемом листе
this.getWorksheet().formatPainter(this.stateFormatPainter);
}
if (!bLockDraw) {
ws.objectRender.controller.updateSelectionState();
ws.objectRender.controller.updateOverlay();
}
if (!window["NATIVE_EDITOR_ENJINE"]) {
this._onSelectionNameChanged(ws.getSelectionName(/*bRangeText*/false));
this._onWSSelectionChanged();
this._onSelectionMathInfoChanged(ws.getSelectionMathInfo());
}
this._onScrollReinitialize(AscCommonExcel.c_oAscScrollType.ScrollVertical | AscCommonExcel.c_oAscScrollType.ScrollHorizontal);
// Zoom теперь на каждом листе одинаковый, не отправляем смену
//TODO при добавлении любого действия в историю (например добавление нового листа), мы можем его потом отменить с повощью опции авторазвертывания
this.toggleAutoCorrectOptions(null, true);
window['AscCommon'].g_specialPasteHelper.SpecialPasteButton_Hide();
return this;
};
WorkbookView.prototype.stopTarget = function(ws) {
if (null === ws && -1 !== this.wsActive) {
ws = this.getWorksheet(this.wsActive);
}
if (null !== ws && ws.objectRender && ws.objectRender.drawingDocument) {
ws.objectRender.drawingDocument.TargetEnd();
}
};
WorkbookView.prototype.updateWorksheetByModel = function() {
// ToDo Сделал небольшую заглушку с показом листа. Нужно как мне кажется перейти от wsViews на wsViewsId (хранить по id)
var oldActiveWs;
if (-1 !== this.wsActive) {
oldActiveWs = this.wsViews[this.wsActive];
}
//расставляем ws так как они идут в модели.
var oNewWsViews = [];
for (var i in this.wsViews) {
var item = this.wsViews[i];
if (null != item && null != this.model.getWorksheetById(item.model.getId())) {
oNewWsViews[item.model.getIndex()] = item;
}
}
this.wsViews = oNewWsViews;
var wsActive = this.model.getActive();
var newActiveWs = this.wsViews[wsActive];
if (undefined === newActiveWs || oldActiveWs !== newActiveWs) {
// Если сменили, то покажем
this.wsActive = -1;
this.showWorksheet(wsActive, true);
} else {
this.wsActive = wsActive;
}
};
WorkbookView.prototype._canResize = function() {
var isRetina = AscBrowser.isRetina;
var oldWidth = this.canvas.width;
var oldHeight = this.canvas.height;
var width, height, styleWidth, styleHeight;
width = styleWidth = this.element.offsetWidth - (this.Api.isMobileVersion ? 0 : this.defaults.scroll.widthPx);
height = styleHeight = this.element.offsetHeight - (this.Api.isMobileVersion ? 0 : this.defaults.scroll.heightPx);
if (isRetina) {
width = AscCommon.AscBrowser.convertToRetinaValue(width, true);
height = AscCommon.AscBrowser.convertToRetinaValue(height, true);
}
if (oldWidth === width && oldHeight === height && this.isInit) {
return false;
}
this.isInit = true;
this.canvas.width = this.canvasOverlay.width = this.canvasGraphic.width = this.canvasGraphicOverlay.width = width;
this.canvas.height = this.canvasOverlay.height = this.canvasGraphic.height = this.canvasGraphicOverlay.height = height;
this.canvas.style.width = this.canvasOverlay.style.width = this.canvasGraphic.style.width = this.canvasGraphicOverlay.style.width = styleWidth + 'px';
this.canvas.style.height = this.canvasOverlay.style.height = this.canvasGraphic.style.height = this.canvasGraphicOverlay.style.height = styleHeight + 'px';
this._reInitGraphics();
return true;
};
WorkbookView.prototype._reInitGraphics = function () {
var canvasWidth = this.canvasGraphic.width;
var canvasHeight = this.canvasGraphic.height;
this.shapeCtx.init(this.drawingGraphicCtx.ctx, canvasWidth, canvasHeight, canvasWidth * 25.4 / this.drawingGraphicCtx.ppiX, canvasHeight * 25.4 / this.drawingGraphicCtx.ppiY);
this.shapeCtx.CalculateFullTransform();
var overlayWidth = this.canvasGraphicOverlay.width;
var overlayHeight = this.canvasGraphicOverlay.height;
this.shapeOverlayCtx.init(this.overlayGraphicCtx.ctx, overlayWidth, overlayHeight, overlayWidth * 25.4 / this.overlayGraphicCtx.ppiX, overlayHeight * 25.4 / this.overlayGraphicCtx.ppiY);
this.shapeOverlayCtx.CalculateFullTransform();
this.mainGraphics.init(this.drawingCtx.ctx, canvasWidth, canvasHeight, canvasWidth * 25.4 / this.drawingCtx.ppiX, canvasHeight * 25.4 / this.drawingCtx.ppiY);
this.trackOverlay.init(this.shapeOverlayCtx.m_oContext, "ws-canvas-graphic-overlay", 0, 0, overlayWidth, overlayHeight, (overlayWidth * 25.4 / this.overlayGraphicCtx.ppiX), (overlayHeight * 25.4 / this.overlayGraphicCtx.ppiY));
this.autoShapeTrack.init(this.trackOverlay, 0, 0, overlayWidth, overlayHeight, overlayWidth * 25.4 / this.overlayGraphicCtx.ppiX, overlayHeight * 25.4 / this.overlayGraphicCtx.ppiY);
this.autoShapeTrack.Graphics.CalculateFullTransform();
};
/** @param event {jQuery.Event} */
WorkbookView.prototype.resize = function(event) {
if (this._canResize()) {
var item;
var activeIndex = this.model.getActive();
for (var i in this.wsViews) {
item = this.wsViews[i];
// Делаем resize (для не активных сменим как только сделаем его активным)
item.resize(/*isDraw*/i == activeIndex, this.cellEditor);
}
this.drawWorksheet();
} else {
// ToDo не должно происходить ничего, но нам приходит resize сверху, поэтому проверим отрисовывали ли мы
if (-1 === this.wsActive || this.wsMustDraw) {
this.drawWorksheet();
}
}
this.wsMustDraw = false;
};
WorkbookView.prototype.getSelectionInfo = function () {
if (!this.oSelectionInfo) {
this._updateSelectionInfo();
}
return this.oSelectionInfo;
};
// Получаем свойство: редактируем мы сейчас или нет
WorkbookView.prototype.getCellEditMode = function() {
return this.isCellEditMode;
};
WorkbookView.prototype.canEdit = function() {
return this.Api.canEdit();
};
WorkbookView.prototype.getDialogSheetName = function () {
return this.dialogSheetName || !this.isActive();
};
WorkbookView.prototype.setCellEditMode = function(flag) {
this.isCellEditMode = !!flag;
};
WorkbookView.prototype.isActive = function () {
return (-1 === this.copyActiveSheet || this.wsActive === this.copyActiveSheet);
};
WorkbookView.prototype.getIsTrackShape = function() {
var ws = this.getWorksheet();
if (!ws) {
return false;
}
if (ws.objectRender && ws.objectRender.controller) {
return ws.objectRender.controller.checkTrackDrawings();
}
};
WorkbookView.prototype.getZoom = function() {
return this.drawingCtx.getZoom();
};
WorkbookView.prototype.changeZoom = function(factor) {
if (factor === this.getZoom()) {
return;
}
this.buffers.main.changeZoom(factor);
this.buffers.overlay.changeZoom(factor);
this.buffers.mainGraphic.changeZoom(factor);
this.buffers.overlayGraphic.changeZoom(factor);
if (!factor) {
this.cellEditor.changeZoom(factor);
}
// Нужно сбросить кэш букв
var i, length;
for (i = 0, length = this.fmgrGraphics.length; i < length; ++i)
this.fmgrGraphics[i].ClearFontsRasterCache();
if (AscCommon.g_fontManager) {
AscCommon.g_fontManager.ClearFontsRasterCache();
AscCommon.g_fontManager.m_pFont = null;
}
if (AscCommon.g_fontManager2) {
AscCommon.g_fontManager2.ClearFontsRasterCache();
AscCommon.g_fontManager2.m_pFont = null;
}
if (!factor) {
this.wsMustDraw = true;
this._calcMaxDigitWidth();
}
var item;
var activeIndex = this.model.getActive();
for (i in this.wsViews) {
item = this.wsViews[i];
// Меняем zoom (для не активных сменим как только сделаем его активным)
if (!factor) {
item._initWorksheetDefaultWidth();
}
item.changeZoom(/*isDraw*/i == activeIndex);
this._reInitGraphics();
item.objectRender.changeZoom(this.drawingCtx.scaleFactor);
if (i == activeIndex && factor) {
item.draw();
//ToDo item.drawDepCells();
}
}
this._onScrollReinitialize(AscCommonExcel.c_oAscScrollType.ScrollVertical | AscCommonExcel.c_oAscScrollType.ScrollHorizontal);
this.handlers.trigger("asc_onZoomChanged", this.getZoom());
};
WorkbookView.prototype.getEnableKeyEventsHandler = function(bIsNaturalFocus) {
var res = this.enableKeyEvents;
if (res && bIsNaturalFocus && this.getCellEditMode() && this.input.isFocused) {
res = false;
}
return res;
};
WorkbookView.prototype.enableKeyEventsHandler = function(f) {
this.enableKeyEvents = !!f;
this.controller.enableKeyEventsHandler(this.enableKeyEvents);
if (this.cellEditor) {
this.cellEditor.enableKeyEventsHandler(this.enableKeyEvents);
}
};
// Останавливаем ввод данных в редакторе ввода
WorkbookView.prototype.closeCellEditor = function (cancel) {
return this.getCellEditMode() ? this._onStopCellEditing(cancel) : true;
};
WorkbookView.prototype.restoreFocus = function() {
if (window["NATIVE_EDITOR_ENJINE"]) {
return;
}
if (this.cellEditor.hasFocus) {
this.cellEditor.restoreFocus();
}
};
WorkbookView.prototype._onUpdateCellEditor = function(text, cursorPosition, fPos, fName) {
if (this.skipHelpSelector) {
return;
}
// ToDo для ускорения можно завести объект, куда класть результаты поиска по формулам и второй раз не искать.
var i, arrResult = [], defNamesList, defName, defNameStr;
if (fName) {
fName = fName.toUpperCase();
for (i = 0; i < this.formulasList.length; ++i) {
if (0 === this.formulasList[i].indexOf(fName)) {
arrResult.push(new AscCommonExcel.asc_CCompleteMenu(this.formulasList[i], c_oAscPopUpSelectorType.Func));
}
}
defNamesList = this.getDefinedNames(Asc.c_oAscGetDefinedNamesList.WorksheetWorkbook);
fName = fName.toLowerCase();
for (i = 0; i < defNamesList.length; ++i) {
/*defName = defNamesList[i];
if (0 === defName.Name.toLowerCase().indexOf(fName)) {
arrResult.push(new AscCommonExcel.asc_CCompleteMenu(defName.Name, !defName.isTable ? c_oAscPopUpSelectorType.Range : c_oAscPopUpSelectorType.Table));*/
defName = defNamesList[i];
defNameStr = defName.Name.toLowerCase();
if(null !== defName.LocalSheetId && defNameStr === "print_area") {
defNameStr = AscCommon.translateManager.getValue("Print_Area");
}
if (0 === defNameStr.toLowerCase().indexOf(fName)) {
arrResult.push(new AscCommonExcel.asc_CCompleteMenu(defNameStr, !defName.isTable ? c_oAscPopUpSelectorType.Range : c_oAscPopUpSelectorType.Table));
}
}
}
if (0 < arrResult.length) {
this.handlers.trigger('asc_onFormulaCompleteMenu', arrResult);
this.lastFPos = fPos;
this.lastFNameLength = fName.length;
} else {
this.handlers.trigger('asc_onFormulaCompleteMenu', null);
this.lastFPos = -1;
this.lastFNameLength = 0;
}
};
// Вставка формулы в редактор
WorkbookView.prototype.insertInCellEditor = function (name, type, autoComplete) {
var t = this, ws = this.getWorksheet(), cursorPos, isNotFunction, tmp;
var activeCellRange = ws.getActiveCell(0, 0, false);
if (ws.model.inPivotTable(activeCellRange)) {
this.handlers.trigger("asc_onError", c_oAscError.ID.LockedCellPivot, c_oAscError.Level.NoCritical);
return;
}
if (c_oAscPopUpSelectorType.None === type) {
ws.setSelectionInfo("value", name, /*onlyActive*/true);
return;
}
isNotFunction = c_oAscPopUpSelectorType.Func !== type && c_oAscPopUpSelectorType.FuncWizard !== type;
// Проверяем, открыт ли редактор
var isFormulaContains, funcInfo;
if (this.getCellEditMode()) {
if (isNotFunction) {
this.skipHelpSelector = true;
}
isFormulaContains = this.cellEditor.isFormula() && c_oAscPopUpSelectorType.FuncWizard === type;
if (-1 !== this.lastFPos) {
if (-1 === this.arrExcludeFormulas.indexOf(name) && !isNotFunction) {
//если следующий символ скобка - не добавляем ещё одну
if('(' !== this.cellEditor.textRender.getChars(this.cellEditor.cursorPos, 1)) {
name += '('; // ToDo сделать проверки при добавлении, чтобы не вызывать постоянно окно
}
} else {
this.skipHelpSelector = true;
}
tmp = this.cellEditor.skipTLUpdate;
this.cellEditor.skipTLUpdate = false;
this.cellEditor.replaceText(this.lastFPos, this.lastFNameLength, name);
this.cellEditor.skipTLUpdate = tmp;
} else if (false === this.cellEditor.insertFormula(name, isNotFunction)) {
// Не смогли вставить формулу, закроем редактор, с сохранением текста
this.cellEditor.close(true);
isFormulaContains = false;
}
this.skipHelpSelector = false;
if (isFormulaContains) {
funcInfo = ws.model.getActiveFunctionInfo(this.cellEditor._formula, this.cellEditor._parseResult);
t.handlers.trigger("asc_onSendFunctionWizardInfo", funcInfo);
}
} else {
// Проверка глобального лока
if (this.collaborativeEditing.getGlobalLock()) {
return;
}
var selectionRange = ws.model.selectionRange.clone();
//если в ячейке уже есть формула
isFormulaContains = c_oAscPopUpSelectorType.FuncWizard === type ? ws.model.isActiveCellFormula() : null;
if (!isFormulaContains) {
// Редактор закрыт
var cellRange = {};
// Если нужно сделать автозаполнение формулы, то ищем ячейки)
if (autoComplete) {
cellRange = ws.autoCompleteFormula(name);
}
if (isNotFunction) {
name = "=" + name;
} else {
if (cellRange.notEditCell) {
// Мы уже ввели все что нужно, редактор открывать не нужно
return;
}
if (cellRange.text) {
// Меняем значение ячейки
name = "=" + name + "(" + cellRange.text + ")";
} else {
// Меняем значение ячейки
name = "=" + name + "()";
}
// Вычисляем позицию курсора (он должен быть в функции)
cursorPos = name.length - 1;
}
}
//this.cellEditor.lastInsertedFormulaPos = cursorPos;
var openEditor = function (res) {
if (res) {
// Выставляем переменные, что мы редактируем
t.setCellEditMode(true);
if (isNotFunction) {
t.skipHelpSelector = true;
}
t.hideSpecialPasteButton();
if (isFormulaContains) {
t.cellEditor.needFindFirstFunction = true;
ws.openCellEditor(t.cellEditor, t.cellEditor.cursorPos, false, true, false, false, selectionRange);
//TODO вызываю отсюда служебную функцию, пересмотреть!
t.cellEditor._moveCursor(-11, t.cellEditor._parseResult.cursorPos + 1);
t.cellEditor.needFindFirstFunction = null;
} else {
// Открываем, с выставлением позиции курсора
ws.openCellEditorWithText(t.cellEditor, name, cursorPos, /*isFocus*/false, selectionRange);
}
if (c_oAscPopUpSelectorType.FuncWizard === type) {
var funcInfo = ws.model.getActiveFunctionInfo(t.cellEditor._formula, t.cellEditor._parseResult);
t.handlers.trigger("asc_onSendFunctionWizardInfo", funcInfo);
}
if (isNotFunction) {
t.skipHelpSelector = false;
}
} else {
t.setCellEditMode(false);
t.controller.setStrictClose(false);
t.controller.setFormulaEditMode(false);
ws.setFormulaEditMode(false);
}
};
ws._isLockedCells(activeCellRange, /*subType*/null, openEditor);
}
};
WorkbookView.prototype.preInsertFormula = function() {
var t = this, ws = this.getWorksheet();
var activeCellRange = ws.getActiveCell(0, 0, false);
var selectionRange = ws.model.selectionRange.clone();
var functionInfo = null;
if (this.getCellEditMode()) {
//при парсинге формулы она может быть изменена, например может быть добавлена последняя незакрытая скобка
var parseResult = t.cellEditor ? t.cellEditor._parseResult : null;
if (parseResult && parseResult.activeFunction) {
var _f = t.cellEditor._formula.Formula;
if (_f[_f.length - 1] === "(") {
_f += ")";
t.cellEditor._formula.Formula = _f;
}
if (t.cellEditor.textRender.chars !== "=" + _f) {
this.cellEditor.selectionBegin = 1;
this.cellEditor.selectionEnd = t.cellEditor.textRender.getCharsCount();
//TODO проверить нужно ли перемещать курсор?
var _cursorPos = this.cellEditor.cursorPos;
this.cellEditor.pasteText(_f);
this.cellEditor._moveCursor(-11, _cursorPos);
} else {
this.cellEditor._updateFormulaEditMod();
}
functionInfo = ws.model.getActiveFunctionInfo(t.cellEditor._formula, t.cellEditor._parseResult);
}
t.handlers.trigger("asc_onSendFunctionWizardInfo", functionInfo);
} else {
if (this.collaborativeEditing.getGlobalLock()) {
return;
}
var openEditor = function (res) {
functionInfo = null;
if (res) {
// Выставляем переменные, что мы редактируем
t.setCellEditMode(true);
t.hideSpecialPasteButton();
if (ws.model.isActiveCellFormula()) {
//если ячейка с формулой, то либо перемещаемся к первой функции и отркываем диалог wizard
//если функции нет, то перемещаемся в конец формулы и открываем окно выбора функции
t.cellEditor.needFindFirstFunction = true;
ws.openCellEditor(t.cellEditor, t.cellEditor.cursorPos, false, true, false, false, selectionRange);
t.cellEditor.needFindFirstFunction = null;
var parseResult = t.cellEditor._parseResult;
if (parseResult && parseResult.activeFunction) {
//TODO вызываю отсюда служебную функцию, пересмотреть!
t.cellEditor._moveCursor(-11, t.cellEditor._parseResult.cursorPos + 1);
functionInfo = ws.model.getActiveFunctionInfo(t.cellEditor._formula, t.cellEditor._parseResult);
} else {
t.cellEditor._moveCursor(-11, t.cellEditor._parseResult.cursorPos + 1);
}
} else {
ws.openCellEditorWithText(t.cellEditor, "=", 1, /*isFocus*/false, selectionRange);
}
}
t.handlers.trigger("asc_onSendFunctionWizardInfo", functionInfo);
};
ws._isLockedCells(activeCellRange, /*subType*/null, openEditor);
}
};
WorkbookView.prototype.insertArgumentInFormula = function(val, argNum, type) {
if (!this.getCellEditMode()) {
return;
}
var ws = this.getWorksheet();
//argPosArr
var parseResult = this.cellEditor ? this.cellEditor._parseResult : null;
if (!parseResult || !parseResult.argPosArr || !parseResult.activeFunction || argNum > parseResult.activeFunction.argumentsMax) {
return;
}
if (!parseResult.argPosArr[argNum]) {
//меняем строку и добавляем разделителей
for (var i = parseResult.argPosArr.length; i <= argNum; i++) {
val = AscCommon.FormulaSeparators.functionArgumentSeparator + val;
}
//TODO продумать прпобразование аргументов(допустим строковые значения)
} else {
//полностью заменяем аргумент - для этого чистим предыдущую запись
this.cellEditor.selectionBegin = parseResult.argPosArr[argNum].start;
this.cellEditor.selectionEnd = parseResult.argPosArr[argNum].end;
//TODO нужно ли чистить? при вставке текста должны произойти замена.
this.cellEditor.empty(Asc.c_oAscCleanOptions.All);
if (parseResult.argPosArr[argNum].start === parseResult.argPosArr[argNum].end) {
//TODO вызываю отсюда служебную функцию, пересмотреть!
this.cellEditor._moveCursor(-11, parseResult.argPosArr[argNum].start);
}
}
this.cellEditor.pasteText(val);
return ws.model.getActiveFunctionInfo(this.cellEditor._formula, this.cellEditor._parseResult);
};
WorkbookView.prototype.moveCursorFunctionArgument = function (argNum, pos) {
if (!this.getCellEditMode()) {
return;
}
var ws = this.getWorksheet();
//argPosArr
var parseResult = this.cellEditor ? this.cellEditor._parseResult : null;
if (!parseResult || !parseResult.argPosArr || !parseResult.activeFunction || argNum > parseResult.activeFunction.argumentsMax) {
return;
}
if (!parseResult.argPosArr[argNum]) {
//меняем строку и добавляем разделителей
var val = "";
for (var i = parseResult.argPosArr.length; i <= argNum; i++) {
val = AscCommon.FormulaSeparators.functionArgumentSeparator + val;
}
this.cellEditor.pasteText(val);
}
this.cellEditor._moveCursor(-11, parseResult.argPosArr[argNum].start + pos);
};
WorkbookView.prototype.bIsEmptyClipboard = function() {
return g_clipboardExcel.bIsEmptyClipboard(this.getCellEditMode());
};
WorkbookView.prototype.checkCopyToClipboard = function(_clipboard, _formats) {
var t = this, ws;
ws = t.getWorksheet();
g_clipboardExcel.checkCopyToClipboard(ws, _clipboard, _formats);
};
WorkbookView.prototype.pasteData = function(_format, data1, data2, text_data, doNotShowButton) {
var t = this, ws;
ws = t.getWorksheet();
g_clipboardExcel.pasteData(ws, _format, data1, data2, text_data, null, doNotShowButton);
};
WorkbookView.prototype.specialPasteData = function(props) {
if (!this.getCellEditMode()) {
this.getWorksheet().specialPaste(props);
}
};
WorkbookView.prototype.showSpecialPasteButton = function(props) {
if (!this.getCellEditMode()) {
this.getWorksheet().showSpecialPasteOptions(props);
}
};
WorkbookView.prototype.updateSpecialPasteButton = function(props) {
if (!this.getCellEditMode()) {
this.getWorksheet().updateSpecialPasteButton(props);
}
};
WorkbookView.prototype.hideSpecialPasteButton = function() {
//TODO пересмотреть!
//сейчас сначала добавляются данные в историю, потом идет закрытие редактора ячейки
//следовательно убираю проверку на редактирование ячейки
/*if (!this.getCellEditMode()) {*/
this.handlers.trigger("hideSpecialPasteOptions");
//}
};
WorkbookView.prototype.selectionCut = function () {
if (this.getCellEditMode()) {
this.cellEditor.cutSelection();
} else {
if (this.getWorksheet().isNeedSelectionCut()) {
this.getWorksheet().emptySelection(c_oAscCleanOptions.All, true);
} else {
//в данном случае не вырезаем, а записываем
if(false === this.getWorksheet().isMultiSelect()) {
this.cutIdSheet = this.getWorksheet().model.Id;
this.getWorksheet().cutRange = this.getWorksheet().model.selectionRange.getLast();
}
}
}
};
WorkbookView.prototype.undo = function() {
var oFormulaLocaleInfo = AscCommonExcel.oFormulaLocaleInfo;
oFormulaLocaleInfo.Parse = false;
oFormulaLocaleInfo.DigitSep = false;
if (!this.getCellEditMode()) {
if (!History.Undo() && this.collaborativeEditing.getFast() && this.collaborativeEditing.getCollaborativeEditing()) {
this.Api.sync_TryUndoInFastCollaborative();
}
} else {
this.cellEditor.undo();
}
oFormulaLocaleInfo.Parse = true;
oFormulaLocaleInfo.DigitSep = true;
};
WorkbookView.prototype.redo = function() {
if (!this.getCellEditMode()) {
History.Redo();
} else {
this.cellEditor.redo();
}
};
WorkbookView.prototype.setFontAttributes = function(prop, val) {
if (!this.getCellEditMode()) {
this.getWorksheet().setSelectionInfo(prop, val);
} else {
this.cellEditor.setTextStyle(prop, val);
}
};
WorkbookView.prototype.changeFontSize = function(prop, val) {
if (!this.getCellEditMode()) {
this.getWorksheet().setSelectionInfo(prop, val);
} else {
this.cellEditor.setTextStyle(prop, val);
}
};
WorkbookView.prototype.setCellFormat = function (format) {
this.getWorksheet().setSelectionInfo("format", format);
};
WorkbookView.prototype.emptyCells = function (options) {
if (!this.getCellEditMode()) {
if (Asc.c_oAscCleanOptions.Comments === options) {
this.removeAllComments(false, true);
} else {
this.getWorksheet().emptySelection(options);
}
this.restoreFocus();
} else {
this.cellEditor.empty(options);
}
};
WorkbookView.prototype._setSelectionDialogType = function (selectionDialogType) {
this.dialogSheetName = (c_oAscSelectionDialogType.Chart === selectionDialogType ||
c_oAscSelectionDialogType.PivotTableData === selectionDialogType ||
c_oAscSelectionDialogType.PivotTableReport === selectionDialogType);
this.dialogAbsName = (c_oAscSelectionDialogType.None !== selectionDialogType &&
c_oAscSelectionDialogType.FunctionWizard !== selectionDialogType);
};
WorkbookView.prototype.setSelectionDialogMode = function (selectionDialogType, selectRange) {
var newSelectionDialogMode = c_oAscSelectionDialogType.None !== selectionDialogType;
if (newSelectionDialogMode === this.selectionDialogMode) {
return;
}
this._setSelectionDialogType(selectionDialogType);
var drawSelection = false;
if (newSelectionDialogMode) {
this.copyActiveSheet = this.wsActive;
var tmpSelectRange = AscCommon.parserHelp.parse3DRef(selectRange);
if (tmpSelectRange) {
var ws = this.model.getWorksheetByName(tmpSelectRange.sheet);
if (!ws || ws.getHidden()) {
tmpSelectRange = null;
} else {
var index = ws.getIndex();
if (index !== this.wsActive) {
this.showWorksheet(index);
}
tmpSelectRange = tmpSelectRange.range;
}
} else {
tmpSelectRange = selectRange;
}
this.getWorksheet().copySelection(true, tmpSelectRange && AscCommonExcel.g_oRangeCache.getAscRange(tmpSelectRange));
this.selectionDialogMode = newSelectionDialogMode;
this.input.disabled = true;
drawSelection = true;
} else {
this.selectionDialogMode = newSelectionDialogMode;
this.getWorksheet().copySelection(false);
if (this.copyActiveSheet !== this.wsActive) {
this.showWorksheet(this.copyActiveSheet);
} else {
drawSelection = true;
}
this.copyActiveSheet = -1;
this.input.disabled = false;
}
if (drawSelection) {
this.getWorksheet()._drawSelection();
}
};
WorkbookView.prototype.formatPainter = function(stateFormatPainter) {
// Если передали состояние, то выставляем его. Если нет - то меняем на противоположное.
this.stateFormatPainter = (null != stateFormatPainter) ? stateFormatPainter : ((c_oAscFormatPainterState.kOff !== this.stateFormatPainter) ? c_oAscFormatPainterState.kOff : c_oAscFormatPainterState.kOn);
this.rangeFormatPainter = this.getWorksheet().formatPainter(this.stateFormatPainter);
if (this.stateFormatPainter) {
this.copyActiveSheet = this.wsActive;
} else {
this.copyActiveSheet = -1;
this.handlers.trigger('asc_onStopFormatPainter');
}
};
// Поиск текста в листе
WorkbookView.prototype.findCellText = function (options) {
this.closeCellEditor();
// Для поиска эта переменная не нужна (но она может остаться от replace)
options.selectionRange = null;
var result = this.model.findCellText(options);
if (result) {
var ws = this.getWorksheet();
var range = new Asc.Range(result.col, result.row, result.col, result.row);
options.findInSelection ? ws.setActiveCell(result) : ws.setSelection(range);
return true;
}
return null;
};
// Замена текста в листе
WorkbookView.prototype.replaceCellText = function (options) {
this.closeCellEditor();
if (!options.isMatchCase) {
options.findWhat = options.findWhat.toLowerCase();
}
options.findRegExp = AscCommonExcel.getFindRegExp(options.findWhat, options);
History.Create_NewPoint();
History.StartTransaction();
options.clearFindAll();
if (options.isReplaceAll) {
// На ReplaceAll ставим медленную операцию
this.Api.sync_StartAction(c_oAscAsyncActionType.BlockInteraction, c_oAscAsyncAction.SlowOperation);
}
var ws = this.getWorksheet();
ws.replaceCellText(options, false, this.fReplaceCallback);
};
WorkbookView.prototype._replaceCellTextCallback = function(options) {
if (!options.error) {
options.updateFindAll();
if (!options.scanOnOnlySheet && options.isReplaceAll) {
// Замена на всей книге
var i = ++options.sheetIndex;
if (this.model.getActive() === i) {
i = ++options.sheetIndex;
}
if (i < this.model.getWorksheetCount()) {
var ws = this.getWorksheet(i);
ws.replaceCellText(options, true, this.fReplaceCallback);
return;
}
options.sheetIndex = -1;
}
this.handlers.trigger("asc_onRenameCellTextEnd", options.countFindAll, options.countReplaceAll);
}
History.EndTransaction();
if (options.isReplaceAll) {
// Заканчиваем медленную операцию
this.Api.sync_EndAction(c_oAscAsyncActionType.BlockInteraction, c_oAscAsyncAction.SlowOperation);
}
};
WorkbookView.prototype.getDefinedNames = function(defNameListId) {
return this.model.getDefinedNamesWB(defNameListId, true);
};
WorkbookView.prototype.setDefinedNames = function(defName) {
//ToDo проверка defName.ref на знак "=" в начале ссылки. знака нет тогда это либо число либо строка, так делает Excel.
this.model.setDefinesNames(defName.Name, defName.Ref, defName.Scope);
this.handlers.trigger("asc_onDefName");
};
WorkbookView.prototype.editDefinedNames = function(oldName, newName) {
//ToDo проверка defName.ref на знак "=" в начале ссылки. знака нет тогда это либо число либо строка, так делает Excel.
if (this.collaborativeEditing.getGlobalLock()) {
return;
}
var ws = this.getWorksheet(), t = this;
var editDefinedNamesCallback = function(res) {
if (res) {
if (oldName && oldName.asc_getIsTable()) {
ws.model.autoFilters.changeDisplayNameTable(oldName.asc_getName(), newName.asc_getName());
} else {
t.model.editDefinesNames(oldName, newName);
}
t.handlers.trigger("asc_onEditDefName", oldName, newName);
//условие исключает второй вызов asc_onRefreshDefNameList(первый в unlockDefName)
if(!(t.collaborativeEditing.getCollaborativeEditing() && t.collaborativeEditing.getFast()))
{
t.handlers.trigger("asc_onRefreshDefNameList");
}
} else {
t.handlers.trigger("asc_onError", c_oAscError.ID.LockCreateDefName, c_oAscError.Level.NoCritical);
}
t._onSelectionNameChanged(ws.getSelectionName(/*bRangeText*/false));
if(ws.viewPrintLines) {
ws.updateSelection();
}
};
var defNameId;
if (oldName) {
defNameId = t.model.getDefinedName(oldName);
defNameId = defNameId ? defNameId.getNodeId() : null;
}
var callback = function() {
ws._isLockedDefNames(editDefinedNamesCallback, defNameId);
};
var tableRange;
if(oldName && true === oldName.isTable)
{
var table = ws.model.autoFilters._getFilterByDisplayName(oldName.Name);
if(table)
{
tableRange = table.Ref;
}
}
if(tableRange)
{
ws._isLockedCells( tableRange, null, callback );
}
else
{
callback();
}
};
WorkbookView.prototype.delDefinedNames = function(oldName) {
//ToDo проверка defName.ref на знак "=" в начале ссылки. знака нет тогда это либо число либо строка, так делает Excel.
if (this.collaborativeEditing.getGlobalLock()) {
return;
}
var ws = this.getWorksheet(), t = this;
if (oldName) {
var delDefinedNamesCallback = function(res) {
if (res) {
t.model.delDefinesNames(oldName);
t.handlers.trigger("asc_onRefreshDefNameList");
} else {
t.handlers.trigger("asc_onError", c_oAscError.ID.LockCreateDefName, c_oAscError.Level.NoCritical);
}
t._onSelectionNameChanged(ws.getSelectionName(/*bRangeText*/false));
if(ws.viewPrintLines) {
ws.updateSelection();
}
};
var defNameId = t.model.getDefinedName(oldName).getNodeId();
ws._isLockedDefNames(delDefinedNamesCallback, defNameId);
}
};
WorkbookView.prototype.getDefaultDefinedName = function() {
//ToDo проверка defName.ref на знак "=" в начале ссылки. знака нет тогда это либо число либо строка, так делает Excel.
var ws = this.getWorksheet();
var oRangeValue = ws.getSelectionRangeValue();
return new Asc.asc_CDefName("", oRangeValue.asc_getName(), null);
};
WorkbookView.prototype.getDefaultTableStyle = function() {
return this.model.TableStyles.DefaultTableStyle;
};
WorkbookView.prototype.unlockDefName = function() {
this.model.unlockDefName();
this.handlers.trigger("asc_onRefreshDefNameList");
this.handlers.trigger("asc_onLockDefNameManager", Asc.c_oAscDefinedNameReason.OK);
};
WorkbookView.prototype.unlockCurrentDefName = function(name, sheetId) {
this.model.unlockCurrentDefName(name, sheetId);
//this.handlers.trigger("asc_onRefreshDefNameList");
//this.handlers.trigger("asc_onLockDefNameManager", Asc.c_oAscDefinedNameReason.OK);
};
WorkbookView.prototype._onCheckDefNameLock = function() {
return this.model.checkDefNameLock();
};
// Печать
WorkbookView.prototype.printSheets = function(printPagesData, pdfDocRenderer) {
//change zoom on default
var viewZoom = this.getZoom();
this.changeZoom(1);
var pdfPrinter = new AscCommonExcel.CPdfPrinter(this.fmgrGraphics[3], this.m_oFont);
if (pdfDocRenderer) {
pdfPrinter.DocumentRenderer = pdfDocRenderer;
}
var ws;
if (0 === printPagesData.arrPages.length) {
// Печать пустой страницы
ws = this.getWorksheet();
ws.drawForPrint(pdfPrinter, null);
} else {
var indexWorksheet = -1;
var indexWorksheetTmp = -1;
for (var i = 0; i < printPagesData.arrPages.length; ++i) {
indexWorksheetTmp = printPagesData.arrPages[i].indexWorksheet;
if (indexWorksheetTmp !== indexWorksheet) {
ws = this.getWorksheet(indexWorksheetTmp);
indexWorksheet = indexWorksheetTmp;
}
ws.drawForPrint(pdfPrinter, printPagesData.arrPages[i], i, printPagesData.arrPages.length);
}
}
this.changeZoom(viewZoom);
return pdfPrinter;
};
WorkbookView.prototype._calcPagesPrintSheet = function (index, printPagesData, onlySelection, adjustPrint) {
var ws = this.model.getWorksheet(index);
var wsView = this.getWorksheet(index);
if (!ws.getHidden()) {
var pageOptionsMap = adjustPrint ? adjustPrint.asc_getPageOptionsMap() : null;
var pagePrintOptions = pageOptionsMap && pageOptionsMap[index] ? pageOptionsMap[index] : ws.PagePrintOptions;
wsView.calcPagesPrint(pagePrintOptions, onlySelection, index, printPagesData.arrPages, null, adjustPrint);
}
};
WorkbookView.prototype.calcPagesPrint = function (adjustPrint) {
if (!adjustPrint) {
adjustPrint = new Asc.asc_CAdjustPrint();
}
var viewZoom = this.getZoom();
this.changeZoom(1);
var printPagesData = new asc_CPrintPagesData();
var printType = adjustPrint.asc_getPrintType();
if (printType === Asc.c_oAscPrintType.ActiveSheets) {
this._calcPagesPrintSheet(this.model.getActive(), printPagesData, false, adjustPrint);
} else if (printType === Asc.c_oAscPrintType.EntireWorkbook) {
// Колличество листов
var countWorksheets = this.model.getWorksheetCount();
for (var i = 0; i < countWorksheets; ++i) {
if(adjustPrint.isOnlyFirstPage && i !== 0) {
break;
}
this._calcPagesPrintSheet(i, printPagesData, false, adjustPrint);
}
} else if (printType === Asc.c_oAscPrintType.Selection) {
this._calcPagesPrintSheet(this.model.getActive(), printPagesData, true, adjustPrint);
}
if (AscCommonExcel.c_kMaxPrintPages === printPagesData.arrPages.length) {
this.handlers.trigger("asc_onError", c_oAscError.ID.PrintMaxPagesCount, c_oAscError.Level.NoCritical);
}
this.changeZoom(viewZoom);
return printPagesData;
};
// Вызывать только для нативной печати
WorkbookView.prototype._nativeCalculate = function() {
var item;
for (var i in this.wsViews) {
item = this.wsViews[i];
item._cleanCellsTextMetricsCache();
item._prepareDrawingObjects();
}
};
WorkbookView.prototype.calculate = function (type) {
this.model.calculate(type);
this.drawWS();
};
WorkbookView.prototype.reInit = function() {
var ws = this.getWorksheet();
ws._initCellsArea(AscCommonExcel.recalcType.full);
ws._updateVisibleColsCount();
ws._updateVisibleRowsCount();
};
WorkbookView.prototype.drawWS = function() {
this.getWorksheet().draw();
};
WorkbookView.prototype.onShowDrawingObjects = function(clearCanvas) {
var ws = this.getWorksheet();
ws.objectRender.showDrawingObjects(clearCanvas);
};
WorkbookView.prototype.insertHyperlink = function(options) {
var ws = this.getWorksheet();
if (ws.objectRender.selectedGraphicObjectsExists()) {
if (ws.objectRender.controller.canAddHyperlink()) {
ws.objectRender.controller.insertHyperlink(options);
}
} else {
ws.setSelectionInfo("hyperlink", options);
this.restoreFocus();
}
};
WorkbookView.prototype.removeHyperlink = function() {
var ws = this.getWorksheet();
if (ws.objectRender.selectedGraphicObjectsExists()) {
ws.objectRender.controller.removeHyperlink();
} else {
ws.setSelectionInfo("rh");
}
};
WorkbookView.prototype.setDocumentPlaceChangedEnabled = function(val) {
this.isDocumentPlaceChangedEnabled = val;
};
WorkbookView.prototype.showComments = function (val, isShowSolved) {
if (this.isShowComments !== val || this.isShowSolved !== isShowSolved) {
this.isShowComments = val;
this.isShowSolved = isShowSolved;
this.drawWS();
}
};
WorkbookView.prototype.removeComment = function (id) {
var ws = this.getWorksheet();
ws.cellCommentator.removeComment(id);
this.cellCommentator.removeComment(id);
};
WorkbookView.prototype.removeAllComments = function (isMine, isCurrent) {
var range;
var ws = this.getWorksheet();
isMine = isMine ? (this.Api.DocInfo && this.Api.DocInfo.get_UserId()) : null;
History.Create_NewPoint();
History.StartTransaction();
if (isCurrent) {
ws._getSelection().ranges.forEach(function (item) {
ws.cellCommentator.deleteCommentsRange(item, isMine);
});
} else {
range = new Asc.Range(0, 0, AscCommon.gc_nMaxCol0, AscCommon.gc_nMaxRow0);
this.cellCommentator.deleteCommentsRange(range, isMine);
ws.cellCommentator.deleteCommentsRange(range, isMine);
}
History.EndTransaction();
};
/*
* @param {c_oAscRenderingModeType} mode Режим отрисовки
* @param {Boolean} isInit инициализация или нет
*/
WorkbookView.prototype.setFontRenderingMode = function(mode, isInit) {
if (mode !== this.fontRenderingMode) {
this.fontRenderingMode = mode;
if (c_oAscFontRenderingModeType.noHinting === mode) {
this._setHintsProps(false, false);
} else if (c_oAscFontRenderingModeType.hinting === mode) {
this._setHintsProps(true, false);
} else if (c_oAscFontRenderingModeType.hintingAndSubpixeling === mode) {
this._setHintsProps(true, true);
}
if (!isInit) {
this.drawWS();
this.cellEditor.setFontRenderingMode(mode);
}
}
};
WorkbookView.prototype.initFormulasList = function() {
this.formulasList = [];
var oFormulaList = AscCommonExcel.cFormulaFunctionLocalized ? AscCommonExcel.cFormulaFunctionLocalized :
AscCommonExcel.cFormulaFunction;
for (var f in oFormulaList) {
this.formulasList.push(f);
}
this.arrExcludeFormulas = [cBoolLocal.t, cBoolLocal.f];
};
WorkbookView.prototype._setHintsProps = function(bIsHinting, bIsSubpixHinting) {
var manager;
for (var i = 0, length = this.fmgrGraphics.length; i < length; ++i) {
manager = this.fmgrGraphics[i];
// Последний без хинтования (только для измерения)
if (i === length - 1) {
bIsHinting = bIsSubpixHinting = false;
}
manager.SetHintsProps(bIsHinting, bIsSubpixHinting);
}
};
WorkbookView.prototype._calcMaxDigitWidth = function () {
// set default worksheet header font for calculations
this.buffers.main.setFont(AscCommonExcel.g_oDefaultFormat.Font);
// Измеряем в pt
this.stringRender.measureString("0123456789", new AscCommonExcel.CellFlags());
// Переводим в px и приводим к целому (int)
this.model.maxDigitWidth = this.maxDigitWidth = this.stringRender.getWidestCharWidth();
// Проверка для Calibri 11 должно быть this.maxDigitWidth = 7
if (!this.maxDigitWidth) {
throw "Error: can't measure text string";
}
// Padding рассчитывается исходя из maxDigitWidth (http://social.msdn.microsoft.com/Forums/en-US/9a6a9785-66ad-4b6b-bb9f-74429381bd72/margin-padding-in-cell-excel?forum=os_binaryfile)
this.defaults.worksheetView.cells.padding = Math.max(asc.ceil(this.maxDigitWidth / 4), 2);
this.model.paddingPlusBorder = 2 * this.defaults.worksheetView.cells.padding + 1;
};
WorkbookView.prototype.getPivotMergeStyle = function (sheetMergedStyles, range, style, pivot) {
var styleInfo = pivot.asc_getStyleInfo();
var i, r, dxf, stripe1, stripe2, emptyStripe = new Asc.CTableStyleElement();
if (style) {
dxf = style.wholeTable && style.wholeTable.dxf;
if (dxf) {
sheetMergedStyles.setTablePivotStyle(range, dxf);
}
if (styleInfo.showColStripes) {
stripe1 = style.firstColumnStripe || emptyStripe;
stripe2 = style.secondColumnStripe || emptyStripe;
if (stripe1.dxf) {
sheetMergedStyles.setTablePivotStyle(range, stripe1.dxf,
new Asc.CTableStyleStripe(stripe1.size, stripe2.size));
}
if (stripe2.dxf && range.c1 + stripe1.size <= range.c2) {
sheetMergedStyles.setTablePivotStyle(
new Asc.Range(range.c1 + stripe1.size, range.r1, range.c2, range.r2), stripe2.dxf,
new Asc.CTableStyleStripe(stripe2.size, stripe1.size));
}
}
if (styleInfo.showRowStripes) {
stripe1 = style.firstRowStripe || emptyStripe;
stripe2 = style.secondRowStripe || emptyStripe;
if (stripe1.dxf) {
sheetMergedStyles.setTablePivotStyle(range, stripe1.dxf,
new Asc.CTableStyleStripe(stripe1.size, stripe2.size, true));
}
if (stripe2.dxf && range.r1 + stripe1.size <= range.r2) {
sheetMergedStyles.setTablePivotStyle(
new Asc.Range(range.c1, range.r1 + stripe1.size, range.c2, range.r2), stripe2.dxf,
new Asc.CTableStyleStripe(stripe2.size, stripe1.size, true));
}
}
dxf = style.firstColumn && style.firstColumn.dxf;
if (styleInfo.showRowHeaders && dxf) {
sheetMergedStyles.setTablePivotStyle(new Asc.Range(range.c1, range.r1, range.c1, range.r2), dxf);
}
dxf = style.headerRow && style.headerRow.dxf;
if (styleInfo.showColHeaders && dxf) {
sheetMergedStyles.setTablePivotStyle(new Asc.Range(range.c1, range.r1, range.c2, range.r1), dxf);
}
dxf = style.firstHeaderCell && style.firstHeaderCell.dxf;
if (styleInfo.showColHeaders && styleInfo.showRowHeaders && dxf) {
sheetMergedStyles.setTablePivotStyle(new Asc.Range(range.c1, range.r1, range.c1, range.r1), dxf);
}
if (pivot.asc_getColGrandTotals()) {
dxf = style.lastColumn && style.lastColumn.dxf;
if (dxf) {
sheetMergedStyles.setTablePivotStyle(new Asc.Range(range.c2, range.r1, range.c2, range.r2), dxf);
}
}
if (styleInfo.showRowHeaders) {
for (i = range.r1 + 1; i < range.r2; ++i) {
r = i - (range.r1 + 1);
if (0 === r % 3) {
dxf = style.firstRowSubheading;
}
if (dxf = (dxf && dxf.dxf)) {
sheetMergedStyles.setTablePivotStyle(new Asc.Range(range.c1, i, range.c2, i), dxf);
}
}
}
if (pivot.asc_getRowGrandTotals()) {
dxf = style.totalRow && style.totalRow.dxf;
if (dxf) {
sheetMergedStyles.setTablePivotStyle(new Asc.Range(range.c1, range.r2, range.c2, range.r2), dxf);
}
}
}
};
WorkbookView.prototype.getTableStyles = function (props, bPivotTable) {
var wb = this.model;
var t = this;
var result = [];
var canvas = document.createElement('canvas');
var tableStyleInfo;
var pivotStyleInfo;
var defaultStyles, styleThumbnailHeight, row, col = 5;
var styleThumbnailWidth = window["IS_NATIVE_EDITOR"] ? 90 : 61;
if(bPivotTable)
{
styleThumbnailHeight = 49;
row = 8;
defaultStyles = wb.TableStyles.DefaultStylesPivot;
pivotStyleInfo = props;
}
else
{
styleThumbnailHeight = window["IS_NATIVE_EDITOR"] ? 48 : 46;
row = 5;
defaultStyles = wb.TableStyles.DefaultStyles;
tableStyleInfo = new AscCommonExcel.TableStyleInfo();
if (props) {
tableStyleInfo.ShowColumnStripes = props.asc_getBandVer();
tableStyleInfo.ShowFirstColumn = props.asc_getFirstCol();
tableStyleInfo.ShowLastColumn = props.asc_getLastCol();
tableStyleInfo.ShowRowStripes = props.asc_getBandHor();
tableStyleInfo.HeaderRowCount = props.asc_getFirstRow();
tableStyleInfo.TotalsRowCount = props.asc_getLastRow();
} else {
tableStyleInfo.ShowColumnStripes = false;
tableStyleInfo.ShowFirstColumn = false;
tableStyleInfo.ShowLastColumn = false;
tableStyleInfo.ShowRowStripes = true;
tableStyleInfo.HeaderRowCount = true;
tableStyleInfo.TotalsRowCount = false;
}
}
if (AscBrowser.isRetina)
{
styleThumbnailWidth = AscCommon.AscBrowser.convertToRetinaValue(styleThumbnailWidth, true);
styleThumbnailHeight = AscCommon.AscBrowser.convertToRetinaValue(styleThumbnailHeight, true);
}
canvas.width = styleThumbnailWidth;
canvas.height = styleThumbnailHeight;
var sizeInfo = {w: styleThumbnailWidth, h: styleThumbnailHeight, row: row, col: col};
var ctx = new Asc.DrawingContext({canvas: canvas, units: 0/*px*/, fmgrGraphics: this.fmgrGraphics, font: this.m_oFont});
var addStyles = function(styles, type, bEmptyStyle)
{
var style;
for (var i in styles)
{
if ((bPivotTable && styles[i].pivot) || (!bPivotTable && styles[i].table))
{
if (window["IS_NATIVE_EDITOR"]) {
//TODO empty style?
window["native"]["BeginDrawStyle"](type, i);
}
t._drawTableStyle(ctx, styles[i], tableStyleInfo, pivotStyleInfo, sizeInfo);
if (window["IS_NATIVE_EDITOR"]) {
window["native"]["EndDrawStyle"]();
} else {
style = new AscCommon.CStyleImage();
style.name = bEmptyStyle ? null : i;
style.displayName = styles[i].displayName;
style.type = type;
style.image = canvas.toDataURL("image/png");
result.push(style);
}
}
}
};
addStyles(wb.TableStyles.CustomStyles, AscCommon.c_oAscStyleImage.Document);
if (props) {
//None style
var emptyStyle = new Asc.CTableStyle();
emptyStyle.displayName = "None";
emptyStyle.pivot = bPivotTable;
addStyles({null: emptyStyle}, AscCommon.c_oAscStyleImage.Default, true);
}
addStyles(defaultStyles, AscCommon.c_oAscStyleImage.Default);
return result;
};
WorkbookView.prototype._drawTableStyle = function (ctx, style, tableStyleInfo, pivotStyleInfo, size) {
ctx.clear();
var w = size.w;
var h = size.h;
var row = size.row;
var col = size.col;
var startX = 1;
var startY = 1;
var ySize = (h - 1) - 2 * startY;
var xSize = w - 2 * startX;
var stepY = (ySize) / row;
var stepX = (xSize) / col;
var lineStepX = (xSize - 1) / 5;
var whiteColor = new CColor(255, 255, 255);
var blackColor = new CColor(0, 0, 0);
var defaultColor;
if (!style || !style.wholeTable || !style.wholeTable.dxf.font) {
defaultColor = blackColor;
} else {
defaultColor = style.wholeTable.dxf.font.getColor();
}
ctx.setFillStyle(whiteColor);
ctx.fillRect(0, 0, xSize + 2 * startX, ySize + 2 * startY);
var calculateLineVer = function(color, x, y1, y2)
{
ctx.beginPath();
ctx.setStrokeStyle(color);
ctx.lineVer(x + startX, y1 + startY, y2 + startY);
ctx.stroke();
ctx.closePath();
};
var calculateLineHor = function(color, x1, y, x2)
{
ctx.beginPath();
ctx.setStrokeStyle(color);
ctx.lineHor(x1 + startX, y + startY, x2 + startX);
ctx.stroke();
ctx.closePath();
};
var calculateRect = function(color, x1, y1, w, h)
{
ctx.beginPath();
ctx.setFillStyle(color);
ctx.fillRect(x1 + startX, y1 + startY, w, h);
ctx.closePath();
};
var bbox = new Asc.Range(0, 0, col - 1, row - 1);
var sheetMergedStyles = new AscCommonExcel.SheetMergedStyles();
var hiddenManager = new AscCommonExcel.HiddenManager(null);
if(pivotStyleInfo)
{
this.getPivotMergeStyle(sheetMergedStyles, bbox, style, pivotStyleInfo);
}
else if(tableStyleInfo)
{
style.initStyle(sheetMergedStyles, bbox, tableStyleInfo,
null !== tableStyleInfo.HeaderRowCount ? tableStyleInfo.HeaderRowCount : 1,
null !== tableStyleInfo.TotalsRowCount ? tableStyleInfo.TotalsRowCount : 0);
}
var compiledStylesArr = [];
for (var i = 0; i < row; i++)
{
for (var j = 0; j < col; j++) {
var color = null, prevStyle;
var curStyle = AscCommonExcel.getCompiledStyle(sheetMergedStyles, hiddenManager, i, j);
if(!compiledStylesArr[i])
{
compiledStylesArr[i] = [];
}
compiledStylesArr[i][j] = curStyle;
//fill
color = curStyle && curStyle.fill && curStyle.fill.bg();
if(color)
{
calculateRect(color, j * stepX, i * stepY, stepX, stepY);
}
//borders
//left
prevStyle = (j - 1 >= 0) ? compiledStylesArr[i][j - 1] : null;
color = AscCommonExcel.getMatchingBorder(prevStyle && prevStyle.border && prevStyle.border.r, curStyle && curStyle.border && curStyle.border.l);
if(color && color.w > 0)
{
calculateLineVer(color.c, j * lineStepX, i * stepY, (i + 1) * stepY);
}
//right
color = curStyle && curStyle.border && curStyle.border.r;
if(color && color.w > 0)
{
calculateLineVer(color.c, (j + 1) * lineStepX, i * stepY, (i + 1) * stepY);
}
//top
prevStyle = (i - 1 >= 0) ? compiledStylesArr[i - 1][j] : null;
color = AscCommonExcel.getMatchingBorder(prevStyle && prevStyle.border && prevStyle.border.b, curStyle && curStyle.border && curStyle.border.t);
if(color && color.w > 0)
{
calculateLineHor(color.c, j * stepX, i * stepY, (j + 1) * stepX);
}
//bottom
color = curStyle && curStyle.border && curStyle.border.b;
if(color && color.w > 0)
{
calculateLineHor(color.c, j * stepX, (i + 1) * stepY, (j + 1) * stepX);
}
//marks
color = (curStyle && curStyle.font && curStyle.font.c) || defaultColor;
calculateLineHor(color, j * lineStepX + 3, (i + 1) * stepY - stepY / 2, (j + 1) * lineStepX - 2);
}
}
};
WorkbookView.prototype.IsSelectionUse = function () {
return !this.getWorksheet().getSelectionShape();
};
WorkbookView.prototype.GetSelectionRectsBounds = function () {
if (this.getWorksheet().getSelectionShape())
return null;
var ws = this.getWorksheet();
var range = ws.model.selectionRange.getLast();
var type = range.getType();
var l = ws.getCellLeft(range.c1, 3);
var t = ws.getCellTop(range.r1, 3);
var offset = ws.getCellsOffset(3);
return {
X: asc.c_oAscSelectionType.RangeRow === type ? -offset.left : l - offset.left,
Y: asc.c_oAscSelectionType.RangeCol === type ? -offset.top : t - offset.top,
W: asc.c_oAscSelectionType.RangeRow === type ? offset.left :
ws.getCellLeft(range.c2, 3) - l + ws.getColumnWidth(range.c2, 3),
H: asc.c_oAscSelectionType.RangeCol === type ? offset.top :
ws.getCellTop(range.r2, 3) - t + ws.getRowHeight(range.r2, 3),
T: type
};
};
WorkbookView.prototype.GetCaptionSize = function()
{
var offset = this.getWorksheet().getCellsOffset(3);
return {
W: offset.left,
H: offset.top
};
};
WorkbookView.prototype.ConvertXYToLogic = function (x, y) {
return this.getWorksheet().ConvertXYToLogic(x, y);
};
WorkbookView.prototype.ConvertLogicToXY = function (xL, yL) {
return this.getWorksheet().ConvertLogicToXY(xL, yL)
};
WorkbookView.prototype.changeFormatTableInfo = function (tableName, optionType, val) {
var ws = this.getWorksheet();
return ws.af_changeFormatTableInfo(tableName, optionType, val);
};
WorkbookView.prototype.applyAutoCorrectOptions = function (val) {
var api = window["Asc"]["editor"];
var prevProps;
switch (val) {
case Asc.c_oAscAutoCorrectOptions.UndoTableAutoExpansion: {
prevProps = {
props: this.autoCorrectStore.props,
cell: this.autoCorrectStore.cell,
wsId: this.autoCorrectStore.wsId
};
api.asc_Undo();
this.autoCorrectStore = prevProps;
this.autoCorrectStore.props[0] = Asc.c_oAscAutoCorrectOptions.RedoTableAutoExpansion;
this.toggleAutoCorrectOptions(true);
break;
}
case Asc.c_oAscAutoCorrectOptions.RedoTableAutoExpansion: {
prevProps = {
props: this.autoCorrectStore.props,
cell: this.autoCorrectStore.cell,
wsId: this.autoCorrectStore.wsId
};
api.asc_Redo();
this.autoCorrectStore = prevProps;
this.autoCorrectStore.props[0] = Asc.c_oAscAutoCorrectOptions.UndoTableAutoExpansion;
this.toggleAutoCorrectOptions(true);
break;
}
}
return true;
};
WorkbookView.prototype.toggleAutoCorrectOptions = function (isSwitch, val) {
if (isSwitch) {
if (val) {
this.autoCorrectStore = val;
var options = new Asc.asc_CAutoCorrectOptions();
options.asc_setOptions(this.autoCorrectStore.props);
options.asc_setCellCoord(
this.getWorksheet().getCellCoord(this.autoCorrectStore.cell.c1, this.autoCorrectStore.cell.r1));
this.handlers.trigger("asc_onToggleAutoCorrectOptions", options);
} else if (this.autoCorrectStore) {
if (this.autoCorrectStore.wsId === this.model.getActiveWs().getId()) {
var options = new Asc.asc_CAutoCorrectOptions();
options.asc_setOptions(this.autoCorrectStore.props);
options.asc_setCellCoord(
this.getWorksheet().getCellCoord(this.autoCorrectStore.cell.c1, this.autoCorrectStore.cell.r1));
this.handlers.trigger("asc_onToggleAutoCorrectOptions", options);
} else {
this.handlers.trigger("asc_onToggleAutoCorrectOptions");
}
}
} else {
if(this.autoCorrectStore) {
if (val) {
this.autoCorrectStore = null;
}
this.handlers.trigger("asc_onToggleAutoCorrectOptions");
}
}
};
WorkbookView.prototype.savePagePrintOptions = function (arrPagesPrint) {
var t = this;
var viewMode = !this.canEdit();
if(!arrPagesPrint) {
return;
}
var callback = function (isSuccess) {
if (false === isSuccess) {
return;
}
for(var i in arrPagesPrint) {
var ws = t.getWorksheet(parseInt(i));
ws.savePageOptions(arrPagesPrint[i], viewMode);
window["Asc"]["editor"]._onUpdateLayoutMenu(ws.model.Id);
}
};
var lockInfoArr = [];
var lockInfo;
for(var i in arrPagesPrint) {
lockInfo = this.getWorksheet(parseInt(i)).getLayoutLockInfo();
lockInfoArr.push(lockInfo);
}
if(viewMode) {
callback();
} else {
this.collaborativeEditing.lock(lockInfoArr, callback);
}
};
WorkbookView.prototype.cleanCutData = function (bDrawSelection, bCleanBuffer) {
if(this.cutIdSheet) {
var activeWs = this.wsViews[this.wsActive];
var ws = this.getWorksheetById(this.cutIdSheet);
if(bDrawSelection && activeWs && ws && activeWs.model.Id === ws.model.Id) {
activeWs.cleanSelection();
}
if(ws) {
ws.cutRange = null;
}
this.cutIdSheet = null;
if(bDrawSelection && activeWs && ws && activeWs.model.Id === ws.model.Id) {
activeWs.updateSelection();
}
//ms чистит буфер, если происходят какие-то изменения в документе с посвеченной областью вырезать
//мы в данном случае не можем так делать, поскольку не можем прочесть информацию из буфера и убедиться, что
//там именно тот вырезанный фрагмент. тем самым можем затереть какую-то важную информацию
if(bCleanBuffer) {
AscCommon.g_clipboardBase.ClearBuffer();
}
}
};
WorkbookView.prototype.updateGroupData = function () {
this.getWorksheet()._updateGroups(true);
this.getWorksheet()._updateGroups(null);
};
WorkbookView.prototype.pasteSheet = function (base64, insertBefore, name, callback) {
var t = this;
var tempWorkbook = new AscCommonExcel.Workbook();
tempWorkbook.setCommonIndexObjectsFrom(this.model);
var pasteProcessor = AscCommonExcel.g_clipboardExcel.pasteProcessor;
var aPastedImages = pasteProcessor._readExcelBinary(base64.split('xslData;')[1], tempWorkbook, true);
var pastedWs = tempWorkbook.aWorksheets[0];
var newFonts = {};
newFonts = tempWorkbook.generateFontMap2();
newFonts = pasteProcessor._convertFonts(newFonts);
for (var i = 0; i < pastedWs.Drawings.length; i++) {
pastedWs.Drawings[i].graphicObject.getAllFonts(newFonts);
}
var doCopy = function() {
History.Create_NewPoint();
var renameParams = t.model.copyWorksheet(0, insertBefore, name, undefined, undefined, undefined, pastedWs);
callback(renameParams);
};
var api = window["Asc"]["editor"];
api._loadFonts(newFonts, function () {
if (aPastedImages && aPastedImages.length) {
pasteProcessor._loadImagesOnServer(aPastedImages, function () {
doCopy();
});
} else {
doCopy();
}
});
};
//------------------------------------------------------------export---------------------------------------------------
window['AscCommonExcel'] = window['AscCommonExcel'] || {};
window["AscCommonExcel"].WorkbookView = WorkbookView;
})(window);
| cell/view/WorkbookView.js | /*
* (c) Copyright Ascensio System SIA 2010-2019
*
* This program is a free software product. You can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License (AGPL)
* version 3 as published by the Free Software Foundation. In accordance with
* Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
* that Ascensio System SIA expressly excludes the warranty of non-infringement
* of any third-party rights.
*
* This program is distributed WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For
* details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
*
* You can contact Ascensio System SIA at 20A-12 Ernesta Birznieka-Upisha
* street, Riga, Latvia, EU, LV-1050.
*
* The interactive user interfaces in modified source and object code versions
* of the Program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU AGPL version 3.
*
* Pursuant to Section 7(b) of the License you must retain the original Product
* logo when distributing the program. Pursuant to Section 7(e) we decline to
* grant you any rights under trademark law for use of our trademarks.
*
* All the Product's GUI elements, including illustrations and icon sets, as
* well as technical writing content are licensed under the terms of the
* Creative Commons Attribution-ShareAlike 4.0 International. See the License
* terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
*
*/
"use strict";
(/**
* @param {Window} window
* @param {undefined} undefined
*/
function(window, undefined) {
/*
* Import
* -----------------------------------------------------------------------------
*/
var c_oAscFormatPainterState = AscCommon.c_oAscFormatPainterState;
var AscBrowser = AscCommon.AscBrowser;
var CColor = AscCommon.CColor;
var cBoolLocal = AscCommon.cBoolLocal;
var History = AscCommon.History;
var asc = window["Asc"];
var asc_applyFunction = AscCommonExcel.applyFunction;
var asc_round = asc.round;
var asc_typeof = asc.typeOf;
var asc_CMM = AscCommonExcel.asc_CMouseMoveData;
var asc_CPrintPagesData = AscCommonExcel.CPrintPagesData;
var c_oTargetType = AscCommonExcel.c_oTargetType;
var c_oAscError = asc.c_oAscError;
var c_oAscCleanOptions = asc.c_oAscCleanOptions;
var c_oAscSelectionDialogType = asc.c_oAscSelectionDialogType;
var c_oAscMouseMoveType = asc.c_oAscMouseMoveType;
var c_oAscPopUpSelectorType = asc.c_oAscPopUpSelectorType;
var c_oAscAsyncAction = asc.c_oAscAsyncAction;
var c_oAscFontRenderingModeType = asc.c_oAscFontRenderingModeType;
var c_oAscAsyncActionType = asc.c_oAscAsyncActionType;
var g_clipboardExcel = AscCommonExcel.g_clipboardExcel;
function WorkbookCommentsModel(handlers, aComments) {
this.workbook = {handlers: handlers};
this.aComments = aComments;
}
WorkbookCommentsModel.prototype.getId = function() {
return null;
};
WorkbookCommentsModel.prototype.getMergedByCell = function() {
return null;
};
function WorksheetViewSettings() {
this.header = {
style: [// Header colors
{ // kHeaderDefault
background: new CColor(241, 241, 241), border: new CColor(213, 213, 213), color: new CColor(54, 54, 54)
}, { // kHeaderActive
background: new CColor(193, 193, 193), border: new CColor(146, 146, 146), color: new CColor(54, 54, 54)
}, { // kHeaderHighlighted
background: new CColor(223, 223, 223), border: new CColor(175, 175, 175), color: new CColor(101, 106, 112)
}, { // kHeaderSelected
background: new CColor(170, 170, 170), border: new CColor(117, 119, 122), color: new CColor(54, 54, 54)
}], cornerColor: new CColor(193, 193, 193)
};
this.cells = {
defaultState: {
background: new CColor(255, 255, 255), border: new CColor(202, 202, 202)
}, padding: -1 /*px horizontal padding*/
};
this.activeCellBorderColor = new CColor(72, 121, 92);
this.activeCellBorderColor2 = new CColor(255, 255, 255, 1);
this.findFillColor = new CColor(255, 238, 128, 1);
// Цвет закрепленных областей
this.frozenColor = new CColor(105, 119, 62, 1);
// Число знаков для математической информации
this.mathMaxDigCount = 9;
var cnv = document.createElement("canvas");
cnv.width = 2;
cnv.height = 2;
var ctx = cnv.getContext("2d");
ctx.clearRect(0, 0, 2, 2);
ctx.fillStyle = "#000";
ctx.fillRect(0, 0, 1, 1);
ctx.fillRect(1, 1, 1, 1);
this.ptrnLineDotted1 = ctx.createPattern(cnv, "repeat");
this.halfSelection = false;
return this;
}
/**
* Widget for displaying and editing Workbook object
* -----------------------------------------------------------------------------
* @param {AscCommonExcel.Workbook} model Workbook
* @param {AscCommonExcel.asc_CEventsController} controller Events controller
* @param {HandlersList} handlers Events handlers for WorkbookView events
* @param {Element} elem Container element
* @param {Element} inputElem Input element for top line editor
* @param {Object} Api
* @param {CCollaborativeEditing} collaborativeEditing
* @param {c_oAscFontRenderingModeType} fontRenderingMode
*
* @constructor
* @memberOf Asc
*/
function WorkbookView(model, controller, handlers, elem, inputElem, Api, collaborativeEditing, fontRenderingMode) {
this.defaults = {
scroll: {
widthPx: 14, heightPx: 14
}, worksheetView: new WorksheetViewSettings()
};
this.model = model;
this.enableKeyEvents = true;
this.controller = controller;
this.handlers = handlers;
this.wsViewHandlers = null;
this.element = elem;
this.input = inputElem;
this.Api = Api;
this.collaborativeEditing = collaborativeEditing;
this.lastSendInfoRange = null;
this.oSelectionInfo = null;
this.canUpdateAfterShiftUp = false; // Нужно ли обновлять информацию после отпускания Shift
this.keepType = false;
this.timerId = null;
this.timerEnd = false;
//----- declaration -----
this.isInit = false;
this.canvas = undefined;
this.canvasOverlay = undefined;
this.canvasGraphic = undefined;
this.canvasGraphicOverlay = undefined;
this.wsActive = -1;
this.wsMustDraw = false; // Означает, что мы выставили активный, но не отрисовали его
this.wsViews = [];
this.cellEditor = undefined;
this.fontRenderingMode = null;
this.lockDraw = false; // Lock отрисовки на некоторое время
this.isCellEditMode = false;
this.isShowComments = true;
this.isShowSolved = true;
this.formulasList = []; // Список всех формул
this.lastFPos = -1; // Последняя позиция формулы
this.lastFNameLength = ''; // Последний кусок формулы
this.skipHelpSelector = false; // Пока true - не показываем окно подсказки
// Константы для подстановке формулы (что не нужно добавлять скобки)
this.arrExcludeFormulas = [];
this.fReplaceCallback = null; // Callback для замены текста
// Фонт, который выставлен в DrawingContext, он должен быть один на все DrawingContext-ы
this.m_oFont = AscCommonExcel.g_oDefaultFormat.Font.clone();
// Теперь у нас 2 FontManager-а на весь документ + 1 для автофигур (а не на каждом листе свой)
this.fmgrGraphics = []; // FontManager for draw (1 для обычного + 1 для поворотного текста)
this.fmgrGraphics.push(new AscFonts.CFontManager({mode:"cell"})); // Для обычного
this.fmgrGraphics.push(new AscFonts.CFontManager({mode:"cell"})); // Для поворотного
this.fmgrGraphics.push(new AscFonts.CFontManager()); // Для автофигур
this.fmgrGraphics.push(new AscFonts.CFontManager({mode:"cell"})); // Для измерений
this.fmgrGraphics[0].Initialize(true); // IE memory enable
this.fmgrGraphics[1].Initialize(true); // IE memory enable
this.fmgrGraphics[2].Initialize(true); // IE memory enable
this.fmgrGraphics[3].Initialize(true); // IE memory enable
this.buffers = {};
this.drawingCtx = undefined;
this.overlayCtx = undefined;
this.drawingGraphicCtx = undefined;
this.overlayGraphicCtx = undefined;
this.shapeCtx = null;
this.shapeOverlayCtx = null;
this.mainGraphics = undefined;
this.stringRender = undefined;
this.trackOverlay = null;
this.autoShapeTrack = null;
this.stateFormatPainter = c_oAscFormatPainterState.kOff;
this.rangeFormatPainter = null;
this.selectionDialogMode = false;
this.dialogAbsName = false;
this.dialogSheetName = false;
this.copyActiveSheet = -1;
this.lastActiveSheet = -1;
// Комментарии для всего документа
this.cellCommentator = null;
// Флаг о подписке на эвенты о смене позиции документа (скролл) для меню
this.isDocumentPlaceChangedEnabled = false;
// Максимальная ширина числа из 0,1,2...,9, померенная в нормальном шрифте(дефалтовый для книги) в px(целое)
// Ecma-376 Office Open XML Part 1, пункт 18.3.1.13
this.maxDigitWidth = 0;
//-----------------------
this.MobileTouchManager = null;
this.defNameAllowCreate = true;
this._init(fontRenderingMode);
this.autoCorrectStore = null;//объект для хранения параметров иконки авторазвертывания таблиц
this.cutIdSheet = null;
return this;
}
WorkbookView.prototype._init = function(fontRenderingMode) {
var self = this;
// Init font managers rendering
// Изначально мы инициализируем c_oAscFontRenderingModeType.hintingAndSubpixeling
this.setFontRenderingMode(fontRenderingMode, /*isInit*/true);
// add style
var _head = document.getElementsByTagName('head')[0];
var style0 = document.createElement('style');
style0.type = 'text/css';
style0.innerHTML = ".block_elem { position:absolute;padding:0;margin:0; }";
_head.appendChild(style0);
// create canvas
if (null != this.element) {
this.element.innerHTML = '<div id="ws-canvas-outer">\
<canvas id="ws-canvas"></canvas>\
<canvas id="ws-canvas-overlay"></canvas>\
<canvas id="ws-canvas-graphic"></canvas>\
<canvas id="ws-canvas-graphic-overlay"></canvas>\
<canvas id="id_target_cursor" class="block_elem" width="1" height="1"\
style="width:2px;height:13px;display:none;z-index:9;"></canvas>\
</div>';
this.canvas = document.getElementById("ws-canvas");
this.canvasOverlay = document.getElementById("ws-canvas-overlay");
this.canvasGraphic = document.getElementById("ws-canvas-graphic");
this.canvasGraphicOverlay = document.getElementById("ws-canvas-graphic-overlay");
}
this.buffers.main = new asc.DrawingContext({
canvas: this.canvas, units: 0/*px*/, fmgrGraphics: this.fmgrGraphics, font: this.m_oFont
});
this.buffers.overlay = new asc.DrawingContext({
canvas: this.canvasOverlay, units: 0/*px*/, fmgrGraphics: this.fmgrGraphics, font: this.m_oFont
});
this.buffers.mainGraphic = new asc.DrawingContext({
canvas: this.canvasGraphic, units: 0/*px*/, fmgrGraphics: this.fmgrGraphics, font: this.m_oFont
});
this.buffers.overlayGraphic = new asc.DrawingContext({
canvas: this.canvasGraphicOverlay, units: 0/*px*/, fmgrGraphics: this.fmgrGraphics, font: this.m_oFont
});
this.drawingCtx = this.buffers.main;
this.overlayCtx = this.buffers.overlay;
this.drawingGraphicCtx = this.buffers.mainGraphic;
this.overlayGraphicCtx = this.buffers.overlayGraphic;
this.shapeCtx = new AscCommon.CGraphics();
this.shapeOverlayCtx = new AscCommon.CGraphics();
this.mainGraphics = new AscCommon.CGraphics();
this.trackOverlay = new AscCommon.COverlay();
this.trackOverlay.IsCellEditor = true;
this.autoShapeTrack = new AscCommon.CAutoshapeTrack();
this.shapeCtx.m_oAutoShapesTrack = this.autoShapeTrack;
this.shapeCtx.m_oFontManager = this.fmgrGraphics[2];
this.shapeOverlayCtx.m_oFontManager = this.fmgrGraphics[2];
this.mainGraphics.m_oFontManager = this.fmgrGraphics[0];
// Обновляем размеры (чуть ниже, потому что должны быть проинициализированы ctx)
this._canResize();
this.stringRender = new AscCommonExcel.StringRender(this.buffers.main);
// Мерить нужно только со 100% и один раз для всего документа
this._calcMaxDigitWidth();
if (!window["NATIVE_EDITOR_ENJINE"]) {
// initialize events controller
this.controller.init(this, this.element, /*this.canvasOverlay*/ this.canvasGraphicOverlay, /*handlers*/{
"resize": function () {
self.resize.apply(self, arguments);
}, "initRowsCount": function () {
self._onInitRowsCount.apply(self, arguments);
}, "initColsCount": function () {
self._onInitColsCount.apply(self, arguments);
}, "scrollY": function () {
self._onScrollY.apply(self, arguments);
}, "scrollX": function () {
self._onScrollX.apply(self, arguments);
}, "changeSelection": function () {
self._onChangeSelection.apply(self, arguments);
}, "changeSelectionDone": function () {
self._onChangeSelectionDone.apply(self, arguments);
}, "changeSelectionRightClick": function () {
self._onChangeSelectionRightClick.apply(self, arguments);
}, "selectionActivePointChanged": function () {
self._onSelectionActivePointChanged.apply(self, arguments);
}, "updateWorksheet": function () {
self._onUpdateWorksheet.apply(self, arguments);
}, "resizeElement": function () {
self._onResizeElement.apply(self, arguments);
}, "resizeElementDone": function () {
self._onResizeElementDone.apply(self, arguments);
}, "changeFillHandle": function () {
self._onChangeFillHandle.apply(self, arguments);
}, "changeFillHandleDone": function () {
self._onChangeFillHandleDone.apply(self, arguments);
}, "moveRangeHandle": function () {
self._onMoveRangeHandle.apply(self, arguments);
}, "moveRangeHandleDone": function () {
self._onMoveRangeHandleDone.apply(self, arguments);
}, "moveResizeRangeHandle": function () {
self._onMoveResizeRangeHandle.apply(self, arguments);
}, "moveResizeRangeHandleDone": function () {
self._onMoveResizeRangeHandleDone.apply(self, arguments);
}, "editCell": function () {
self._onEditCell.apply(self, arguments);
}, "stopCellEditing": function () {
return self._onStopCellEditing.apply(self, arguments);
}, "isRestrictionComments": function () {
return self.Api.isRestrictionComments();
}, "empty": function () {
self._onEmpty.apply(self, arguments);
}, "canEnterCellRange": function () {
self.cellEditor.setFocus(false);
var ret = self.cellEditor.canEnterCellRange();
ret ? self.cellEditor.activateCellRange() : true;
return ret;
}, "enterCellRange": function () {
self.lockDraw = true;
self.skipHelpSelector = true;
self.cellEditor.setFocus(false);
self.getWorksheet().enterCellRange(self.cellEditor);
self.skipHelpSelector = false;
self.lockDraw = false;
}, "undo": function () {
self.undo.apply(self, arguments);
}, "redo": function () {
self.redo.apply(self, arguments);
}, "mouseDblClick": function () {
self._onMouseDblClick.apply(self, arguments);
}, "showNextPrevWorksheet": function () {
self._onShowNextPrevWorksheet.apply(self, arguments);
}, "setFontAttributes": function () {
self._onSetFontAttributes.apply(self, arguments);
}, "setCellFormat": function () {
self._onSetCellFormat.apply(self, arguments);
}, "selectColumnsByRange": function () {
self._onSelectColumnsByRange.apply(self, arguments);
}, "selectRowsByRange": function () {
self._onSelectRowsByRange.apply(self, arguments);
}, "save": function () {
self.Api.asc_Save();
}, "showCellEditorCursor": function () {
self._onShowCellEditorCursor.apply(self, arguments);
}, "print": function () {
self.Api.onPrint();
}, "addFunction": function () {
self.insertInCellEditor.apply(self, arguments);
}, "canvasClick": function () {
self.enableKeyEventsHandler(true);
}, "autoFiltersClick": function () {
self._onAutoFiltersClick.apply(self, arguments);
}, "commentCellClick": function () {
self._onCommentCellClick.apply(self, arguments);
}, "isGlobalLockEditCell": function () {
return self.collaborativeEditing.getGlobalLockEditCell();
}, "updateSelectionName": function () {
self._onUpdateSelectionName.apply(self, arguments);
}, "stopFormatPainter": function () {
self._onStopFormatPainter.apply(self, arguments);
}, "groupRowClick": function () {
return self._onGroupRowClick.apply(self, arguments);
},
// Shapes
"graphicObjectMouseDown": function () {
self._onGraphicObjectMouseDown.apply(self, arguments);
}, "graphicObjectMouseMove": function () {
self._onGraphicObjectMouseMove.apply(self, arguments);
}, "graphicObjectMouseUp": function () {
self._onGraphicObjectMouseUp.apply(self, arguments);
}, "graphicObjectMouseUpEx": function () {
self._onGraphicObjectMouseUpEx.apply(self, arguments);
}, "graphicObjectWindowKeyDown": function () {
return self._onGraphicObjectWindowKeyDown.apply(self, arguments);
}, "graphicObjectWindowKeyPress": function () {
return self._onGraphicObjectWindowKeyPress.apply(self, arguments);
}, "getGraphicsInfo": function () {
return self._onGetGraphicsInfo.apply(self, arguments);
}, "updateSelectionShape": function () {
return self._onUpdateSelectionShape.apply(self, arguments);
}, "canReceiveKeyPress": function () {
return self.getWorksheet().objectRender.controller.canReceiveKeyPress();
}, "stopAddShape": function () {
self.getWorksheet().objectRender.controller.checkEndAddShape();
},
// Frozen anchor
"moveFrozenAnchorHandle": function () {
self._onMoveFrozenAnchorHandle.apply(self, arguments);
}, "moveFrozenAnchorHandleDone": function () {
self._onMoveFrozenAnchorHandleDone.apply(self, arguments);
},
// AutoComplete
"showAutoComplete": function () {
self.showAutoComplete.apply(self, arguments);
}, "onContextMenu": function (event) {
self.handlers.trigger("asc_onContextMenu", event);
},
// DataValidation
"onDataValidation": function () {
if (self.oSelectionInfo && self.oSelectionInfo.dataValidation) {
self.handlers.trigger("asc_onValidationListMenu", self.oSelectionInfo.dataValidation.getListValues(self.model.getActiveWs()));
}
},
// FormatPainter
'isFormatPainter': function () {
return self.stateFormatPainter;
},
//calculate
'calculate': function () {
self.calculate.apply(self, arguments);
},
'changeFormatTableInfo': function () {
var table = self.getSelectionInfo().formatTableInfo;
return table && self.changeFormatTableInfo(table.tableName, Asc.c_oAscChangeTableStyleInfo.rowTotal, !table.lastRow);
},
//special paste
"hideSpecialPasteOptions": function () {
self.handlers.trigger("hideSpecialPasteOptions");
}
});
if (this.input && this.input.addEventListener) {
this.input.addEventListener("focus", function () {
self.input.isFocused = true;
if (!self.canEdit()) {
return;
}
self._onStopFormatPainter();
self.controller.setStrictClose(true);
self.cellEditor.callTopLineMouseup = true;
if (!self.getCellEditMode() && !self.controller.isFillHandleMode) {
self._onEditCell(/*isFocus*/true);
}
}, false);
this.input.addEventListener('keydown', function (event) {
if (self.isCellEditMode) {
self.handlers.trigger('asc_onInputKeyDown', event);
if (!event.defaultPrevented) {
self.cellEditor._onWindowKeyDown(event, true);
}
}
}, false);
}
this.Api.onKeyDown = function (event) {
self.controller._onWindowKeyDown(event);
if (self.isCellEditMode) {
self.cellEditor._onWindowKeyDown(event, false);
}
};
this.Api.onKeyPress = function (event) {
self.controller._onWindowKeyPress(event);
if (self.isCellEditMode) {
self.cellEditor._onWindowKeyPress(event);
}
};
this.Api.onKeyUp = function (event) {
self.controller._onWindowKeyUp(event);
if (self.isCellEditMode) {
self.cellEditor._onWindowKeyUp(event);
}
};
this.Api.Begin_CompositeInput = function () {
var oWSView = self.getWorksheet();
if (oWSView && oWSView.isSelectOnShape) {
if (oWSView.objectRender) {
oWSView.objectRender.Begin_CompositeInput();
}
return;
}
if (!self.isCellEditMode) {
self._onEditCell(false, true, undefined, true, function () {
self.cellEditor.Begin_CompositeInput();
});
} else {
self.cellEditor.Begin_CompositeInput();
}
};
this.Api.Replace_CompositeText = function (arrCharCodes) {
var oWSView = self.getWorksheet();
if(oWSView && oWSView.isSelectOnShape){
if(oWSView.objectRender){
oWSView.objectRender.Replace_CompositeText(arrCharCodes);
}
return;
}
if (self.isCellEditMode) {
self.cellEditor.Replace_CompositeText(arrCharCodes);
}
};
this.Api.End_CompositeInput = function () {
var oWSView = self.getWorksheet();
if(oWSView && oWSView.isSelectOnShape){
if(oWSView.objectRender){
oWSView.objectRender.End_CompositeInput();
}
return;
}
if (self.isCellEditMode) {
self.cellEditor.End_CompositeInput();
}
};
this.Api.Set_CursorPosInCompositeText = function (nPos) {
var oWSView = self.getWorksheet();
if(oWSView && oWSView.isSelectOnShape){
if(oWSView.objectRender){
oWSView.objectRender.Set_CursorPosInCompositeText(nPos);
}
return;
}
if (self.isCellEditMode) {
self.cellEditor.Set_CursorPosInCompositeText(nPos);
}
};
this.Api.Get_CursorPosInCompositeText = function () {
var res = 0;
var oWSView = self.getWorksheet();
if(oWSView && oWSView.isSelectOnShape){
if(oWSView.objectRender){
res = oWSView.objectRender.Get_CursorPosInCompositeText();
}
}
else if (self.isCellEditMode) {
res = self.cellEditor.Get_CursorPosInCompositeText();
}
return res;
};
this.Api.Get_MaxCursorPosInCompositeText = function () {
var res = 0; var oWSView = self.getWorksheet();
if(oWSView && oWSView.isSelectOnShape){
if(oWSView.objectRender){
res = oWSView.objectRender.Get_CursorPosInCompositeText();
}
}
else if (self.isCellEditMode) {
res = self.cellEditor.Get_MaxCursorPosInCompositeText();
}
return res;
};
this.Api.AddTextWithPr = function (familyName, arrCharCodes) {
var ws = self.getWorksheet();
if (ws && ws.isSelectOnShape) {
var textPr = new CTextPr();
textPr.RFonts = new CRFonts();
textPr.RFonts.Set_All(familyName, -1);
ws.objectRender.controller.addTextWithPr(new AscCommon.CUnicodeStringEmulator(arrCharCodes), textPr, true);
return;
}
if (!self.isCellEditMode) {
self._onEditCell(undefined, undefined, undefined, false, function () {
self.cellEditor.setTextStyle('fn', familyName);
self.cellEditor._addCharCodes(arrCharCodes);
});
} else {
self.cellEditor.setTextStyle('fn', familyName);
self.cellEditor._addCharCodes(arrCharCodes);
}
};
this.Api.beginInlineDropTarget = function (event) {
if (!self.controller.isMoveRangeMode) {
self.controller.isMoveRangeMode = true;
self.getWorksheet().dragAndDropRange = new Asc.Range(0, 0, 0, 0);
}
self.controller._onMouseMove(event);
};
this.Api.endInlineDropTarget = function (event) {
self.controller.isMoveRangeMode = false;
var ws = self.getWorksheet();
var newSelection = ws.activeMoveRange.clone();
ws._cleanSelectionMoveRange();
ws.dragAndDropRange = null;
self._onSetSelection(newSelection);
};
this.Api.isEnabledDropTarget = function () {
return !self.isCellEditMode;
};
AscCommon.InitBrowserInputContext(this.Api, "id_target_cursor");
this.model.dependencyFormulas.calcTree();
}
this.cellEditor =
new AscCommonExcel.CellEditor(this.element, this.input, this.fmgrGraphics, this.m_oFont, /*handlers*/{
"closed": function () {
self._onCloseCellEditor.apply(self, arguments);
}, "updated": function () {
self.Api.checkLastWork();
self._onUpdateCellEditor.apply(self, arguments);
}, "gotFocus": function (hasFocus) {
self.controller.setFocus(!hasFocus);
}, "updateFormulaEditMod": function () {
self.controller.setFormulaEditMode.apply(self.controller, arguments);
var ws = self.getWorksheet();
if (ws) {
if (!self.lockDraw) {
ws.cleanSelection();
}
for (var i in self.wsViews) {
self.wsViews[i].cleanFormulaRanges();
}
// ws.cleanFormulaRanges();
ws.setFormulaEditMode.apply(ws, arguments);
}
}, "updateEditorState": function (state) {
self.handlers.trigger("asc_onEditCell", state);
}, "isGlobalLockEditCell": function () {
return self.collaborativeEditing.getGlobalLockEditCell();
}, "updateFormulaEditModEnd": function () {
if (!self.lockDraw) {
self.getWorksheet().updateSelection();
}
}, "newRange": function (range, ws) {
if (!ws) {
self.getWorksheet().addFormulaRange(range);
} else {
self.getWorksheet(self.model.getWorksheetIndexByName(ws)).addFormulaRange(range);
}
}, "existedRange": function (range, ws) {
var editRangeSheet = ws ? self.model.getWorksheetIndexByName(ws) : self.lastActiveSheet;
if (-1 === editRangeSheet || editRangeSheet === self.wsActive) {
self.getWorksheet().activeFormulaRange(range);
} else {
self.getWorksheet(editRangeSheet).removeFormulaRange(range);
self.getWorksheet().addFormulaRange(range);
}
}, "updateUndoRedoChanged": function (bCanUndo, bCanRedo) {
self.handlers.trigger("asc_onCanUndoChanged", bCanUndo);
self.handlers.trigger("asc_onCanRedoChanged", bCanRedo);
}, "applyCloseEvent": function () {
self.controller._onWindowKeyDown.apply(self.controller, arguments);
}, "canEdit": function () {
return self.canEdit();
}, "getFormulaRanges": function () {
return (self.cellFormulaEnterWSOpen || self.getWorksheet()).getFormulaRanges();
}, "isActive": function () {
return self.isActive();
}, "getSelectionDialogMode": function () {
return self.selectionDialogMode;
}, "getCellFormulaEnterWSOpen": function () {
return self.cellFormulaEnterWSOpen;
}, "getActiveWS": function () {
return self.getWorksheet().model;
}, "setStrictClose": function (val) {
self.controller.setStrictClose(val);
}, "updateEditorSelectionInfo": function (info) {
self.handlers.trigger("asc_onEditorSelectionChanged", info);
}, "onContextMenu": function (event) {
self.handlers.trigger("asc_onContextMenu", event);
}, "updatedEditableFunction": function (fName) {
self.handlers.trigger("asc_onFormulaInfo", fName);
}
}, this.defaults.worksheetView.cells.padding);
this.wsViewHandlers = new AscCommonExcel.asc_CHandlersList(/*handlers*/{
"getViewMode": function () {
return self.Api.getViewMode();
}, "isRestrictionComments": function () {
return self.Api.isRestrictionComments();
}, "reinitializeScroll": function (type) {
self._onScrollReinitialize(type);
}, "selectionChanged": function () {
self._onWSSelectionChanged();
}, "selectionNameChanged": function () {
self._onSelectionNameChanged.apply(self, arguments);
}, "selectionMathInfoChanged": function () {
self._onSelectionMathInfoChanged.apply(self, arguments);
}, 'onFilterInfo': function (countFilter, countRecords) {
self.handlers.trigger("asc_onFilterInfo", countFilter, countRecords);
}, "onErrorEvent": function (errorId, level) {
self.handlers.trigger("asc_onError", errorId, level);
}, "slowOperation": function (isStart) {
(isStart ? self.Api.sync_StartAction : self.Api.sync_EndAction).call(self.Api,
c_oAscAsyncActionType.BlockInteraction, c_oAscAsyncAction.SlowOperation);
}, "setAutoFiltersDialog": function (arrVal) {
self.handlers.trigger("asc_onSetAFDialog", arrVal);
}, "selectionRangeChanged": function (val) {
self.handlers.trigger("asc_onSelectionRangeChanged", val);
}, "onRenameCellTextEnd": function (countFind, countReplace) {
self.handlers.trigger("asc_onRenameCellTextEnd", countFind, countReplace);
}, 'onStopFormatPainter': function () {
self._onStopFormatPainter();
}, 'getRangeFormatPainter': function () {
return self.rangeFormatPainter;
}, "onDocumentPlaceChanged": function () {
self._onDocumentPlaceChanged();
}, "updateSheetViewSettings": function () {
self.handlers.trigger("asc_onUpdateSheetViewSettings");
}, "onScroll": function (d) {
self.controller.scroll(d);
}, "getLockDefNameManagerStatus": function () {
return self.defNameAllowCreate;
}, 'isActive': function () {
return self.isActive();
}, "drawMobileSelection": function (color) {
if (self.MobileTouchManager) {
self.MobileTouchManager.CheckSelect(self.trackOverlay, color);
}
}, "showSpecialPasteOptions": function (val) {
self.handlers.trigger("asc_onShowSpecialPasteOptions", val);
if (!window['AscCommon'].g_specialPasteHelper.showSpecialPasteButton) {
window['AscCommon'].g_specialPasteHelper.showSpecialPasteButton = true;
}
}, 'checkLastWork': function () {
self.Api.checkLastWork();
}, "toggleAutoCorrectOptions": function (bIsShow, val) {
self.toggleAutoCorrectOptions(bIsShow, val);
}, "selectSearchingResults": function () {
return self.Api.selectSearchingResults;
}, "getMainGraphics": function () {
return self.mainGraphics;
}, "cleanCutData": function (bDrawSelection, bCleanBuffer) {
self.cleanCutData(bDrawSelection, bCleanBuffer);
}
});
this.model.handlers.add("cleanCellCache", function(wsId, oRanges, skipHeight) {
var ws = self.getWorksheetById(wsId, true);
if (ws) {
ws.updateRanges(oRanges, skipHeight);
}
});
this.model.handlers.add("changeWorksheetUpdate", function(wsId, val) {
var ws = self.getWorksheetById(wsId);
if (ws) {
ws.changeWorksheet("update", val);
}
});
this.model.handlers.add("showWorksheet", function(wsId) {
var wsModel = self.model.getWorksheetById(wsId), index;
if (wsModel) {
index = wsModel.getIndex();
self.showWorksheet(index, true);
}
});
this.model.handlers.add("setSelection", function() {
self._onSetSelection.apply(self, arguments);
});
this.model.handlers.add("getSelectionState", function() {
return self._onGetSelectionState.apply(self);
});
this.model.handlers.add("setSelectionState", function() {
self._onSetSelectionState.apply(self, arguments);
});
this.model.handlers.add("reInit", function() {
self.reInit.apply(self, arguments);
});
this.model.handlers.add("drawWS", function() {
self.drawWS.apply(self, arguments);
});
this.model.handlers.add("showDrawingObjects", function() {
self.onShowDrawingObjects.apply(self, arguments);
});
this.model.handlers.add("setCanUndo", function(bCanUndo) {
self.handlers.trigger("asc_onCanUndoChanged", bCanUndo);
});
this.model.handlers.add("setCanRedo", function(bCanRedo) {
self.handlers.trigger("asc_onCanRedoChanged", bCanRedo);
});
this.model.handlers.add("setDocumentModified", function(bIsModified) {
self.Api.onUpdateDocumentModified(bIsModified);
});
this.model.handlers.add("updateWorksheetByModel", function() {
self.updateWorksheetByModel.apply(self, arguments);
});
this.model.handlers.add("undoRedoAddRemoveRowCols", function(sheetId, type, range, bUndo) {
if (true === bUndo) {
if (AscCH.historyitem_Worksheet_AddRows === type) {
self.collaborativeEditing.removeRowsRange(sheetId, range.clone(true));
self.collaborativeEditing.undoRows(sheetId, range.r2 - range.r1 + 1);
} else if (AscCH.historyitem_Worksheet_RemoveRows === type) {
self.collaborativeEditing.addRowsRange(sheetId, range.clone(true));
self.collaborativeEditing.undoRows(sheetId, range.r2 - range.r1 + 1);
} else if (AscCH.historyitem_Worksheet_AddCols === type) {
self.collaborativeEditing.removeColsRange(sheetId, range.clone(true));
self.collaborativeEditing.undoCols(sheetId, range.c2 - range.c1 + 1);
} else if (AscCH.historyitem_Worksheet_RemoveCols === type) {
self.collaborativeEditing.addColsRange(sheetId, range.clone(true));
self.collaborativeEditing.undoCols(sheetId, range.c2 - range.c1 + 1);
}
} else {
if (AscCH.historyitem_Worksheet_AddRows === type) {
self.collaborativeEditing.addRowsRange(sheetId, range.clone(true));
self.collaborativeEditing.addRows(sheetId, range.r1, range.r2 - range.r1 + 1);
} else if (AscCH.historyitem_Worksheet_RemoveRows === type) {
self.collaborativeEditing.removeRowsRange(sheetId, range.clone(true));
self.collaborativeEditing.removeRows(sheetId, range.r1, range.r2 - range.r1 + 1);
} else if (AscCH.historyitem_Worksheet_AddCols === type) {
self.collaborativeEditing.addColsRange(sheetId, range.clone(true));
self.collaborativeEditing.addCols(sheetId, range.c1, range.c2 - range.c1 + 1);
} else if (AscCH.historyitem_Worksheet_RemoveCols === type) {
self.collaborativeEditing.removeColsRange(sheetId, range.clone(true));
self.collaborativeEditing.removeCols(sheetId, range.c1, range.c2 - range.c1 + 1);
}
}
});
this.model.handlers.add("undoRedoHideSheet", function(sheetId) {
self.showWorksheet(sheetId);
// Посылаем callback об изменении списка листов
self.Api.sheetsChanged();
});
this.model.handlers.add("updateSelection", function () {
if (!self.lockDraw) {
self.getWorksheet().updateSelection();
}
});
this.handlers.add("asc_onLockDefNameManager", function(reason) {
self.defNameAllowCreate = !(reason == Asc.c_oAscDefinedNameReason.LockDefNameManager);
});
this.handlers.add('addComment', function (id, data) {
self._onWSSelectionChanged();
self.handlers.trigger('asc_onAddComment', id, data);
});
this.handlers.add('removeComment', function (id) {
self._onWSSelectionChanged();
self.handlers.trigger('asc_onRemoveComment', id);
});
this.handlers.add('hiddenComments', function () {
return !self.isShowComments;
});
this.handlers.add('showSolved', function () {
return self.isShowSolved;
});
this.model.handlers.add("hideSpecialPasteOptions", function() {
self.handlers.trigger("asc_onHideSpecialPasteOptions");
});
this.model.handlers.add("toggleAutoCorrectOptions", function(bIsShow, val) {
self.toggleAutoCorrectOptions(bIsShow, val);
});
this.model.handlers.add("cleanCutData", function(bDrawSelection, bCleanBuffer) {
self.cleanCutData(bDrawSelection, bCleanBuffer);
});
this.model.handlers.add("updateGroupData", function() {
self.updateGroupData();
});
this.cellCommentator = new AscCommonExcel.CCellCommentator({
model: new WorkbookCommentsModel(this.handlers, this.model.aComments),
collaborativeEditing: this.collaborativeEditing,
draw: function() {
},
handlers: {
trigger: function() {
return false;
}
}
});
if (0 < this.model.aComments.length) {
this.handlers.trigger("asc_onAddComments", this.model.aComments);
}
this.initFormulasList();
this.fReplaceCallback = function() {
self._replaceCellTextCallback.apply(self, arguments);
};
return this;
};
WorkbookView.prototype.destroy = function() {
this.controller.destroy();
this.cellEditor.destroy();
return this;
};
WorkbookView.prototype._createWorksheetView = function(wsModel) {
return new AscCommonExcel.WorksheetView(this, wsModel, this.wsViewHandlers, this.buffers, this.stringRender, this.maxDigitWidth, this.collaborativeEditing, this.defaults.worksheetView);
};
WorkbookView.prototype._onSelectionNameChanged = function(name) {
this.handlers.trigger("asc_onSelectionNameChanged", name);
};
WorkbookView.prototype._onSelectionMathInfoChanged = function(info) {
this.handlers.trigger("asc_onSelectionMathChanged", info);
};
// Проверяет, сменили ли мы диапазон (для того, чтобы не отправлять одинаковую информацию о диапазоне)
WorkbookView.prototype._isEqualRange = function(range, isSelectOnShape) {
if (null === this.lastSendInfoRange) {
return false;
}
return this.lastSendInfoRange.isEqual(range) && this.lastSendInfoRangeIsSelectOnShape === isSelectOnShape;
};
WorkbookView.prototype._updateSelectionInfo = function () {
var ws = this.cellFormulaEnterWSOpen ? this.cellFormulaEnterWSOpen : this.getWorksheet();
this.oSelectionInfo = ws.getSelectionInfo();
this.lastSendInfoRange = ws.model.selectionRange.clone();
this.lastSendInfoRangeIsSelectOnShape = ws.getSelectionShape();
};
WorkbookView.prototype._onWSSelectionChanged = function(isSaving) {
this._updateSelectionInfo();
// При редактировании ячейки не нужно пересылать изменения
if (this.input && !this.getCellEditMode() && !this.selectionDialogMode) {
// Сами запретим заходить в строку формул, когда выделен shape
if (this.lastSendInfoRangeIsSelectOnShape) {
this.input.disabled = true;
this.input.value = '';
} else {
this.input.disabled = false;
this.input.value = this.oSelectionInfo.text;
}
}
this.handlers.trigger("asc_onSelectionChanged", this.oSelectionInfo);
this.handlers.trigger("asc_onSelectionEnd");
this._onInputMessage();
if (!isSaving) {
this.Api.cleanSpelling();
}
};
WorkbookView.prototype._onInputMessage = function () {
var title = null, message = null;
var dataValidation = this.oSelectionInfo && this.oSelectionInfo.dataValidation;
if (dataValidation && dataValidation.showInputMessage && !this.model.getActiveWs().getDisablePrompts()) {
title = dataValidation.promptTitle;
message = dataValidation.promt;
}
this.handlers.trigger("asc_onInputMessage", title, message);
};
WorkbookView.prototype._onScrollReinitialize = function (type) {
if (window["NATIVE_EDITOR_ENJINE"] || !type) {
return;
}
var ws = this.getWorksheet();
if (AscCommonExcel.c_oAscScrollType.ScrollHorizontal & type) {
this.controller.reinitScrollX(ws.getFirstVisibleCol(true), ws.getHorizontalScrollRange(), ws.getHorizontalScrollMax());
}
if (AscCommonExcel.c_oAscScrollType.ScrollVertical & type) {
this.controller.reinitScrollY(ws.getFirstVisibleRow(true), ws.getVerticalScrollRange(), ws.getVerticalScrollMax());
}
if (this.Api.isMobileVersion) {
this.MobileTouchManager.Resize();
}
};
WorkbookView.prototype._onInitRowsCount = function () {
var ws = this.getWorksheet();
if (ws._initRowsCount()) {
this._onScrollReinitialize(AscCommonExcel.c_oAscScrollType.ScrollVertical);
}
};
WorkbookView.prototype._onInitColsCount = function () {
var ws = this.getWorksheet();
if (ws._initColsCount()) {
this._onScrollReinitialize(AscCommonExcel.c_oAscScrollType.ScrollHorizontal);
}
};
WorkbookView.prototype._onScrollY = function(pos, initRowsCount) {
var ws = this.getWorksheet();
var delta = asc_round(pos - ws.getFirstVisibleRow(true));
if (delta !== 0) {
ws.scrollVertical(delta, this.cellEditor, initRowsCount);
}
};
WorkbookView.prototype._onScrollX = function(pos, initColsCount) {
var ws = this.getWorksheet();
var delta = asc_round(pos - ws.getFirstVisibleCol(true));
if (delta !== 0) {
ws.scrollHorizontal(delta, this.cellEditor, initColsCount);
}
};
WorkbookView.prototype._onSetSelection = function(range) {
var ws = this.getWorksheet();
ws._endSelectionShape();
ws.setSelection(range);
};
WorkbookView.prototype._onGetSelectionState = function() {
var res = null;
var ws = this.getWorksheet(null, true);
if (ws && AscCommon.isRealObject(ws.objectRender) && AscCommon.isRealObject(ws.objectRender.controller)) {
res = ws.objectRender.controller.getSelectionState();
}
return (res && res[0] && res[0].focus) ? res : null;
};
WorkbookView.prototype._onSetSelectionState = function(state) {
if (null !== state) {
var ws = this.getWorksheetById(state[0].worksheetId);
if (ws && ws.objectRender && ws.objectRender.controller) {
ws.objectRender.controller.setSelectionState(state);
ws.setSelectionShape(true);
ws._scrollToRange(ws.objectRender.getSelectedDrawingsRange());
ws.objectRender.showDrawingObjectsEx(true);
ws.objectRender.controller.updateOverlay();
ws.objectRender.controller.updateSelectionState();
}
// Селектим после выставления состояния
}
};
WorkbookView.prototype._onChangeSelection = function (isStartPoint, dc, dr, isCoord, isCtrl, callback) {
var ws = this.getWorksheet();
var t = this;
var d = isStartPoint ? ws.changeSelectionStartPoint(dc, dr, isCoord, isCtrl) :
ws.changeSelectionEndPoint(dc, dr, isCoord, isCoord && this.keepType);
if (!isCoord && !isStartPoint) {
// Выделение с зажатым shift
this.canUpdateAfterShiftUp = true;
}
this.keepType = isCoord;
if (isCoord && !this.timerEnd && this.timerId === null) {
this.timerId = setTimeout(function () {
var arrClose = [];
arrClose.push(new asc_CMM({type: c_oAscMouseMoveType.None}));
t.handlers.trigger("asc_onMouseMove", arrClose);
t._onUpdateCursor(AscCommonExcel.kCurCells);
t.timerId = null;
t.timerEnd = true;
},1000);
}
asc_applyFunction(callback, d);
};
// Окончание выделения
WorkbookView.prototype._onChangeSelectionDone = function(x, y, event) {
if (this.timerId !== null) {
clearTimeout(this.timerId);
this.timerId = null;
}
this.keepType = false;
if (this.selectionDialogMode) {
return;
}
var ws = this.getWorksheet();
ws.changeSelectionDone();
this._onSelectionNameChanged(ws.getSelectionName(/*bRangeText*/false));
// Проверим, нужно ли отсылать информацию о ячейке
var ar = ws.model.selectionRange.getLast();
var isSelectOnShape = ws.getSelectionShape();
if (!this._isEqualRange(ws.model.selectionRange, isSelectOnShape)) {
this._onWSSelectionChanged();
this._onSelectionMathInfoChanged(ws.getSelectionMathInfo());
}
// Нужно очистить поиск
this.model.cleanFindResults();
var ct = ws.getCursorTypeFromXY(x, y);
if (c_oTargetType.Hyperlink === ct.target && !this.controller.isFormulaEditMode) {
// Проверим замерженность
var isHyperlinkClick = false;
if(isSelectOnShape) {
var button = 0;
if(event) {
button = AscCommon.getMouseButton(event);
}
if(button === 0) {
isHyperlinkClick = true;
}
}
else if(ar.isOneCell()) {
isHyperlinkClick = true;
}
else {
var mergedRange = ws.model.getMergedByCell(ar.r1, ar.c1);
if (mergedRange && ar.isEqual(mergedRange)) {
isHyperlinkClick = true;
}
}
if (isHyperlinkClick && !this.timerEnd) {
if (false === ct.hyperlink.hyperlinkModel.getVisited() && !isSelectOnShape) {
ct.hyperlink.hyperlinkModel.setVisited(true);
if (ct.hyperlink.hyperlinkModel.Ref) {
ws._updateRange(ct.hyperlink.hyperlinkModel.Ref.getBBox0());
ws.draw();
}
}
switch (ct.hyperlink.asc_getType()) {
case Asc.c_oAscHyperlinkType.WebLink:
this.handlers.trigger("asc_onHyperlinkClick", ct.hyperlink.asc_getHyperlinkUrl());
break;
case Asc.c_oAscHyperlinkType.RangeLink:
// ToDo надо поправить отрисовку комментария для данной ячейки (с которой уходим)
this.handlers.trigger("asc_onHideComment");
this.Api._asc_setWorksheetRange(ct.hyperlink);
break;
}
}
}
this.timerEnd = false;
};
// Обработка нажатия правой кнопки мыши
WorkbookView.prototype._onChangeSelectionRightClick = function(dc, dr, target) {
var ws = this.getWorksheet();
ws.changeSelectionStartPointRightClick(dc, dr, target);
};
// Обработка движения в выделенной области
WorkbookView.prototype._onSelectionActivePointChanged = function(dc, dr, callback) {
var ws = this.getWorksheet();
var d = ws.changeSelectionActivePoint(dc, dr);
asc_applyFunction(callback, d);
};
WorkbookView.prototype._onUpdateWorksheet = function(x, y, ctrlKey, callback) {
var ws = this.getWorksheet(), ct = undefined;
var arrMouseMoveObjects = []; // Теперь это массив из объектов, над которыми курсор
var t = this;
//ToDo: включить определение target, если находимся в режиме редактирования ячейки.
if (x === undefined && y === undefined) {
ws.cleanHighlightedHeaders();
if (this.timerId === null) {
this.timerId = setTimeout(function () {
var arrClose = [];
arrClose.push(new asc_CMM({type: c_oAscMouseMoveType.None}));
t.handlers.trigger("asc_onMouseMove", arrClose);
t.timerId = null;
}, 1000);
}
} else {
ct = ws.getCursorTypeFromXY(x, y);
ct.coordX = x;
ct.coordY = y;
if (this.timerId !== null) {
clearTimeout(this.timerId);
this.timerId = null;
}
// Отправление эвента об удалении всего листа (именно удалении, т.к. если просто залочен, то не рисуем рамку вокруг)
if (undefined !== ct.userIdAllSheet) {
arrMouseMoveObjects.push(new asc_CMM({
type: c_oAscMouseMoveType.LockedObject,
x: AscCommon.AscBrowser.convertToRetinaValue(ct.lockAllPosLeft),
y: AscCommon.AscBrowser.convertToRetinaValue(ct.lockAllPosTop),
userId: ct.userIdAllSheet,
lockedObjectType: Asc.c_oAscMouseMoveLockedObjectType.Sheet
}));
} else {
// Отправление эвента о залоченности свойств всего листа (только если не удален весь лист)
if (undefined !== ct.userIdAllProps) {
arrMouseMoveObjects.push(new asc_CMM({
type: c_oAscMouseMoveType.LockedObject,
x: AscCommon.AscBrowser.convertToRetinaValue(ct.lockAllPosLeft),
y: AscCommon.AscBrowser.convertToRetinaValue(ct.lockAllPosTop),
userId: ct.userIdAllProps,
lockedObjectType: Asc.c_oAscMouseMoveLockedObjectType.TableProperties
}));
}
}
// Отправление эвента о наведении на залоченный объект
if (undefined !== ct.userId) {
arrMouseMoveObjects.push(new asc_CMM({
type: c_oAscMouseMoveType.LockedObject,
x: AscCommon.AscBrowser.convertToRetinaValue(ct.lockRangePosLeft),
y: AscCommon.AscBrowser.convertToRetinaValue(ct.lockRangePosTop),
userId: ct.userId,
lockedObjectType: Asc.c_oAscMouseMoveLockedObjectType.Range
}));
}
// Проверяем комментарии ячейки
if (ct.commentIndexes) {
arrMouseMoveObjects.push(new asc_CMM({
type: c_oAscMouseMoveType.Comment,
x: ct.commentCoords.dLeftPX,
reverseX: ct.commentCoords.dReverseLeftPX,
y: ct.commentCoords.dTopPX,
aCommentIndexes: ct.commentIndexes
}));
}
// Проверяем гиперссылку
if (ct.target === c_oTargetType.Hyperlink) {
if (!ctrlKey) {
arrMouseMoveObjects.push(new asc_CMM({
type: c_oAscMouseMoveType.Hyperlink,
x: AscCommon.AscBrowser.convertToRetinaValue(x),
y: AscCommon.AscBrowser.convertToRetinaValue(y),
hyperlink: ct.hyperlink
}));
} else {
ct.cursor = AscCommonExcel.kCurCells;
}
}
// проверяем фильтр
if (ct.target === c_oTargetType.FilterObject) {
if (ct.isPivot) {
//необходимо сгенерировать объект AutoFiltersOptions
} else {
var filterObj = ws.af_setDialogProp(ct.idFilter, true);
if(filterObj) {
arrMouseMoveObjects.push(new asc_CMM({
type: c_oAscMouseMoveType.Filter,
x: AscCommon.AscBrowser.convertToRetinaValue(x),
y: AscCommon.AscBrowser.convertToRetinaValue(y),
filter: filterObj
}));
}
}
}
/* Проверяем, может мы на никаком объекте (такая схема оказалась приемлимой
* для отдела разработки приложений)
*/
if (0 === arrMouseMoveObjects.length) {
// Отправляем эвент, что мы ни на какой области
arrMouseMoveObjects.push(new asc_CMM({type: c_oAscMouseMoveType.None}));
}
// Отсылаем эвент с объектами
this.handlers.trigger("asc_onMouseMove", arrMouseMoveObjects);
if (ct.target === c_oTargetType.MoveRange && ctrlKey && ct.cursor === "move") {
ct.cursor = "copy";
}
this._onUpdateCursor(ct.cursor);
if (ct.target === c_oTargetType.ColumnHeader || ct.target === c_oTargetType.RowHeader) {
ws.drawHighlightedHeaders(ct.col, ct.row);
} else {
ws.cleanHighlightedHeaders();
}
}
asc_applyFunction(callback, ct);
};
WorkbookView.prototype._onUpdateCursor = function (cursor) {
var newHtmlCursor = AscCommon.g_oHtmlCursor.value(cursor);
if (this.element.style.cursor !== newHtmlCursor) {
this.element.style.cursor = newHtmlCursor;
}
};
WorkbookView.prototype._onResizeElement = function(target, x, y) {
var arrMouseMoveObjects = [];
if (target.target === c_oTargetType.ColumnResize) {
arrMouseMoveObjects.push(this.getWorksheet().drawColumnGuides(target.col, x, y, target.mouseX));
} else if (target.target === c_oTargetType.RowResize) {
arrMouseMoveObjects.push(this.getWorksheet().drawRowGuides(target.row, x, y, target.mouseY));
}
/* Проверяем, может мы на никаком объекте (такая схема оказалась приемлимой
* для отдела разработки приложений)
*/
if (0 === arrMouseMoveObjects.length) {
// Отправляем эвент, что мы ни на какой области
arrMouseMoveObjects.push(new asc_CMM({type: c_oAscMouseMoveType.None}));
}
// Отсылаем эвент с объектами
this.handlers.trigger("asc_onMouseMove", arrMouseMoveObjects);
};
WorkbookView.prototype._onResizeElementDone = function(target, x, y, isResizeModeMove) {
var ws = this.getWorksheet();
if (isResizeModeMove) {
if (target.target === c_oTargetType.ColumnResize) {
ws.changeColumnWidth(target.col, x, target.mouseX);
} else if (target.target === c_oTargetType.RowResize) {
ws.changeRowHeight(target.row, y, target.mouseY);
}
window['AscCommon'].g_specialPasteHelper.SpecialPasteButton_Update_Position();
this._onDocumentPlaceChanged();
}
ws.draw();
// Отсылаем окончание смены размеров (в FF не срабатывало обычное движение)
this.handlers.trigger("asc_onMouseMove", [new asc_CMM({type: c_oAscMouseMoveType.None})]);
};
// Обработка автозаполнения
WorkbookView.prototype._onChangeFillHandle = function(x, y, callback, tableIndex) {
var ws = this.getWorksheet();
var d = ws.changeSelectionFillHandle(x, y, tableIndex);
asc_applyFunction(callback, d);
};
// Обработка окончания автозаполнения
WorkbookView.prototype._onChangeFillHandleDone = function(x, y, ctrlPress) {
var ws = this.getWorksheet();
ws.applyFillHandle(x, y, ctrlPress);
};
// Обработка перемещения диапазона
WorkbookView.prototype._onMoveRangeHandle = function(x, y, callback) {
var ws = this.getWorksheet();
var d = ws.changeSelectionMoveRangeHandle(x, y);
asc_applyFunction(callback, d);
};
// Обработка окончания перемещения диапазона
WorkbookView.prototype._onMoveRangeHandleDone = function(ctrlKey) {
var ws = this.getWorksheet();
ws.applyMoveRangeHandle(ctrlKey);
};
WorkbookView.prototype._onMoveResizeRangeHandle = function(x, y, target, callback) {
var ws = this.getWorksheet();
var d = ws.changeSelectionMoveResizeRangeHandle(x, y, target, this.cellEditor);
asc_applyFunction(callback, d);
};
WorkbookView.prototype._onMoveResizeRangeHandleDone = function(target) {
var ws = this.getWorksheet();
ws.applyMoveResizeRangeHandle(target);
};
// Frozen anchor
WorkbookView.prototype._onMoveFrozenAnchorHandle = function(x, y, target) {
var ws = this.getWorksheet();
ws.drawFrozenGuides(x, y, target);
};
WorkbookView.prototype._onMoveFrozenAnchorHandleDone = function(x, y, target) {
// Закрепляем область
var ws = this.getWorksheet();
ws.applyFrozenAnchor(x, y, target);
};
WorkbookView.prototype.showAutoComplete = function() {
var ws = this.getWorksheet();
var arrValues = ws.getCellAutoCompleteValues(ws.model.selectionRange.activeCell);
this.handlers.trigger('asc_onEntriesListMenu', arrValues);
};
WorkbookView.prototype._onAutoFiltersClick = function(idFilter) {
this.getWorksheet().af_setDialogProp(idFilter);
};
WorkbookView.prototype._onGroupRowClick = function(x, y, target, type) {
return this.getWorksheet().groupRowClick(x, y, target, type);
};
WorkbookView.prototype._onCommentCellClick = function(x, y) {
this.getWorksheet().cellCommentator.showCommentByXY(x, y);
};
WorkbookView.prototype._onUpdateSelectionName = function (forcibly) {
if (this.canUpdateAfterShiftUp || forcibly) {
this.canUpdateAfterShiftUp = false;
var ws = this.getWorksheet();
this._onSelectionNameChanged(ws.getSelectionName(/*bRangeText*/false));
}
};
WorkbookView.prototype._onStopFormatPainter = function() {
if (this.stateFormatPainter) {
this.formatPainter(c_oAscFormatPainterState.kOff);
}
};
// Shapes
WorkbookView.prototype._onGraphicObjectMouseDown = function(e, x, y) {
var ws = this.getWorksheet();
ws.objectRender.graphicObjectMouseDown(e, x, y);
};
WorkbookView.prototype._onGraphicObjectMouseMove = function(e, x, y) {
var ws = this.getWorksheet();
ws.objectRender.graphicObjectMouseMove(e, x, y);
};
WorkbookView.prototype._onGraphicObjectMouseUp = function(e, x, y) {
var ws = this.getWorksheet();
ws.objectRender.graphicObjectMouseUp(e, x, y);
};
WorkbookView.prototype._onGraphicObjectMouseUpEx = function(e, x, y) {
//var ws = this.getWorksheet();
//ws.objectRender.calculateCell(x, y);
};
WorkbookView.prototype._onGraphicObjectWindowKeyDown = function(e) {
var objectRender = this.getWorksheet().objectRender;
return (0 < objectRender.getSelectedGraphicObjects().length) ? objectRender.graphicObjectKeyDown(e) : false;
};
WorkbookView.prototype._onGraphicObjectWindowKeyPress = function(e) {
var objectRender = this.getWorksheet().objectRender;
return (0 < objectRender.getSelectedGraphicObjects().length) ? objectRender.graphicObjectKeyPress(e) : false;
};
WorkbookView.prototype._onGetGraphicsInfo = function(x, y) {
var ws = this.getWorksheet();
return ws.objectRender.checkCursorDrawingObject(x, y);
};
WorkbookView.prototype._onUpdateSelectionShape = function(isSelectOnShape) {
var ws = this.getWorksheet();
return ws.setSelectionShape(isSelectOnShape);
};
// Double click
WorkbookView.prototype._onMouseDblClick = function(x, y, isHideCursor, callback) {
var ws = this.getWorksheet();
var ct = ws.getCursorTypeFromXY(x, y);
if (ct.target === c_oTargetType.ColumnResize || ct.target === c_oTargetType.RowResize) {
if (ct.target === c_oTargetType.ColumnResize) {
ws.autoFitColumnsWidth(ct.col);
} else {
ws.autoFitRowHeight(ct.row, ct.row);
}
asc_applyFunction(callback);
} else {
if (ct.col >= 0 && ct.row >= 0) {
this.controller.setStrictClose(!ws._isCellNullText(ct.col, ct.row));
}
// In view mode or click on column | row | all | frozenMove | drawing object do not process
if (!this.canEdit() || c_oTargetType.ColumnHeader === ct.target || c_oTargetType.RowHeader === ct.target ||
c_oTargetType.Corner === ct.target || c_oTargetType.FrozenAnchorH === ct.target ||
c_oTargetType.FrozenAnchorV === ct.target || ws.objectRender.checkCursorDrawingObject(x, y)) {
asc_applyFunction(callback);
return;
}
// При dbl клике фокус выставляем в зависимости от наличия текста в ячейке
this._onEditCell(/*isFocus*/undefined, /*isClearCell*/undefined, /*isHideCursor*/isHideCursor, /*isQuickInput*/false);
}
};
WorkbookView.prototype._onWindowMouseUpExternal = function (event, x, y) {
this.controller._onWindowMouseUpExternal(event, x, y);
if (this.isCellEditMode) {
this.cellEditor._onWindowMouseUp(event, x, y);
}
};
WorkbookView.prototype._onEditCell = function(isFocus, isClearCell, isHideCursor, isQuickInput, callback) {
var t = this;
// Проверка глобального лока
if (this.collaborativeEditing.getGlobalLock() || this.controller.isResizeMode) {
return;
}
var ws = t.getWorksheet();
var activeCellRange = ws.getActiveCell(0, 0, false);
var selectionRange = ws.model.selectionRange.clone();
var activeWsModel = this.model.getActiveWs();
if (activeWsModel.inPivotTable(activeCellRange)) {
this.handlers.trigger("asc_onError", c_oAscError.ID.LockedCellPivot, c_oAscError.Level.NoCritical);
return;
}
var editFunction = function() {
t.setCellEditMode(true);
t.hideSpecialPasteButton();
ws.openCellEditor(t.cellEditor, /*cursorPos*/undefined, isFocus, isClearCell,
/*isHideCursor*/isHideCursor, /*isQuickInput*/isQuickInput, selectionRange);
t.input.disabled = false;
t.Api.cleanSpelling(true);
// Эвент на обновление состояния редактора
t.cellEditor._updateEditorState();
asc_applyFunction(callback, true);
};
var editLockCallback = function(res) {
if (!res) {
t.setCellEditMode(false);
t.controller.setStrictClose(false);
t.controller.setFormulaEditMode(false);
ws.setFormulaEditMode(false);
t.input.disabled = true;
// Выключаем lock для редактирования ячейки
t.collaborativeEditing.onStopEditCell();
t.cellEditor.close(false);
t._onWSSelectionChanged();
}
};
// Стартуем редактировать ячейку
activeCellRange = ws.expandActiveCellByFormulaArray(activeCellRange);
if (ws._isLockedCells(activeCellRange, /*subType*/null, editLockCallback)) {
editFunction();
}
};
WorkbookView.prototype._onStopCellEditing = function(cancel) {
return this.cellEditor.close(!cancel);
};
WorkbookView.prototype._onCloseCellEditor = function() {
var isCellEditMode = this.getCellEditMode();
this.setCellEditMode(false);
this.controller.setStrictClose(false);
this.controller.setFormulaEditMode(false);
if (-1 !== this.copyActiveSheet) {
var index = this.copyActiveSheet;
this.cellFormulaEnterWSOpen = null;
this.copyActiveSheet = -1;
if (index !== this.wsActive) {
this.showWorksheet(index);
}
}
var ws = this.getWorksheet();
ws.cleanSelection();
for (var i in this.wsViews) {
this.wsViews[i].setFormulaEditMode(false);
this.wsViews[i].cleanFormulaRanges();
}
ws.updateSelectionWithSparklines();
if (isCellEditMode) {
this.handlers.trigger("asc_onEditCell", Asc.c_oAscCellEditorState.editEnd);
}
// Обновляем состояние Undo/Redo
if (!this.cellEditor.getMenuEditorMode()) {
History._sendCanUndoRedo();
}
// Обновляем состояние информации
this._onWSSelectionChanged();
// Закрываем подбор формулы
if (-1 !== this.lastFPos) {
this.handlers.trigger('asc_onFormulaCompleteMenu', null);
this.lastFPos = -1;
this.lastFNameLength = 0;
}
this.handlers.trigger('asc_onFormulaInfo', null);
};
WorkbookView.prototype._onEmpty = function() {
this.getWorksheet().emptySelection(c_oAscCleanOptions.Text);
};
WorkbookView.prototype._onShowNextPrevWorksheet = function(direction) {
// Колличество листов
var countWorksheets = this.model.getWorksheetCount();
// Покажем следующий лист или предыдущий (если больше нет)
var i = this.wsActive + direction, ws;
while (i !== this.wsActive) {
if (0 > i) {
i = countWorksheets - 1;
} else if (i >= countWorksheets) {
i = 0;
}
ws = this.model.getWorksheet(i);
if (!ws.getHidden()) {
this.showWorksheet(i);
return true;
}
i += direction;
}
return false;
};
WorkbookView.prototype._onSetFontAttributes = function(prop) {
var val;
var selectionInfo = this.getWorksheet().getSelectionInfo().asc_getFont();
switch (prop) {
case "b":
val = !(selectionInfo.asc_getBold());
break;
case "i":
val = !(selectionInfo.asc_getItalic());
break;
case "u":
// ToDo для двойного подчеркивания нужно будет немного переделать схему
val = !(selectionInfo.asc_getUnderline());
val = val ? Asc.EUnderline.underlineSingle : Asc.EUnderline.underlineNone;
break;
case "s":
val = !(selectionInfo.asc_getStrikeout());
break;
}
return this.setFontAttributes(prop, val);
};
WorkbookView.prototype._onSetCellFormat = function (prop) {
var info = new Asc.asc_CFormatCellsInfo();
info.asc_setSymbol(AscCommon.g_oDefaultCultureInfo.LCID);
info.asc_setType(Asc.c_oAscNumFormatType.None);
var formats = AscCommon.getFormatCells(info);
this.setCellFormat(formats[prop]);
};
WorkbookView.prototype._onSelectColumnsByRange = function() {
this.getWorksheet()._selectColumnsByRange();
};
WorkbookView.prototype._onSelectRowsByRange = function() {
this.getWorksheet()._selectRowsByRange();
};
WorkbookView.prototype._onShowCellEditorCursor = function() {
// Показываем курсор
if (this.getCellEditMode()) {
this.cellEditor.showCursor();
}
};
WorkbookView.prototype._onDocumentPlaceChanged = function() {
if (this.isDocumentPlaceChangedEnabled) {
this.handlers.trigger("asc_onDocumentPlaceChanged");
}
};
WorkbookView.prototype.getCellStyles = function(width, height) {
return AscCommonExcel.generateStyles(width, height, this.model.CellStyles, this);
};
WorkbookView.prototype.getWorksheetById = function(id, onlyExist) {
var wsModel = this.model.getWorksheetById(id);
if (wsModel) {
return this.getWorksheet(wsModel.getIndex(), onlyExist);
}
return null;
};
/**
* @param {Number} [index]
* @param {Boolean} [onlyExist]
* @return {AscCommonExcel.WorksheetView}
*/
WorkbookView.prototype.getWorksheet = function(index, onlyExist) {
var wb = this.model;
var i = asc_typeof(index) === "number" && index >= 0 ? index : wb.getActive();
var ws = this.wsViews[i];
if (!ws && !onlyExist) {
ws = this.wsViews[i] = this._createWorksheetView(wb.getWorksheet(i));
ws._prepareComments();
ws._prepareDrawingObjects();
}
return ws;
};
WorkbookView.prototype.drawWorksheet = function () {
if (-1 === this.wsActive) {
return this.showWorksheet();
}
var ws = this.getWorksheet();
ws.draw();
ws.objectRender.controller.updateSelectionState();
ws.objectRender.controller.updateOverlay();
this._onScrollReinitialize(AscCommonExcel.c_oAscScrollType.ScrollVertical | AscCommonExcel.c_oAscScrollType.ScrollHorizontal);
};
/**
*
* @param index
* @param [bLockDraw]
* @returns {WorkbookView}
*/
WorkbookView.prototype.showWorksheet = function (index, bLockDraw) {
if (window["NATIVE_EDITOR_ENJINE"] && !window['IS_NATIVE_EDITOR'] && !window['DoctRendererMode']) {
return this;
}
// ToDo disable method for assembly
var ws, wb = this.model;
if (asc_typeof(index) !== "number" || 0 > index) {
index = wb.getActive();
}
if (index === this.wsActive) {
if (!bLockDraw) {
this.drawWorksheet();
}
return this;
}
var tmpWorksheet, selectionRange = null;
// Только если есть активный
if (-1 !== this.wsActive) {
ws = this.getWorksheet();
// Останавливаем ввод данных в редакторе ввода. Если в режиме ввода формул, то продолжаем работать с cellEditor'ом, чтобы можно было
// выбирать ячейки для формулы
if (this.getCellEditMode()) {
if (this.cellEditor && this.cellEditor.formulaIsOperator()) {
this.lastActiveSheet = this.wsActive;
if (!this.cellFormulaEnterWSOpen) {
this.copyActiveSheet = this.wsActive;
this.cellFormulaEnterWSOpen = ws;
} else {
ws.setFormulaEditMode(false);
}
} else {
this._onStopCellEditing();
}
}
// Делаем очистку селекта
ws.cleanSelection();
this.stopTarget(ws);
}
if (this.selectionDialogMode) {
// Когда идет выбор диапазона, то должны на закрываемом листе отменить выбор диапазона
tmpWorksheet = this.getWorksheet();
selectionRange = tmpWorksheet.model.selectionRange.getLast().clone(true);
tmpWorksheet.copySelection(false);
}
if (this.stateFormatPainter) {
// Должны отменить выбор на закрываемом листе
this.getWorksheet().formatPainter(c_oAscFormatPainterState.kOff);
}
if (index !== wb.getActive()) {
wb.setActive(index);
}
this.wsActive = index;
this.wsMustDraw = bLockDraw;
// Посылаем эвент о смене активного листа
this.handlers.trigger("asc_onActiveSheetChanged", this.wsActive);
this.handlers.trigger("asc_onHideComment");
ws = this.getWorksheet(index);
if (this.selectionDialogMode) {
// Когда идет выбор диапазона, то на показываемом листе должны выставить нужный режим
ws.copySelection(true, selectionRange);
this.handlers.trigger("asc_onSelectionRangeChanged", ws.getSelectionRangeValue());
}
// Мы делали resize или меняли zoom, но не перерисовывали данный лист (он был не активный)
if (ws.updateResize && ws.updateZoom) {
ws.changeZoomResize();
} else if (ws.updateResize) {
ws.resize(true, this.cellEditor);
} else if (ws.updateZoom) {
ws.changeZoom(true);
}
this.updateGroupData();
if (this.cellEditor && this.cellFormulaEnterWSOpen) {
if (ws === this.cellFormulaEnterWSOpen) {
this.cellFormulaEnterWSOpen.setFormulaEditMode(true);
this.cellEditor._showCanvas();
} else if (this.getCellEditMode() && this.cellEditor.isFormula()) {
this.cellFormulaEnterWSOpen.setFormulaEditMode(false);
/*скрываем cellEditor, в редактор добавляем %selected sheet name%+"!" */
this.cellEditor._hideCanvas();
ws.cleanSelection();
ws.setFormulaEditMode(true);
}
}
if (!bLockDraw) {
ws.draw();
}
if (this.stateFormatPainter) {
// Должны отменить выбор на закрываемом листе
this.getWorksheet().formatPainter(this.stateFormatPainter);
}
if (!bLockDraw) {
ws.objectRender.controller.updateSelectionState();
ws.objectRender.controller.updateOverlay();
}
if (!window["NATIVE_EDITOR_ENJINE"]) {
this._onSelectionNameChanged(ws.getSelectionName(/*bRangeText*/false));
this._onWSSelectionChanged();
this._onSelectionMathInfoChanged(ws.getSelectionMathInfo());
}
this._onScrollReinitialize(AscCommonExcel.c_oAscScrollType.ScrollVertical | AscCommonExcel.c_oAscScrollType.ScrollHorizontal);
// Zoom теперь на каждом листе одинаковый, не отправляем смену
//TODO при добавлении любого действия в историю (например добавление нового листа), мы можем его потом отменить с повощью опции авторазвертывания
this.toggleAutoCorrectOptions(null, true);
window['AscCommon'].g_specialPasteHelper.SpecialPasteButton_Hide();
return this;
};
WorkbookView.prototype.stopTarget = function(ws) {
if (null === ws && -1 !== this.wsActive) {
ws = this.getWorksheet(this.wsActive);
}
if (null !== ws && ws.objectRender && ws.objectRender.drawingDocument) {
ws.objectRender.drawingDocument.TargetEnd();
}
};
WorkbookView.prototype.updateWorksheetByModel = function() {
// ToDo Сделал небольшую заглушку с показом листа. Нужно как мне кажется перейти от wsViews на wsViewsId (хранить по id)
var oldActiveWs;
if (-1 !== this.wsActive) {
oldActiveWs = this.wsViews[this.wsActive];
}
//расставляем ws так как они идут в модели.
var oNewWsViews = [];
for (var i in this.wsViews) {
var item = this.wsViews[i];
if (null != item && null != this.model.getWorksheetById(item.model.getId())) {
oNewWsViews[item.model.getIndex()] = item;
}
}
this.wsViews = oNewWsViews;
var wsActive = this.model.getActive();
var newActiveWs = this.wsViews[wsActive];
if (undefined === newActiveWs || oldActiveWs !== newActiveWs) {
// Если сменили, то покажем
this.wsActive = -1;
this.showWorksheet(wsActive, true);
} else {
this.wsActive = wsActive;
}
};
WorkbookView.prototype._canResize = function() {
var isRetina = AscBrowser.isRetina;
var oldWidth = this.canvas.width;
var oldHeight = this.canvas.height;
var width, height, styleWidth, styleHeight;
width = styleWidth = this.element.offsetWidth - (this.Api.isMobileVersion ? 0 : this.defaults.scroll.widthPx);
height = styleHeight = this.element.offsetHeight - (this.Api.isMobileVersion ? 0 : this.defaults.scroll.heightPx);
if (isRetina) {
width = AscCommon.AscBrowser.convertToRetinaValue(width, true);
height = AscCommon.AscBrowser.convertToRetinaValue(height, true);
}
if (oldWidth === width && oldHeight === height && this.isInit) {
return false;
}
this.isInit = true;
this.canvas.width = this.canvasOverlay.width = this.canvasGraphic.width = this.canvasGraphicOverlay.width = width;
this.canvas.height = this.canvasOverlay.height = this.canvasGraphic.height = this.canvasGraphicOverlay.height = height;
this.canvas.style.width = this.canvasOverlay.style.width = this.canvasGraphic.style.width = this.canvasGraphicOverlay.style.width = styleWidth + 'px';
this.canvas.style.height = this.canvasOverlay.style.height = this.canvasGraphic.style.height = this.canvasGraphicOverlay.style.height = styleHeight + 'px';
this._reInitGraphics();
return true;
};
WorkbookView.prototype._reInitGraphics = function () {
var canvasWidth = this.canvasGraphic.width;
var canvasHeight = this.canvasGraphic.height;
this.shapeCtx.init(this.drawingGraphicCtx.ctx, canvasWidth, canvasHeight, canvasWidth * 25.4 / this.drawingGraphicCtx.ppiX, canvasHeight * 25.4 / this.drawingGraphicCtx.ppiY);
this.shapeCtx.CalculateFullTransform();
var overlayWidth = this.canvasGraphicOverlay.width;
var overlayHeight = this.canvasGraphicOverlay.height;
this.shapeOverlayCtx.init(this.overlayGraphicCtx.ctx, overlayWidth, overlayHeight, overlayWidth * 25.4 / this.overlayGraphicCtx.ppiX, overlayHeight * 25.4 / this.overlayGraphicCtx.ppiY);
this.shapeOverlayCtx.CalculateFullTransform();
this.mainGraphics.init(this.drawingCtx.ctx, canvasWidth, canvasHeight, canvasWidth * 25.4 / this.drawingCtx.ppiX, canvasHeight * 25.4 / this.drawingCtx.ppiY);
this.trackOverlay.init(this.shapeOverlayCtx.m_oContext, "ws-canvas-graphic-overlay", 0, 0, overlayWidth, overlayHeight, (overlayWidth * 25.4 / this.overlayGraphicCtx.ppiX), (overlayHeight * 25.4 / this.overlayGraphicCtx.ppiY));
this.autoShapeTrack.init(this.trackOverlay, 0, 0, overlayWidth, overlayHeight, overlayWidth * 25.4 / this.overlayGraphicCtx.ppiX, overlayHeight * 25.4 / this.overlayGraphicCtx.ppiY);
this.autoShapeTrack.Graphics.CalculateFullTransform();
};
/** @param event {jQuery.Event} */
WorkbookView.prototype.resize = function(event) {
if (this._canResize()) {
var item;
var activeIndex = this.model.getActive();
for (var i in this.wsViews) {
item = this.wsViews[i];
// Делаем resize (для не активных сменим как только сделаем его активным)
item.resize(/*isDraw*/i == activeIndex, this.cellEditor);
}
this.drawWorksheet();
} else {
// ToDo не должно происходить ничего, но нам приходит resize сверху, поэтому проверим отрисовывали ли мы
if (-1 === this.wsActive || this.wsMustDraw) {
this.drawWorksheet();
}
}
this.wsMustDraw = false;
};
WorkbookView.prototype.getSelectionInfo = function () {
if (!this.oSelectionInfo) {
this._updateSelectionInfo();
}
return this.oSelectionInfo;
};
// Получаем свойство: редактируем мы сейчас или нет
WorkbookView.prototype.getCellEditMode = function() {
return this.isCellEditMode;
};
WorkbookView.prototype.canEdit = function() {
return this.Api.canEdit();
};
WorkbookView.prototype.getDialogSheetName = function () {
return this.dialogSheetName || !this.isActive();
};
WorkbookView.prototype.setCellEditMode = function(flag) {
this.isCellEditMode = !!flag;
};
WorkbookView.prototype.isActive = function () {
return (-1 === this.copyActiveSheet || this.wsActive === this.copyActiveSheet);
};
WorkbookView.prototype.getIsTrackShape = function() {
var ws = this.getWorksheet();
if (!ws) {
return false;
}
if (ws.objectRender && ws.objectRender.controller) {
return ws.objectRender.controller.checkTrackDrawings();
}
};
WorkbookView.prototype.getZoom = function() {
return this.drawingCtx.getZoom();
};
WorkbookView.prototype.changeZoom = function(factor) {
if (factor === this.getZoom()) {
return;
}
this.buffers.main.changeZoom(factor);
this.buffers.overlay.changeZoom(factor);
this.buffers.mainGraphic.changeZoom(factor);
this.buffers.overlayGraphic.changeZoom(factor);
if (!factor) {
this.cellEditor.changeZoom(factor);
}
// Нужно сбросить кэш букв
var i, length;
for (i = 0, length = this.fmgrGraphics.length; i < length; ++i)
this.fmgrGraphics[i].ClearFontsRasterCache();
if (AscCommon.g_fontManager) {
AscCommon.g_fontManager.ClearFontsRasterCache();
AscCommon.g_fontManager.m_pFont = null;
}
if (AscCommon.g_fontManager2) {
AscCommon.g_fontManager2.ClearFontsRasterCache();
AscCommon.g_fontManager2.m_pFont = null;
}
if (!factor) {
this.wsMustDraw = true;
this._calcMaxDigitWidth();
}
var item;
var activeIndex = this.model.getActive();
for (i in this.wsViews) {
item = this.wsViews[i];
// Меняем zoom (для не активных сменим как только сделаем его активным)
if (!factor) {
item._initWorksheetDefaultWidth();
}
item.changeZoom(/*isDraw*/i == activeIndex);
this._reInitGraphics();
item.objectRender.changeZoom(this.drawingCtx.scaleFactor);
if (i == activeIndex && factor) {
item.draw();
//ToDo item.drawDepCells();
}
}
this._onScrollReinitialize(AscCommonExcel.c_oAscScrollType.ScrollVertical | AscCommonExcel.c_oAscScrollType.ScrollHorizontal);
this.handlers.trigger("asc_onZoomChanged", this.getZoom());
};
WorkbookView.prototype.getEnableKeyEventsHandler = function(bIsNaturalFocus) {
var res = this.enableKeyEvents;
if (res && bIsNaturalFocus && this.getCellEditMode() && this.input.isFocused) {
res = false;
}
return res;
};
WorkbookView.prototype.enableKeyEventsHandler = function(f) {
this.enableKeyEvents = !!f;
this.controller.enableKeyEventsHandler(this.enableKeyEvents);
if (this.cellEditor) {
this.cellEditor.enableKeyEventsHandler(this.enableKeyEvents);
}
};
// Останавливаем ввод данных в редакторе ввода
WorkbookView.prototype.closeCellEditor = function (cancel) {
return this.getCellEditMode() ? this._onStopCellEditing(cancel) : true;
};
WorkbookView.prototype.restoreFocus = function() {
if (window["NATIVE_EDITOR_ENJINE"]) {
return;
}
if (this.cellEditor.hasFocus) {
this.cellEditor.restoreFocus();
}
};
WorkbookView.prototype._onUpdateCellEditor = function(text, cursorPosition, fPos, fName) {
if (this.skipHelpSelector) {
return;
}
// ToDo для ускорения можно завести объект, куда класть результаты поиска по формулам и второй раз не искать.
var i, arrResult = [], defNamesList, defName, defNameStr;
if (fName) {
fName = fName.toUpperCase();
for (i = 0; i < this.formulasList.length; ++i) {
if (0 === this.formulasList[i].indexOf(fName)) {
arrResult.push(new AscCommonExcel.asc_CCompleteMenu(this.formulasList[i], c_oAscPopUpSelectorType.Func));
}
}
defNamesList = this.getDefinedNames(Asc.c_oAscGetDefinedNamesList.WorksheetWorkbook);
fName = fName.toLowerCase();
for (i = 0; i < defNamesList.length; ++i) {
/*defName = defNamesList[i];
if (0 === defName.Name.toLowerCase().indexOf(fName)) {
arrResult.push(new AscCommonExcel.asc_CCompleteMenu(defName.Name, !defName.isTable ? c_oAscPopUpSelectorType.Range : c_oAscPopUpSelectorType.Table));*/
defName = defNamesList[i];
defNameStr = defName.Name.toLowerCase();
if(null !== defName.LocalSheetId && defNameStr === "print_area") {
defNameStr = AscCommon.translateManager.getValue("Print_Area");
}
if (0 === defNameStr.toLowerCase().indexOf(fName)) {
arrResult.push(new AscCommonExcel.asc_CCompleteMenu(defNameStr, !defName.isTable ? c_oAscPopUpSelectorType.Range : c_oAscPopUpSelectorType.Table));
}
}
}
if (0 < arrResult.length) {
this.handlers.trigger('asc_onFormulaCompleteMenu', arrResult);
this.lastFPos = fPos;
this.lastFNameLength = fName.length;
} else {
this.handlers.trigger('asc_onFormulaCompleteMenu', null);
this.lastFPos = -1;
this.lastFNameLength = 0;
}
};
// Вставка формулы в редактор
WorkbookView.prototype.insertInCellEditor = function (name, type, autoComplete) {
var t = this, ws = this.getWorksheet(), cursorPos, isNotFunction, tmp;
var activeCellRange = ws.getActiveCell(0, 0, false);
if (ws.model.inPivotTable(activeCellRange)) {
this.handlers.trigger("asc_onError", c_oAscError.ID.LockedCellPivot, c_oAscError.Level.NoCritical);
return;
}
if (c_oAscPopUpSelectorType.None === type) {
ws.setSelectionInfo("value", name, /*onlyActive*/true);
return;
}
isNotFunction = c_oAscPopUpSelectorType.Func !== type && c_oAscPopUpSelectorType.FuncWizard !== type;
// Проверяем, открыт ли редактор
var isFormulaContains, funcInfo;
if (this.getCellEditMode()) {
if (isNotFunction) {
this.skipHelpSelector = true;
}
isFormulaContains = this.cellEditor.isFormula() && c_oAscPopUpSelectorType.FuncWizard === type;
if (-1 !== this.lastFPos) {
if (-1 === this.arrExcludeFormulas.indexOf(name) && !isNotFunction) {
//если следующий символ скобка - не добавляем ещё одну
if('(' !== this.cellEditor.textRender.getChars(this.cellEditor.cursorPos, 1)) {
name += '('; // ToDo сделать проверки при добавлении, чтобы не вызывать постоянно окно
}
} else {
this.skipHelpSelector = true;
}
tmp = this.cellEditor.skipTLUpdate;
this.cellEditor.skipTLUpdate = false;
this.cellEditor.replaceText(this.lastFPos, this.lastFNameLength, name);
this.cellEditor.skipTLUpdate = tmp;
} else if (false === this.cellEditor.insertFormula(name, isNotFunction)) {
// Не смогли вставить формулу, закроем редактор, с сохранением текста
this.cellEditor.close(true);
isFormulaContains = false;
}
this.skipHelpSelector = false;
if (isFormulaContains) {
funcInfo = ws.model.getActiveFunctionInfo(this.cellEditor._formula, this.cellEditor._parseResult);
t.handlers.trigger("asc_onSendFunctionWizardInfo", funcInfo);
}
} else {
// Проверка глобального лока
if (this.collaborativeEditing.getGlobalLock()) {
return;
}
var selectionRange = ws.model.selectionRange.clone();
//если в ячейке уже есть формула
isFormulaContains = c_oAscPopUpSelectorType.FuncWizard === type ? ws.model.isActiveCellFormula() : null;
if (!isFormulaContains) {
// Редактор закрыт
var cellRange = {};
// Если нужно сделать автозаполнение формулы, то ищем ячейки)
if (autoComplete) {
cellRange = ws.autoCompleteFormula(name);
}
if (isNotFunction) {
name = "=" + name;
} else {
if (cellRange.notEditCell) {
// Мы уже ввели все что нужно, редактор открывать не нужно
return;
}
if (cellRange.text) {
// Меняем значение ячейки
name = "=" + name + "(" + cellRange.text + ")";
} else {
// Меняем значение ячейки
name = "=" + name + "()";
}
// Вычисляем позицию курсора (он должен быть в функции)
cursorPos = name.length - 1;
}
}
//this.cellEditor.lastInsertedFormulaPos = cursorPos;
var openEditor = function (res) {
if (res) {
// Выставляем переменные, что мы редактируем
t.setCellEditMode(true);
if (isNotFunction) {
t.skipHelpSelector = true;
}
t.hideSpecialPasteButton();
if (isFormulaContains) {
t.cellEditor.needFindFirstFunction = true;
ws.openCellEditor(t.cellEditor, t.cellEditor.cursorPos, false, true, false, false, selectionRange);
//TODO вызываю отсюда служебную функцию, пересмотреть!
t.cellEditor._moveCursor(-11, t.cellEditor._parseResult.cursorPos + 1);
t.cellEditor.needFindFirstFunction = null;
} else {
// Открываем, с выставлением позиции курсора
ws.openCellEditorWithText(t.cellEditor, name, cursorPos, /*isFocus*/false, selectionRange);
}
if (c_oAscPopUpSelectorType.FuncWizard === type) {
var funcInfo = ws.model.getActiveFunctionInfo(t.cellEditor._formula, t.cellEditor._parseResult);
t.handlers.trigger("asc_onSendFunctionWizardInfo", funcInfo);
}
if (isNotFunction) {
t.skipHelpSelector = false;
}
} else {
t.setCellEditMode(false);
t.controller.setStrictClose(false);
t.controller.setFormulaEditMode(false);
ws.setFormulaEditMode(false);
}
};
ws._isLockedCells(activeCellRange, /*subType*/null, openEditor);
}
};
WorkbookView.prototype.preInsertFormula = function() {
var t = this, ws = this.getWorksheet();
var activeCellRange = ws.getActiveCell(0, 0, false);
var selectionRange = ws.model.selectionRange.clone();
var functionInfo = null;
if (this.getCellEditMode()) {
//при парсинге формулы она может быть изменена, например может быть добавлена последняя незакрытая скобка
var parseResult = t.cellEditor ? t.cellEditor._parseResult : null;
if (parseResult && parseResult.activeFunction) {
var _f = t.cellEditor._formula.Formula;
if (_f[_f.length - 1] === "(") {
_f += ")";
t.cellEditor._formula.Formula = _f;
}
if (t.cellEditor.textRender.chars !== "=" + _f) {
this.cellEditor.selectionBegin = 1;
this.cellEditor.selectionEnd = t.cellEditor.textRender.getCharsCount();
//TODO проверить нужно ли перемещать курсор?
var _cursorPos = this.cellEditor.cursorPos;
this.cellEditor.pasteText(_f);
this.cellEditor._moveCursor(-11, _cursorPos);
} else {
this.cellEditor._updateFormulaEditMod();
}
functionInfo = ws.model.getActiveFunctionInfo(t.cellEditor._formula, t.cellEditor._parseResult);
}
t.handlers.trigger("asc_onSendFunctionWizardInfo", functionInfo);
} else {
if (this.collaborativeEditing.getGlobalLock()) {
return;
}
var openEditor = function (res) {
functionInfo = null;
if (res) {
// Выставляем переменные, что мы редактируем
t.setCellEditMode(true);
t.hideSpecialPasteButton();
if (ws.model.isActiveCellFormula()) {
//если ячейка с формулой, то либо перемещаемся к первой функции и отркываем диалог wizard
//если функции нет, то перемещаемся в конец формулы и открываем окно выбора функции
t.cellEditor.needFindFirstFunction = true;
ws.openCellEditor(t.cellEditor, t.cellEditor.cursorPos, false, true, false, false, selectionRange);
t.cellEditor.needFindFirstFunction = null;
var parseResult = t.cellEditor._parseResult;
if (parseResult && parseResult.activeFunction) {
//TODO вызываю отсюда служебную функцию, пересмотреть!
t.cellEditor._moveCursor(-11, t.cellEditor._parseResult.cursorPos + 1);
functionInfo = ws.model.getActiveFunctionInfo(t.cellEditor._formula, t.cellEditor._parseResult);
} else {
t.cellEditor._moveCursor(-11, t.cellEditor._parseResult.cursorPos + 1);
}
} else {
ws.openCellEditorWithText(t.cellEditor, "=", 1, /*isFocus*/false, selectionRange);
}
}
t.handlers.trigger("asc_onSendFunctionWizardInfo", functionInfo);
};
ws._isLockedCells(activeCellRange, /*subType*/null, openEditor);
}
};
WorkbookView.prototype.insertArgumentInFormula = function(val, argNum, type) {
if (!this.getCellEditMode()) {
return;
}
var ws = this.getWorksheet();
//argPosArr
var parseResult = this.cellEditor ? this.cellEditor._parseResult : null;
if (!parseResult || !parseResult.argPosArr || !parseResult.activeFunction || argNum > parseResult.activeFunction.argumentsMax) {
return;
}
if (!parseResult.argPosArr[argNum]) {
//меняем строку и добавляем разделителей
for (var i = parseResult.argPosArr.length; i <= argNum; i++) {
val = AscCommon.FormulaSeparators.functionArgumentSeparator + val;
}
//TODO продумать прпобразование аргументов(допустим строковые значения)
} else {
//полностью заменяем аргумент - для этого чистим предыдущую запись
this.cellEditor.selectionBegin = parseResult.argPosArr[argNum].start;
this.cellEditor.selectionEnd = parseResult.argPosArr[argNum].end;
//TODO нужно ли чистить? при вставке текста должны произойти замена.
this.cellEditor.empty(Asc.c_oAscCleanOptions.All);
if (parseResult.argPosArr[argNum].start === parseResult.argPosArr[argNum].end) {
//TODO вызываю отсюда служебную функцию, пересмотреть!
this.cellEditor._moveCursor(-11, parseResult.argPosArr[argNum].start);
}
}
this.cellEditor.pasteText(val);
return ws.model.getActiveFunctionInfo(this.cellEditor._formula, this.cellEditor._parseResult);
};
WorkbookView.prototype.moveCursorFunctionArgument = function (argNum, pos) {
if (!this.getCellEditMode()) {
return;
}
var ws = this.getWorksheet();
//argPosArr
var parseResult = this.cellEditor ? this.cellEditor._parseResult : null;
if (!parseResult || !parseResult.argPosArr || !parseResult.activeFunction || argNum > parseResult.activeFunction.argumentsMax) {
return;
}
if (!parseResult.argPosArr[argNum]) {
//меняем строку и добавляем разделителей
var val = "";
for (var i = parseResult.argPosArr.length; i <= argNum; i++) {
val = AscCommon.FormulaSeparators.functionArgumentSeparator + val;
}
this.cellEditor.pasteText(val);
}
this.cellEditor._moveCursor(-11, parseResult.argPosArr[argNum].start + pos);
};
WorkbookView.prototype.bIsEmptyClipboard = function() {
return g_clipboardExcel.bIsEmptyClipboard(this.getCellEditMode());
};
WorkbookView.prototype.checkCopyToClipboard = function(_clipboard, _formats) {
var t = this, ws;
ws = t.getWorksheet();
g_clipboardExcel.checkCopyToClipboard(ws, _clipboard, _formats);
};
WorkbookView.prototype.pasteData = function(_format, data1, data2, text_data, doNotShowButton) {
var t = this, ws;
ws = t.getWorksheet();
g_clipboardExcel.pasteData(ws, _format, data1, data2, text_data, null, doNotShowButton);
};
WorkbookView.prototype.specialPasteData = function(props) {
if (!this.getCellEditMode()) {
this.getWorksheet().specialPaste(props);
}
};
WorkbookView.prototype.showSpecialPasteButton = function(props) {
if (!this.getCellEditMode()) {
this.getWorksheet().showSpecialPasteOptions(props);
}
};
WorkbookView.prototype.updateSpecialPasteButton = function(props) {
if (!this.getCellEditMode()) {
this.getWorksheet().updateSpecialPasteButton(props);
}
};
WorkbookView.prototype.hideSpecialPasteButton = function() {
//TODO пересмотреть!
//сейчас сначала добавляются данные в историю, потом идет закрытие редактора ячейки
//следовательно убираю проверку на редактирование ячейки
/*if (!this.getCellEditMode()) {*/
this.handlers.trigger("hideSpecialPasteOptions");
//}
};
WorkbookView.prototype.selectionCut = function () {
if (this.getCellEditMode()) {
this.cellEditor.cutSelection();
} else {
if (this.getWorksheet().isNeedSelectionCut()) {
this.getWorksheet().emptySelection(c_oAscCleanOptions.All, true);
} else {
//в данном случае не вырезаем, а записываем
if(false === this.getWorksheet().isMultiSelect()) {
this.cutIdSheet = this.getWorksheet().model.Id;
this.getWorksheet().cutRange = this.getWorksheet().model.selectionRange.getLast();
}
}
}
};
WorkbookView.prototype.undo = function() {
var oFormulaLocaleInfo = AscCommonExcel.oFormulaLocaleInfo;
oFormulaLocaleInfo.Parse = false;
oFormulaLocaleInfo.DigitSep = false;
if (!this.getCellEditMode()) {
if (!History.Undo() && this.collaborativeEditing.getFast() && this.collaborativeEditing.getCollaborativeEditing()) {
this.Api.sync_TryUndoInFastCollaborative();
}
} else {
this.cellEditor.undo();
}
oFormulaLocaleInfo.Parse = true;
oFormulaLocaleInfo.DigitSep = true;
};
WorkbookView.prototype.redo = function() {
if (!this.getCellEditMode()) {
History.Redo();
} else {
this.cellEditor.redo();
}
};
WorkbookView.prototype.setFontAttributes = function(prop, val) {
if (!this.getCellEditMode()) {
this.getWorksheet().setSelectionInfo(prop, val);
} else {
this.cellEditor.setTextStyle(prop, val);
}
};
WorkbookView.prototype.changeFontSize = function(prop, val) {
if (!this.getCellEditMode()) {
this.getWorksheet().setSelectionInfo(prop, val);
} else {
this.cellEditor.setTextStyle(prop, val);
}
};
WorkbookView.prototype.setCellFormat = function (format) {
this.getWorksheet().setSelectionInfo("format", format);
};
WorkbookView.prototype.emptyCells = function (options) {
if (!this.getCellEditMode()) {
if (Asc.c_oAscCleanOptions.Comments === options) {
this.removeAllComments(false, true);
} else {
this.getWorksheet().emptySelection(options);
}
this.restoreFocus();
} else {
this.cellEditor.empty(options);
}
};
WorkbookView.prototype._setSelectionDialogType = function (selectionDialogType) {
this.dialogSheetName = (c_oAscSelectionDialogType.Chart === selectionDialogType ||
c_oAscSelectionDialogType.PivotTableData === selectionDialogType ||
c_oAscSelectionDialogType.PivotTableReport === selectionDialogType);
this.dialogAbsName = (c_oAscSelectionDialogType.None !== selectionDialogType &&
c_oAscSelectionDialogType.FunctionWizard !== selectionDialogType);
};
WorkbookView.prototype.setSelectionDialogMode = function (selectionDialogType, selectRange) {
var newSelectionDialogMode = c_oAscSelectionDialogType.None !== selectionDialogType;
if (newSelectionDialogMode === this.selectionDialogMode) {
return;
}
this._setSelectionDialogType(selectionDialogType);
var drawSelection = false;
if (newSelectionDialogMode) {
this.copyActiveSheet = this.wsActive;
var tmpSelectRange = AscCommon.parserHelp.parse3DRef(selectRange);
if (tmpSelectRange) {
var ws = this.model.getWorksheetByName(tmpSelectRange.sheet);
if (!ws || ws.getHidden()) {
tmpSelectRange = null;
} else {
var index = ws.getIndex();
if (index !== this.wsActive) {
this.showWorksheet(index);
}
tmpSelectRange = tmpSelectRange.range;
}
} else {
tmpSelectRange = selectRange;
}
this.getWorksheet().copySelection(true, tmpSelectRange && AscCommonExcel.g_oRangeCache.getAscRange(tmpSelectRange));
this.selectionDialogMode = newSelectionDialogMode;
this.input.disabled = true;
drawSelection = true;
} else {
this.selectionDialogMode = newSelectionDialogMode;
this.getWorksheet().copySelection(false);
if (this.copyActiveSheet !== this.wsActive) {
this.showWorksheet(this.copyActiveSheet);
} else {
drawSelection = true;
}
this.copyActiveSheet = -1;
this.input.disabled = false;
}
if (drawSelection) {
this.getWorksheet()._drawSelection();
}
};
WorkbookView.prototype.formatPainter = function(stateFormatPainter) {
// Если передали состояние, то выставляем его. Если нет - то меняем на противоположное.
this.stateFormatPainter = (null != stateFormatPainter) ? stateFormatPainter : ((c_oAscFormatPainterState.kOff !== this.stateFormatPainter) ? c_oAscFormatPainterState.kOff : c_oAscFormatPainterState.kOn);
this.rangeFormatPainter = this.getWorksheet().formatPainter(this.stateFormatPainter);
if (this.stateFormatPainter) {
this.copyActiveSheet = this.wsActive;
} else {
this.copyActiveSheet = -1;
this.handlers.trigger('asc_onStopFormatPainter');
}
};
// Поиск текста в листе
WorkbookView.prototype.findCellText = function (options) {
this.closeCellEditor();
// Для поиска эта переменная не нужна (но она может остаться от replace)
options.selectionRange = null;
var result = this.model.findCellText(options);
if (result) {
var ws = this.getWorksheet();
var range = new Asc.Range(result.col, result.row, result.col, result.row);
options.findInSelection ? ws.setActiveCell(result) : ws.setSelection(range);
return true;
}
return null;
};
// Замена текста в листе
WorkbookView.prototype.replaceCellText = function (options) {
this.closeCellEditor();
if (!options.isMatchCase) {
options.findWhat = options.findWhat.toLowerCase();
}
options.findRegExp = AscCommonExcel.getFindRegExp(options.findWhat, options);
History.Create_NewPoint();
History.StartTransaction();
options.clearFindAll();
if (options.isReplaceAll) {
// На ReplaceAll ставим медленную операцию
this.Api.sync_StartAction(c_oAscAsyncActionType.BlockInteraction, c_oAscAsyncAction.SlowOperation);
}
var ws = this.getWorksheet();
ws.replaceCellText(options, false, this.fReplaceCallback);
};
WorkbookView.prototype._replaceCellTextCallback = function(options) {
if (!options.error) {
options.updateFindAll();
if (!options.scanOnOnlySheet && options.isReplaceAll) {
// Замена на всей книге
var i = ++options.sheetIndex;
if (this.model.getActive() === i) {
i = ++options.sheetIndex;
}
if (i < this.model.getWorksheetCount()) {
var ws = this.getWorksheet(i);
ws.replaceCellText(options, true, this.fReplaceCallback);
return;
}
options.sheetIndex = -1;
}
this.handlers.trigger("asc_onRenameCellTextEnd", options.countFindAll, options.countReplaceAll);
}
History.EndTransaction();
if (options.isReplaceAll) {
// Заканчиваем медленную операцию
this.Api.sync_EndAction(c_oAscAsyncActionType.BlockInteraction, c_oAscAsyncAction.SlowOperation);
}
};
WorkbookView.prototype.getDefinedNames = function(defNameListId) {
return this.model.getDefinedNamesWB(defNameListId, true);
};
WorkbookView.prototype.setDefinedNames = function(defName) {
//ToDo проверка defName.ref на знак "=" в начале ссылки. знака нет тогда это либо число либо строка, так делает Excel.
this.model.setDefinesNames(defName.Name, defName.Ref, defName.Scope);
this.handlers.trigger("asc_onDefName");
};
WorkbookView.prototype.editDefinedNames = function(oldName, newName) {
//ToDo проверка defName.ref на знак "=" в начале ссылки. знака нет тогда это либо число либо строка, так делает Excel.
if (this.collaborativeEditing.getGlobalLock()) {
return;
}
var ws = this.getWorksheet(), t = this;
var editDefinedNamesCallback = function(res) {
if (res) {
if (oldName && oldName.asc_getIsTable()) {
ws.model.autoFilters.changeDisplayNameTable(oldName.asc_getName(), newName.asc_getName());
} else {
t.model.editDefinesNames(oldName, newName);
}
t.handlers.trigger("asc_onEditDefName", oldName, newName);
//условие исключает второй вызов asc_onRefreshDefNameList(первый в unlockDefName)
if(!(t.collaborativeEditing.getCollaborativeEditing() && t.collaborativeEditing.getFast()))
{
t.handlers.trigger("asc_onRefreshDefNameList");
}
} else {
t.handlers.trigger("asc_onError", c_oAscError.ID.LockCreateDefName, c_oAscError.Level.NoCritical);
}
t._onSelectionNameChanged(ws.getSelectionName(/*bRangeText*/false));
if(ws.viewPrintLines) {
ws.updateSelection();
}
};
var defNameId;
if (oldName) {
defNameId = t.model.getDefinedName(oldName);
defNameId = defNameId ? defNameId.getNodeId() : null;
}
var callback = function() {
ws._isLockedDefNames(editDefinedNamesCallback, defNameId);
};
var tableRange;
if(oldName && true === oldName.isTable)
{
var table = ws.model.autoFilters._getFilterByDisplayName(oldName.Name);
if(table)
{
tableRange = table.Ref;
}
}
if(tableRange)
{
ws._isLockedCells( tableRange, null, callback );
}
else
{
callback();
}
};
WorkbookView.prototype.delDefinedNames = function(oldName) {
//ToDo проверка defName.ref на знак "=" в начале ссылки. знака нет тогда это либо число либо строка, так делает Excel.
if (this.collaborativeEditing.getGlobalLock()) {
return;
}
var ws = this.getWorksheet(), t = this;
if (oldName) {
var delDefinedNamesCallback = function(res) {
if (res) {
t.model.delDefinesNames(oldName);
t.handlers.trigger("asc_onRefreshDefNameList");
} else {
t.handlers.trigger("asc_onError", c_oAscError.ID.LockCreateDefName, c_oAscError.Level.NoCritical);
}
t._onSelectionNameChanged(ws.getSelectionName(/*bRangeText*/false));
if(ws.viewPrintLines) {
ws.updateSelection();
}
};
var defNameId = t.model.getDefinedName(oldName).getNodeId();
ws._isLockedDefNames(delDefinedNamesCallback, defNameId);
}
};
WorkbookView.prototype.getDefaultDefinedName = function() {
//ToDo проверка defName.ref на знак "=" в начале ссылки. знака нет тогда это либо число либо строка, так делает Excel.
var ws = this.getWorksheet();
var oRangeValue = ws.getSelectionRangeValue();
return new Asc.asc_CDefName("", oRangeValue.asc_getName(), null);
};
WorkbookView.prototype.getDefaultTableStyle = function() {
return this.model.TableStyles.DefaultTableStyle;
};
WorkbookView.prototype.unlockDefName = function() {
this.model.unlockDefName();
this.handlers.trigger("asc_onRefreshDefNameList");
this.handlers.trigger("asc_onLockDefNameManager", Asc.c_oAscDefinedNameReason.OK);
};
WorkbookView.prototype.unlockCurrentDefName = function(name, sheetId) {
this.model.unlockCurrentDefName(name, sheetId);
//this.handlers.trigger("asc_onRefreshDefNameList");
//this.handlers.trigger("asc_onLockDefNameManager", Asc.c_oAscDefinedNameReason.OK);
};
WorkbookView.prototype._onCheckDefNameLock = function() {
return this.model.checkDefNameLock();
};
// Печать
WorkbookView.prototype.printSheets = function(printPagesData, pdfDocRenderer) {
//change zoom on default
var viewZoom = this.getZoom();
this.changeZoom(1);
var pdfPrinter = new AscCommonExcel.CPdfPrinter(this.fmgrGraphics[3], this.m_oFont);
if (pdfDocRenderer) {
pdfPrinter.DocumentRenderer = pdfDocRenderer;
}
var ws;
if (0 === printPagesData.arrPages.length) {
// Печать пустой страницы
ws = this.getWorksheet();
ws.drawForPrint(pdfPrinter, null);
} else {
var indexWorksheet = -1;
var indexWorksheetTmp = -1;
for (var i = 0; i < printPagesData.arrPages.length; ++i) {
indexWorksheetTmp = printPagesData.arrPages[i].indexWorksheet;
if (indexWorksheetTmp !== indexWorksheet) {
ws = this.getWorksheet(indexWorksheetTmp);
indexWorksheet = indexWorksheetTmp;
}
ws.drawForPrint(pdfPrinter, printPagesData.arrPages[i], i, printPagesData.arrPages.length);
}
}
this.changeZoom(viewZoom);
return pdfPrinter;
};
WorkbookView.prototype._calcPagesPrintSheet = function (index, printPagesData, onlySelection, adjustPrint) {
var ws = this.model.getWorksheet(index);
var wsView = this.getWorksheet(index);
if (!ws.getHidden()) {
var pageOptionsMap = adjustPrint ? adjustPrint.asc_getPageOptionsMap() : null;
var pagePrintOptions = pageOptionsMap && pageOptionsMap[index] ? pageOptionsMap[index] : ws.PagePrintOptions;
wsView.calcPagesPrint(pagePrintOptions, onlySelection, index, printPagesData.arrPages, null, adjustPrint);
}
};
WorkbookView.prototype.calcPagesPrint = function (adjustPrint) {
if (!adjustPrint) {
adjustPrint = new Asc.asc_CAdjustPrint();
}
var viewZoom = this.getZoom();
this.changeZoom(1);
var printPagesData = new asc_CPrintPagesData();
var printType = adjustPrint.asc_getPrintType();
if (printType === Asc.c_oAscPrintType.ActiveSheets) {
this._calcPagesPrintSheet(this.model.getActive(), printPagesData, false, adjustPrint);
} else if (printType === Asc.c_oAscPrintType.EntireWorkbook) {
// Колличество листов
var countWorksheets = this.model.getWorksheetCount();
for (var i = 0; i < countWorksheets; ++i) {
if(adjustPrint.isOnlyFirstPage && i !== 0) {
break;
}
this._calcPagesPrintSheet(i, printPagesData, false, adjustPrint);
}
} else if (printType === Asc.c_oAscPrintType.Selection) {
this._calcPagesPrintSheet(this.model.getActive(), printPagesData, true, adjustPrint);
}
if (AscCommonExcel.c_kMaxPrintPages === printPagesData.arrPages.length) {
this.handlers.trigger("asc_onError", c_oAscError.ID.PrintMaxPagesCount, c_oAscError.Level.NoCritical);
}
this.changeZoom(viewZoom);
return printPagesData;
};
// Вызывать только для нативной печати
WorkbookView.prototype._nativeCalculate = function() {
var item;
for (var i in this.wsViews) {
item = this.wsViews[i];
item._cleanCellsTextMetricsCache();
item._prepareDrawingObjects();
}
};
WorkbookView.prototype.calculate = function (type) {
this.model.calculate(type);
this.drawWS();
};
WorkbookView.prototype.reInit = function() {
var ws = this.getWorksheet();
ws._initCellsArea(AscCommonExcel.recalcType.full);
ws._updateVisibleColsCount();
ws._updateVisibleRowsCount();
};
WorkbookView.prototype.drawWS = function() {
this.getWorksheet().draw();
};
WorkbookView.prototype.onShowDrawingObjects = function(clearCanvas) {
var ws = this.getWorksheet();
ws.objectRender.showDrawingObjects(clearCanvas);
};
WorkbookView.prototype.insertHyperlink = function(options) {
var ws = this.getWorksheet();
if (ws.objectRender.selectedGraphicObjectsExists()) {
if (ws.objectRender.controller.canAddHyperlink()) {
ws.objectRender.controller.insertHyperlink(options);
}
} else {
ws.setSelectionInfo("hyperlink", options);
this.restoreFocus();
}
};
WorkbookView.prototype.removeHyperlink = function() {
var ws = this.getWorksheet();
if (ws.objectRender.selectedGraphicObjectsExists()) {
ws.objectRender.controller.removeHyperlink();
} else {
ws.setSelectionInfo("rh");
}
};
WorkbookView.prototype.setDocumentPlaceChangedEnabled = function(val) {
this.isDocumentPlaceChangedEnabled = val;
};
WorkbookView.prototype.showComments = function (val, isShowSolved) {
if (this.isShowComments !== val || this.isShowSolved !== isShowSolved) {
this.isShowComments = val;
this.isShowSolved = isShowSolved;
this.drawWS();
}
};
WorkbookView.prototype.removeComment = function (id) {
var ws = this.getWorksheet();
ws.cellCommentator.removeComment(id);
this.cellCommentator.removeComment(id);
};
WorkbookView.prototype.removeAllComments = function (isMine, isCurrent) {
var range;
var ws = this.getWorksheet();
isMine = isMine ? (this.Api.DocInfo && this.Api.DocInfo.get_UserId()) : null;
History.Create_NewPoint();
History.StartTransaction();
if (isCurrent) {
ws._getSelection().ranges.forEach(function (item) {
ws.cellCommentator.deleteCommentsRange(item, isMine);
});
} else {
range = new Asc.Range(0, 0, AscCommon.gc_nMaxCol0, AscCommon.gc_nMaxRow0);
this.cellCommentator.deleteCommentsRange(range, isMine);
ws.cellCommentator.deleteCommentsRange(range, isMine);
}
History.EndTransaction();
};
/*
* @param {c_oAscRenderingModeType} mode Режим отрисовки
* @param {Boolean} isInit инициализация или нет
*/
WorkbookView.prototype.setFontRenderingMode = function(mode, isInit) {
if (mode !== this.fontRenderingMode) {
this.fontRenderingMode = mode;
if (c_oAscFontRenderingModeType.noHinting === mode) {
this._setHintsProps(false, false);
} else if (c_oAscFontRenderingModeType.hinting === mode) {
this._setHintsProps(true, false);
} else if (c_oAscFontRenderingModeType.hintingAndSubpixeling === mode) {
this._setHintsProps(true, true);
}
if (!isInit) {
this.drawWS();
this.cellEditor.setFontRenderingMode(mode);
}
}
};
WorkbookView.prototype.initFormulasList = function() {
this.formulasList = [];
var oFormulaList = AscCommonExcel.cFormulaFunctionLocalized ? AscCommonExcel.cFormulaFunctionLocalized :
AscCommonExcel.cFormulaFunction;
for (var f in oFormulaList) {
this.formulasList.push(f);
}
this.arrExcludeFormulas = [cBoolLocal.t, cBoolLocal.f];
};
WorkbookView.prototype._setHintsProps = function(bIsHinting, bIsSubpixHinting) {
var manager;
for (var i = 0, length = this.fmgrGraphics.length; i < length; ++i) {
manager = this.fmgrGraphics[i];
// Последний без хинтования (только для измерения)
if (i === length - 1) {
bIsHinting = bIsSubpixHinting = false;
}
manager.SetHintsProps(bIsHinting, bIsSubpixHinting);
}
};
WorkbookView.prototype._calcMaxDigitWidth = function () {
// set default worksheet header font for calculations
this.buffers.main.setFont(AscCommonExcel.g_oDefaultFormat.Font);
// Измеряем в pt
this.stringRender.measureString("0123456789", new AscCommonExcel.CellFlags());
// Переводим в px и приводим к целому (int)
this.model.maxDigitWidth = this.maxDigitWidth = this.stringRender.getWidestCharWidth();
// Проверка для Calibri 11 должно быть this.maxDigitWidth = 7
if (!this.maxDigitWidth) {
throw "Error: can't measure text string";
}
// Padding рассчитывается исходя из maxDigitWidth (http://social.msdn.microsoft.com/Forums/en-US/9a6a9785-66ad-4b6b-bb9f-74429381bd72/margin-padding-in-cell-excel?forum=os_binaryfile)
this.defaults.worksheetView.cells.padding = Math.max(asc.ceil(this.maxDigitWidth / 4), 2);
this.model.paddingPlusBorder = 2 * this.defaults.worksheetView.cells.padding + 1;
};
WorkbookView.prototype.getPivotMergeStyle = function (sheetMergedStyles, range, style, pivot) {
var styleInfo = pivot.asc_getStyleInfo();
var i, r, dxf, stripe1, stripe2, emptyStripe = new Asc.CTableStyleElement();
if (style) {
dxf = style.wholeTable && style.wholeTable.dxf;
if (dxf) {
sheetMergedStyles.setTablePivotStyle(range, dxf);
}
if (styleInfo.showColStripes) {
stripe1 = style.firstColumnStripe || emptyStripe;
stripe2 = style.secondColumnStripe || emptyStripe;
if (stripe1.dxf) {
sheetMergedStyles.setTablePivotStyle(range, stripe1.dxf,
new Asc.CTableStyleStripe(stripe1.size, stripe2.size));
}
if (stripe2.dxf && range.c1 + stripe1.size <= range.c2) {
sheetMergedStyles.setTablePivotStyle(
new Asc.Range(range.c1 + stripe1.size, range.r1, range.c2, range.r2), stripe2.dxf,
new Asc.CTableStyleStripe(stripe2.size, stripe1.size));
}
}
if (styleInfo.showRowStripes) {
stripe1 = style.firstRowStripe || emptyStripe;
stripe2 = style.secondRowStripe || emptyStripe;
if (stripe1.dxf) {
sheetMergedStyles.setTablePivotStyle(range, stripe1.dxf,
new Asc.CTableStyleStripe(stripe1.size, stripe2.size, true));
}
if (stripe2.dxf && range.r1 + stripe1.size <= range.r2) {
sheetMergedStyles.setTablePivotStyle(
new Asc.Range(range.c1, range.r1 + stripe1.size, range.c2, range.r2), stripe2.dxf,
new Asc.CTableStyleStripe(stripe2.size, stripe1.size, true));
}
}
dxf = style.firstColumn && style.firstColumn.dxf;
if (styleInfo.showRowHeaders && dxf) {
sheetMergedStyles.setTablePivotStyle(new Asc.Range(range.c1, range.r1, range.c1, range.r2), dxf);
}
dxf = style.headerRow && style.headerRow.dxf;
if (styleInfo.showColHeaders && dxf) {
sheetMergedStyles.setTablePivotStyle(new Asc.Range(range.c1, range.r1, range.c2, range.r1), dxf);
}
dxf = style.firstHeaderCell && style.firstHeaderCell.dxf;
if (styleInfo.showColHeaders && styleInfo.showRowHeaders && dxf) {
sheetMergedStyles.setTablePivotStyle(new Asc.Range(range.c1, range.r1, range.c1, range.r1), dxf);
}
if (pivot.asc_getColGrandTotals()) {
dxf = style.lastColumn && style.lastColumn.dxf;
if (dxf) {
sheetMergedStyles.setTablePivotStyle(new Asc.Range(range.c2, range.r1, range.c2, range.r2), dxf);
}
}
if (styleInfo.showRowHeaders) {
for (i = range.r1 + 1; i < range.r2; ++i) {
r = i - (range.r1 + 1);
if (0 === r % 3) {
dxf = style.firstRowSubheading;
}
if (dxf = (dxf && dxf.dxf)) {
sheetMergedStyles.setTablePivotStyle(new Asc.Range(range.c1, i, range.c2, i), dxf);
}
}
}
if (pivot.asc_getRowGrandTotals()) {
dxf = style.totalRow && style.totalRow.dxf;
if (dxf) {
sheetMergedStyles.setTablePivotStyle(new Asc.Range(range.c1, range.r2, range.c2, range.r2), dxf);
}
}
}
};
WorkbookView.prototype.getTableStyles = function (props, bPivotTable) {
var wb = this.model;
var t = this;
var result = [];
var canvas = document.createElement('canvas');
var tableStyleInfo;
var pivotStyleInfo;
var defaultStyles, styleThumbnailHeight, row, col = 5;
var styleThumbnailWidth = window["IS_NATIVE_EDITOR"] ? 90 : 61;
if(bPivotTable)
{
styleThumbnailHeight = 49;
row = 8;
defaultStyles = wb.TableStyles.DefaultStylesPivot;
pivotStyleInfo = props;
}
else
{
styleThumbnailHeight = window["IS_NATIVE_EDITOR"] ? 48 : 46;
row = 5;
defaultStyles = wb.TableStyles.DefaultStyles;
tableStyleInfo = new AscCommonExcel.TableStyleInfo();
if (props) {
tableStyleInfo.ShowColumnStripes = props.asc_getBandVer();
tableStyleInfo.ShowFirstColumn = props.asc_getFirstCol();
tableStyleInfo.ShowLastColumn = props.asc_getLastCol();
tableStyleInfo.ShowRowStripes = props.asc_getBandHor();
tableStyleInfo.HeaderRowCount = props.asc_getFirstRow();
tableStyleInfo.TotalsRowCount = props.asc_getLastRow();
} else {
tableStyleInfo.ShowColumnStripes = false;
tableStyleInfo.ShowFirstColumn = false;
tableStyleInfo.ShowLastColumn = false;
tableStyleInfo.ShowRowStripes = true;
tableStyleInfo.HeaderRowCount = true;
tableStyleInfo.TotalsRowCount = false;
}
}
if (AscBrowser.isRetina)
{
styleThumbnailWidth = AscCommon.AscBrowser.convertToRetinaValue(styleThumbnailWidth, true);
styleThumbnailHeight = AscCommon.AscBrowser.convertToRetinaValue(styleThumbnailHeight, true);
}
canvas.width = styleThumbnailWidth;
canvas.height = styleThumbnailHeight;
var sizeInfo = {w: styleThumbnailWidth, h: styleThumbnailHeight, row: row, col: col};
var ctx = new Asc.DrawingContext({canvas: canvas, units: 0/*px*/, fmgrGraphics: this.fmgrGraphics, font: this.m_oFont});
var addStyles = function(styles, type, bEmptyStyle)
{
var style;
for (var i in styles)
{
if ((bPivotTable && styles[i].pivot) || (!bPivotTable && styles[i].table))
{
if (window["IS_NATIVE_EDITOR"]) {
//TODO empty style?
window["native"]["BeginDrawStyle"](type, i);
}
t._drawTableStyle(ctx, styles[i], tableStyleInfo, pivotStyleInfo, sizeInfo);
if (window["IS_NATIVE_EDITOR"]) {
window["native"]["EndDrawStyle"]();
} else {
style = new AscCommon.CStyleImage();
style.name = bEmptyStyle ? null : i;
style.displayName = styles[i].displayName;
style.type = type;
style.image = canvas.toDataURL("image/png");
result.push(style);
}
}
}
};
addStyles(wb.TableStyles.CustomStyles, AscCommon.c_oAscStyleImage.Document);
if (props) {
//None style
var emptyStyle = new Asc.CTableStyle();
emptyStyle.displayName = "None";
emptyStyle.pivot = bPivotTable;
addStyles({null: emptyStyle}, AscCommon.c_oAscStyleImage.Default, true);
}
addStyles(defaultStyles, AscCommon.c_oAscStyleImage.Default);
return result;
};
WorkbookView.prototype._drawTableStyle = function (ctx, style, tableStyleInfo, pivotStyleInfo, size) {
ctx.clear();
var w = size.w;
var h = size.h;
var row = size.row;
var col = size.col;
var startX = 1;
var startY = 1;
var ySize = (h - 1) - 2 * startY;
var xSize = w - 2 * startX;
var stepY = (ySize) / row;
var stepX = (xSize) / col;
var lineStepX = (xSize - 1) / 5;
var whiteColor = new CColor(255, 255, 255);
var blackColor = new CColor(0, 0, 0);
var defaultColor;
if (!style || !style.wholeTable || !style.wholeTable.dxf.font) {
defaultColor = blackColor;
} else {
defaultColor = style.wholeTable.dxf.font.getColor();
}
ctx.setFillStyle(whiteColor);
ctx.fillRect(0, 0, xSize + 2 * startX, ySize + 2 * startY);
var calculateLineVer = function(color, x, y1, y2)
{
ctx.beginPath();
ctx.setStrokeStyle(color);
ctx.lineVer(x + startX, y1 + startY, y2 + startY);
ctx.stroke();
ctx.closePath();
};
var calculateLineHor = function(color, x1, y, x2)
{
ctx.beginPath();
ctx.setStrokeStyle(color);
ctx.lineHor(x1 + startX, y + startY, x2 + startX);
ctx.stroke();
ctx.closePath();
};
var calculateRect = function(color, x1, y1, w, h)
{
ctx.beginPath();
ctx.setFillStyle(color);
ctx.fillRect(x1 + startX, y1 + startY, w, h);
ctx.closePath();
};
var bbox = new Asc.Range(0, 0, col - 1, row - 1);
var sheetMergedStyles = new AscCommonExcel.SheetMergedStyles();
var hiddenManager = new AscCommonExcel.HiddenManager(null);
if(pivotStyleInfo)
{
this.getPivotMergeStyle(sheetMergedStyles, bbox, style, pivotStyleInfo);
}
else if(tableStyleInfo)
{
style.initStyle(sheetMergedStyles, bbox, tableStyleInfo,
null !== tableStyleInfo.HeaderRowCount ? tableStyleInfo.HeaderRowCount : 1,
null !== tableStyleInfo.TotalsRowCount ? tableStyleInfo.TotalsRowCount : 0);
}
var compiledStylesArr = [];
for (var i = 0; i < row; i++)
{
for (var j = 0; j < col; j++) {
var color = null, prevStyle;
var curStyle = AscCommonExcel.getCompiledStyle(sheetMergedStyles, hiddenManager, i, j);
if(!compiledStylesArr[i])
{
compiledStylesArr[i] = [];
}
compiledStylesArr[i][j] = curStyle;
//fill
color = curStyle && curStyle.fill && curStyle.fill.bg();
if(color)
{
calculateRect(color, j * stepX, i * stepY, stepX, stepY);
}
//borders
//left
prevStyle = (j - 1 >= 0) ? compiledStylesArr[i][j - 1] : null;
color = AscCommonExcel.getMatchingBorder(prevStyle && prevStyle.border && prevStyle.border.r, curStyle && curStyle.border && curStyle.border.l);
if(color && color.w > 0)
{
calculateLineVer(color.c, j * lineStepX, i * stepY, (i + 1) * stepY);
}
//right
color = curStyle && curStyle.border && curStyle.border.r;
if(color && color.w > 0)
{
calculateLineVer(color.c, (j + 1) * lineStepX, i * stepY, (i + 1) * stepY);
}
//top
prevStyle = (i - 1 >= 0) ? compiledStylesArr[i - 1][j] : null;
color = AscCommonExcel.getMatchingBorder(prevStyle && prevStyle.border && prevStyle.border.b, curStyle && curStyle.border && curStyle.border.t);
if(color && color.w > 0)
{
calculateLineHor(color.c, j * stepX, i * stepY, (j + 1) * stepX);
}
//bottom
color = curStyle && curStyle.border && curStyle.border.b;
if(color && color.w > 0)
{
calculateLineHor(color.c, j * stepX, (i + 1) * stepY, (j + 1) * stepX);
}
//marks
color = (curStyle && curStyle.font && curStyle.font.c) || defaultColor;
calculateLineHor(color, j * lineStepX + 3, (i + 1) * stepY - stepY / 2, (j + 1) * lineStepX - 2);
}
}
};
WorkbookView.prototype.IsSelectionUse = function () {
return !this.getWorksheet().getSelectionShape();
};
WorkbookView.prototype.GetSelectionRectsBounds = function () {
if (this.getWorksheet().getSelectionShape())
return null;
var ws = this.getWorksheet();
var range = ws.model.selectionRange.getLast();
var type = range.getType();
var l = ws.getCellLeft(range.c1, 3);
var t = ws.getCellTop(range.r1, 3);
var offset = ws.getCellsOffset(3);
return {
X: asc.c_oAscSelectionType.RangeRow === type ? -offset.left : l - offset.left,
Y: asc.c_oAscSelectionType.RangeCol === type ? -offset.top : t - offset.top,
W: asc.c_oAscSelectionType.RangeRow === type ? offset.left :
ws.getCellLeft(range.c2, 3) - l + ws.getColumnWidth(range.c2, 3),
H: asc.c_oAscSelectionType.RangeCol === type ? offset.top :
ws.getCellTop(range.r2, 3) - t + ws.getRowHeight(range.r2, 3),
T: type
};
};
WorkbookView.prototype.GetCaptionSize = function()
{
var offset = this.getWorksheet().getCellsOffset(3);
return {
W: offset.left,
H: offset.top
};
};
WorkbookView.prototype.ConvertXYToLogic = function (x, y) {
return this.getWorksheet().ConvertXYToLogic(x, y);
};
WorkbookView.prototype.ConvertLogicToXY = function (xL, yL) {
return this.getWorksheet().ConvertLogicToXY(xL, yL)
};
WorkbookView.prototype.changeFormatTableInfo = function (tableName, optionType, val) {
var ws = this.getWorksheet();
return ws.af_changeFormatTableInfo(tableName, optionType, val);
};
WorkbookView.prototype.applyAutoCorrectOptions = function (val) {
var api = window["Asc"]["editor"];
var prevProps;
switch (val) {
case Asc.c_oAscAutoCorrectOptions.UndoTableAutoExpansion: {
prevProps = {
props: this.autoCorrectStore.props,
cell: this.autoCorrectStore.cell,
wsId: this.autoCorrectStore.wsId
};
api.asc_Undo();
this.autoCorrectStore = prevProps;
this.autoCorrectStore.props[0] = Asc.c_oAscAutoCorrectOptions.RedoTableAutoExpansion;
this.toggleAutoCorrectOptions(true);
break;
}
case Asc.c_oAscAutoCorrectOptions.RedoTableAutoExpansion: {
prevProps = {
props: this.autoCorrectStore.props,
cell: this.autoCorrectStore.cell,
wsId: this.autoCorrectStore.wsId
};
api.asc_Redo();
this.autoCorrectStore = prevProps;
this.autoCorrectStore.props[0] = Asc.c_oAscAutoCorrectOptions.UndoTableAutoExpansion;
this.toggleAutoCorrectOptions(true);
break;
}
}
return true;
};
WorkbookView.prototype.toggleAutoCorrectOptions = function (isSwitch, val) {
if (isSwitch) {
if (val) {
this.autoCorrectStore = val;
var options = new Asc.asc_CAutoCorrectOptions();
options.asc_setOptions(this.autoCorrectStore.props);
options.asc_setCellCoord(
this.getWorksheet().getCellCoord(this.autoCorrectStore.cell.c1, this.autoCorrectStore.cell.r1));
this.handlers.trigger("asc_onToggleAutoCorrectOptions", options);
} else if (this.autoCorrectStore) {
if (this.autoCorrectStore.wsId === this.model.getActiveWs().getId()) {
var options = new Asc.asc_CAutoCorrectOptions();
options.asc_setOptions(this.autoCorrectStore.props);
options.asc_setCellCoord(
this.getWorksheet().getCellCoord(this.autoCorrectStore.cell.c1, this.autoCorrectStore.cell.r1));
this.handlers.trigger("asc_onToggleAutoCorrectOptions", options);
} else {
this.handlers.trigger("asc_onToggleAutoCorrectOptions");
}
}
} else {
if(this.autoCorrectStore) {
if (val) {
this.autoCorrectStore = null;
}
this.handlers.trigger("asc_onToggleAutoCorrectOptions");
}
}
};
WorkbookView.prototype.savePagePrintOptions = function (arrPagesPrint) {
var t = this;
var viewMode = !this.canEdit();
if(!arrPagesPrint) {
return;
}
var callback = function (isSuccess) {
if (false === isSuccess) {
return;
}
for(var i in arrPagesPrint) {
var ws = t.getWorksheet(parseInt(i));
ws.savePageOptions(arrPagesPrint[i], viewMode);
window["Asc"]["editor"]._onUpdateLayoutMenu(ws.model.Id);
}
};
var lockInfoArr = [];
var lockInfo;
for(var i in arrPagesPrint) {
lockInfo = this.getWorksheet(parseInt(i)).getLayoutLockInfo();
lockInfoArr.push(lockInfo);
}
if(viewMode) {
callback();
} else {
this.collaborativeEditing.lock(lockInfoArr, callback);
}
};
WorkbookView.prototype.cleanCutData = function (bDrawSelection, bCleanBuffer) {
if(this.cutIdSheet) {
var activeWs = this.wsViews[this.wsActive];
var ws = this.getWorksheetById(this.cutIdSheet);
if(bDrawSelection && activeWs && ws && activeWs.model.Id === ws.model.Id) {
activeWs.cleanSelection();
}
if(ws) {
ws.cutRange = null;
}
this.cutIdSheet = null;
if(bDrawSelection && activeWs && ws && activeWs.model.Id === ws.model.Id) {
activeWs.updateSelection();
}
//ms чистит буфер, если происходят какие-то изменения в документе с посвеченной областью вырезать
//мы в данном случае не можем так делать, поскольку не можем прочесть информацию из буфера и убедиться, что
//там именно тот вырезанный фрагмент. тем самым можем затереть какую-то важную информацию
if(bCleanBuffer) {
AscCommon.g_clipboardBase.ClearBuffer();
}
}
};
WorkbookView.prototype.updateGroupData = function () {
this.getWorksheet()._updateGroups(true);
this.getWorksheet()._updateGroups(null);
};
WorkbookView.prototype.pasteSheet = function (base64, insertBefore, name, callback) {
var t = this;
var tempWorkbook = new AscCommonExcel.Workbook();
tempWorkbook.setCommonIndexObjectsFrom(this.model);
var pasteProcessor = AscCommonExcel.g_clipboardExcel.pasteProcessor;
var aPastedImages = pasteProcessor._readExcelBinary(base64.split('xslData;')[1], tempWorkbook, true);
var pastedWs = tempWorkbook.aWorksheets[0];
var newFonts = {};
newFonts = tempWorkbook.generateFontMap2();
newFonts = pasteProcessor._convertFonts(newFonts);
for (var i = 0; i < pastedWs.Drawings.length; i++) {
pastedWs.Drawings[i].graphicObject.getAllFonts(newFonts);
}
var doCopy = function() {
History.Create_NewPoint();
var renameParams = t.model.copyWorksheet(0, insertBefore, name, undefined, undefined, undefined, pastedWs);
callback(renameParams);
};
var api = window["Asc"]["editor"];
api._loadFonts(newFonts, function () {
if (aPastedImages && aPastedImages.length) {
pasteProcessor._loadImagesOnServer(aPastedImages, function () {
doCopy();
});
} else {
doCopy();
}
});
};
//------------------------------------------------------------export---------------------------------------------------
window['AscCommonExcel'] = window['AscCommonExcel'] || {};
window["AscCommonExcel"].WorkbookView = WorkbookView;
})(window);
| [se] Refactoring
Delete unused code
| cell/view/WorkbookView.js | [se] Refactoring | <ide><path>ell/view/WorkbookView.js
<ide> background: new CColor(193, 193, 193), border: new CColor(146, 146, 146), color: new CColor(54, 54, 54)
<ide> }, { // kHeaderHighlighted
<ide> background: new CColor(223, 223, 223), border: new CColor(175, 175, 175), color: new CColor(101, 106, 112)
<del> }, { // kHeaderSelected
<del> background: new CColor(170, 170, 170), border: new CColor(117, 119, 122), color: new CColor(54, 54, 54)
<ide> }], cornerColor: new CColor(193, 193, 193)
<ide> };
<ide> this.cells = { |
|
Java | apache-2.0 | 5d239212826826dd9d7be6bbf1bccfb58d56ec7b | 0 | karma-exchange-org/karma-exchange,karma-exchange-org/karma-exchange | package org.karmaexchange.dao;
import static java.lang.String.format;
import static org.karmaexchange.util.OfyService.ofy;
import static org.karmaexchange.util.UserService.getCurrentUserKey;
import static com.google.common.base.CharMatcher.WHITESPACE;
import static com.google.common.base.Preconditions.checkState;
import java.util.Collection;
import java.util.Date;
import java.util.EnumSet;
import java.util.Iterator;
import java.util.List;
import javax.annotation.Nullable;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import org.karmaexchange.dao.Organization.Role;
import org.karmaexchange.resources.msg.ErrorResponseMsg;
import org.karmaexchange.resources.msg.ErrorResponseMsg.ErrorInfo;
import org.karmaexchange.resources.msg.ValidationErrorInfo;
import org.karmaexchange.resources.msg.ValidationErrorInfo.ValidationError;
import org.karmaexchange.resources.msg.ValidationErrorInfo.ValidationErrorType;
import org.karmaexchange.task.ProcessRatingsServlet;
import org.karmaexchange.util.BoundedHashSet;
import org.karmaexchange.util.SearchUtil;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.ToString;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.googlecode.objectify.Key;
import com.googlecode.objectify.VoidWork;
import com.googlecode.objectify.annotation.Embed;
import com.googlecode.objectify.annotation.Entity;
import com.googlecode.objectify.annotation.Ignore;
import com.googlecode.objectify.annotation.Index;
// TODO(avaliani):
// - Fix EventSearchView for images once we revamp it.
@XmlRootElement
@Entity
@Data
@EqualsAndHashCode(callSuper=true)
@ToString(callSuper=true)
public final class Event extends IdBaseDao<Event> {
/*
* DESIGN DETAILS
*
* Event permissions
* -----------------
* The current permissions scheme is that there is one organization for each event. And that any
* organizer or admin for the organization can edit the event. This simple model handles the
* 99% usage scenario.
*/
public static final int MAX_EVENT_KARMA_POINTS = 500;
public static final int MAX_CACHED_PARTICIPANT_IMAGES = 10;
/* Each event search token results in an index write. Put a reasonable limit on it. */
public static final int MAX_SEARCH_TOKENS = 100;
/*
* TODO(avaliani):
* - look at volunteer match schema
* - compare this to Meetup, OneBrick, Golden Gate athletic club, etc.
*/
private String title;
private String description;
private String specialInstructions; // See flash volunteer.
@Index
private List<KeyWrapper<CauseType>> causes = Lists.newArrayList();
private Location location;
@Index
private Date startTime;
@Index
private Date endTime;
@Ignore
private Status status;
private AlbumRef album;
// private Image primaryImage;
// BUG: This embedded list is not safe since Image has embedded objects that can be
// optionally null. See objectify serialization bug (issue #127).
// TODO(avaliani): fix this embedded list.
// private List<Image> allImages = Lists.newArrayList();
@Index
private List<KeyWrapper<Skill>> skillsPreferred = Lists.newArrayList();
@Index
private List<KeyWrapper<Skill>> skillsRequired = Lists.newArrayList();
// TODO(avaliani): Organizations can co-host events.
@Index
private KeyWrapper<Organization> organization;
private List<OrganizationNamedKeyWrapper> associatedOrganizations = Lists.newArrayList();
// Can not be explicitly set. Automatically managed.
@Ignore
private List<KeyWrapper<User>> organizers = Lists.newArrayList();
// Can not be explicitly set. Automatically managed.
@Ignore
private RegistrationInfo registrationInfo;
// The maxRegistration limit only applies to participants. The limit does not include organizers.
private int maxRegistrations;
// Can not be explicitly set. Automatically managed.
@Ignore
private List<KeyWrapper<User>> registeredUsers = Lists.newArrayList();
// Can not be explicitly set. Automatically managed.
@Ignore
private List<KeyWrapper<User>> waitListedUsers = Lists.newArrayList();
// NOTE: Embedded list is safe since EventParticipant has embedded objects that are always
// non-null.
private List<EventParticipant> participants = Lists.newArrayList();
// We need a consolidated list because pagination does not support OR queries.
// NOTE: We can try adding a conditional index parameter to EventParticipant in the future.
// Need to make sure that there are no objectify serialization / deserialization bugs with
// that model.
@Index
private List<KeyWrapper<User>> indexedParticipants = Lists.newArrayList();
// Can not be set. Automatically managed. Only includes organizers and registered users. Wait
// listed users images are skipped.
// NOTE: Embedded list is safe since ParticipantImage has embedded objects that are always
// non-null.
private List<ParticipantImage> cachedParticipantImages = Lists.newArrayList();
private IndexedAggregateRating rating;
private DerivedRatingTracker derivedRatings;
/**
* The number of karma points earned by participating in the event. This is derived from the
* start and end time.
*/
@Index
private int karmaPoints;
@Index
private List<String> searchableTokens;
@Index
private boolean completionProcessed;
private CompletionTaskTracker completionTasks;
/*
* If this is false and the event is complete then the organizer should be asked to update
* the attendance info and write an event thank you note.
*/
private boolean organizerProcessedCompletion;
private List<SuitableForType> suitableForTypes = Lists.newArrayList();
public enum RegistrationInfo {
ORGANIZER,
REGISTERED,
REGISTERED_NO_SHOW,
WAIT_LISTED,
CAN_REGISTER,
CAN_WAIT_LIST,
FULL
}
public enum Status {
UPCOMING,
IN_PROGRESS,
COMPLETED
}
public enum ParticipantType {
ORGANIZER,
REGISTERED,
REGISTERED_NO_SHOW,
WAIT_LISTED
}
private enum MutationType {
INSERT,
UPDATE,
DELETE
}
public void setOrganizers(List<KeyWrapper<User>> ignored) {
// No-op it.
}
public void setRegisteredUsers(List<KeyWrapper<User>> ignored) {
// No-op it.
}
public void setWaitListedUsers(List<KeyWrapper<User>> ignored) {
// No-op it.
}
public void setCachedParticipantImages(List<ParticipantImage> ignored) {
// No-op it.
}
public void setRegistrationInfo(RegistrationInfo ignored) {
// No-op it.
}
public static String getParticipantPropertyName() {
return "indexedParticipants.key";
}
@Override
protected void preProcessInsert() {
super.preProcessInsert();
if (title != null) {
title = WHITESPACE.trimFrom(title);
}
for (EventParticipant participant : participants) {
if (participant.type == ParticipantType.REGISTERED_NO_SHOW) {
throw ErrorResponseMsg.createException(
"only events that have completed can have no show participants",
ErrorInfo.Type.BAD_REQUEST);
}
}
initParticipantLists();
// Add the current user as an organizer if there are no organizers registered.
if (organizers.isEmpty()) {
Iterables.removeIf(participants, EventParticipant.userPredicate(getCurrentUserKey()));
participants.add(EventParticipant.create(getCurrentUserKey(), ParticipantType.ORGANIZER));
initParticipantLists();
}
processParticipants();
processSuitableFor();
validateEvent();
initKarmaPoints();
rating = IndexedAggregateRating.create();
initDerivedRatings();
// The list of associated organizations is consumed by initSearchableTokens(), so the
// associated organizations must be set prior to invoking initSearchableTokens().
initAssociatedOrganizations();
initSearchableTokens();
completionProcessed = false;
completionTasks = null;
}
@Override
protected void processUpdate(Event prevObj) {
super.processUpdate(prevObj);
if (title != null) {
title = WHITESPACE.trimFrom(title);
}
initKarmaPoints();
// Rating is independently and transactionally updated.
rating = prevObj.rating;
derivedRatings = prevObj.derivedRatings;
// Participants is independently and transactionally updated.
participants = Lists.newArrayList(prevObj.participants);
processParticipants();
processSuitableFor();
validateEvent();
// The list of associated organizations is consumed by initSearchableTokens(), so the
// associated organizations must be set prior to invoking initSearchableTokens().
associatedOrganizations = prevObj.associatedOrganizations;
initSearchableTokens();
completionProcessed = prevObj.completionProcessed;
completionTasks = prevObj.completionTasks;
// Do event validation that is specific to event updates.
validateEventUpdate(prevObj);
}
private void processParticipantMutation(EventParticipant updatedParticipant,
MutationType mutationType) {
processParticipantMutation(ImmutableList.of(updatedParticipant), mutationType);
}
private void processParticipantMutation(Collection<EventParticipant> mutatedParticipants,
MutationType mutationType) {
processParticipants();
for (EventParticipant participant : mutatedParticipants) {
derivedRatings.processParticipantMutation(this, participant, mutationType);
if (completionTasks != null) {
completionTasks.processParticipantMutation(this, participant, mutationType);
updateCompletionProcessed();
}
}
validateEvent();
}
private void processRatingUpdate() {
derivedRatings.processRatingUpdate(this);
}
private void processPendingRating() {
derivedRatings.processPendingRating(this);
}
private boolean hasPendingRatings() {
return derivedRatings.hasPendingRatings();
}
private void processCompletionTasks() {
// Note that we don't check the time to see if it's okay to process completion tasks.
// Instead we trust that the caller has checked the time. This handles cases where there
// is clock skew and the completion task was aborted and restarted on a different machine.
if (completionTasks == null) {
// This is the first time completion tasks are being processed. On the first pass the
// event object state must be cleaned up.
removeWaitListedUsers();
// After the state is cleaned up we process the remaining event completion tasks.
completionTasks = new CompletionTaskTracker(this);
}
completionTasks.processPendingTask(this);
updateCompletionProcessed();
}
private void updateCompletionProcessed() {
completionProcessed = !completionTasks.tasksPending();
}
private void removeWaitListedUsers() {
List<EventParticipant> participantsRemoved = Lists.newArrayList();
Iterator<EventParticipant> participantIter = participants.iterator();
while (participantIter.hasNext()) {
EventParticipant participant = participantIter.next();
if (participant.getType() == ParticipantType.WAIT_LISTED) {
participantIter.remove();
participantsRemoved.add(participant);
}
}
processParticipantMutation(participantsRemoved, MutationType.DELETE);
}
private void processParticipants() {
initParticipantLists();
processWaitList();
updateCachedParticipantImages();
}
private void processSuitableFor() {
if (!suitableForTypes.isEmpty()) {
// Eliminate any duplicates.
EnumSet<SuitableForType> suitableForSet = EnumSet.copyOf(suitableForTypes);
suitableForTypes = Lists.newArrayList(suitableForSet);
}
}
@Override
protected void processLoad() {
// initParticipantLists() must be called prior to processLoad so that updatePermissions can
// use the participant lists to calculate the permissions.
initParticipantLists();
super.processLoad();
initStatus();
updateRegistrationInfo();
}
private void initStatus() {
status = computeStatus(this);
}
private static Status computeStatus(Event event) {
if (event.completionTasks != null) {
return Status.COMPLETED;
}
Date now = new Date();
if (now.before(event.startTime)) {
return Status.UPCOMING;
} else if (now.before(event.endTime)) {
return Status.IN_PROGRESS;
} else {
return Status.COMPLETED;
}
}
private void initKarmaPoints() {
long eventDurationMins = (endTime.getTime() - startTime.getTime()) / (1000 * 60);
karmaPoints = (int) Math.min(eventDurationMins, MAX_EVENT_KARMA_POINTS);
}
private void initDerivedRatings() {
derivedRatings = new DerivedRatingTracker(this);
}
private void initAssociatedOrganizations() {
associatedOrganizations = Lists.newArrayList();
for (Organization org : Organization.getOrgAndAncestorOrgs(KeyWrapper.toKey(organization))) {
associatedOrganizations.add(new OrganizationNamedKeyWrapper(org));
}
}
private void initSearchableTokens() {
BoundedHashSet<String> searchableTokensSet = BoundedHashSet.create(MAX_SEARCH_TOKENS);
Key<Organization> primaryOrgKey = KeyWrapper.toKey(organization);
// Throw an exception if we can't add the primary org token to the searchableTokensSet.
searchableTokensSet.add(
SearchUtil.ReservedToken.PRIMARY_ORG.create(
Organization.getSearchTokenSuffix(primaryOrgKey)));
for (OrganizationNamedKeyWrapper orgKeyWrapper : associatedOrganizations) {
// Throw an exception if we can't add the org token to the searchableTokensSet.
searchableTokensSet.add(
SearchUtil.ReservedToken.ORG.create(
Organization.getSearchTokenSuffix(KeyWrapper.toKey(orgKeyWrapper))));
}
for (SuitableForType suitableForType : suitableForTypes) {
searchableTokensSet.addIfSpace(suitableForType.getTag());
}
// The lowest priority tokens should be added to the end of the searchableContent. Once the
// token limit is hit the remaining tokens will be discarded.
StringBuilder searchableContent = new StringBuilder();
searchableContent.append(title);
searchableContent.append(' ');
for (KeyWrapper<CauseType> causeKeyWrapper : causes) {
Key<CauseType> causeKey = KeyWrapper.toKey(causeKeyWrapper);
// We add causes both as tags and text strings to be parsed since keywords like
// homeless and animals are good for non-tag based keyword search.
searchableContent.append(CauseType.getCauseTypeAsString(causeKey));
searchableContent.append(' ');
searchableTokensSet.addIfSpace(CauseType.getTag(causeKey));
}
if ((location != null) && (location.getTitle() != null)) {
searchableContent.append(location.getTitle());
searchableContent.append(' ');
}
searchableContent.append(description);
SearchUtil.addSearchableTokens(searchableTokensSet, searchableContent.toString(),
EnumSet.of(SearchUtil.ParseOptions.EXCLUDE_RESERVED_TOKENS));
searchableTokens = Lists.newArrayList(searchableTokensSet);
}
private void initParticipantLists() {
organizers = Lists.newArrayList();
registeredUsers = Lists.newArrayList();
waitListedUsers = Lists.newArrayList();;
indexedParticipants = Lists.newArrayList();;
for (EventParticipant participant : participants) {
switch (participant.getType()) {
case ORGANIZER:
organizers.add(participant.getUser());
indexedParticipants.add(participant.getUser());
break;
case REGISTERED:
registeredUsers.add(participant.getUser());
indexedParticipants.add(participant.getUser());
break;
case REGISTERED_NO_SHOW:
// Do nothing.
break;
case WAIT_LISTED:
waitListedUsers.add(participant.getUser());
indexedParticipants.add(participant.getUser());
break;
default:
checkState(false, "unknown participant type: " + participant.getType());
}
}
}
@Nullable
private EventParticipant tryFindParticipant(Key<User> userKey) {
return Iterables.tryFind(participants, EventParticipant.userPredicate(userKey)).orNull();
}
public List<KeyWrapper<User>> getParticipants(ParticipantType participantType) {
List<KeyWrapper<User>> participantSubset = Lists.newArrayList();
for (EventParticipant participant : participants) {
if (participant.type == participantType) {
participantSubset.add(participant.user);
}
}
return participantSubset;
}
private void validateEvent() {
List<ValidationError> validationErrors = Lists.newArrayList();
if ((null == title) || title.isEmpty()) {
validationErrors.add(new ResourceValidationError(
this, ValidationErrorType.RESOURCE_FIELD_VALUE_REQUIRED, "title"));
}
// TODO(avaliani): make sure the description has a minimum length. Avoiding this for now
// since we don't have auto event creation.
if (null == startTime) {
validationErrors.add(new ResourceValidationError(
this, ValidationErrorType.RESOURCE_FIELD_VALUE_REQUIRED, "startTime"));
}
if (null == endTime) {
validationErrors.add(new ResourceValidationError(
this, ValidationErrorType.RESOURCE_FIELD_VALUE_REQUIRED, "endTime"));
}
if ((startTime != null) && (endTime != null) && !startTime.before(endTime)) {
validationErrors.add(new MultiFieldResourceValidationError(
this, ValidationErrorType.RESOURCE_FIELD_VALUE_MUST_BE_GT_SPECIFIED_FIELD,
"endTime", "startTime"));
}
if (maxRegistrations < 1) {
validationErrors.add(new LimitResourceValidationError(
this, ValidationErrorType.RESOURCE_FIELD_VALUE_MUST_BE_GTEQ_LIMIT,
"maxRegistrations", 1));
}
if (organization == null) {
validationErrors.add(new ResourceValidationError(
this, ValidationErrorType.RESOURCE_FIELD_VALUE_REQUIRED, "organization"));
} else {
if (organizers.isEmpty()) {
validationErrors.add(new ResourceValidationError(
this, ValidationErrorType.RESOURCE_FIELD_VALUE_REQUIRED, "organizers"));
List<User> organizerEntities =
BaseDao.load(KeyWrapper.toKeys(organizers), ofy().transactionless());
for (User organizer : organizerEntities) {
if (!organizer.hasOrgMembership(KeyWrapper.toKey(organization), Role.ORGANIZER)) {
validationErrors.add(new ListValueValidationError(
this, ValidationErrorType.RESOURCE_FIELD_LIST_VALUE_INVALID_PERMISSIONS, "organizers",
organizer.getKey()));
}
}
}
}
if (!validationErrors.isEmpty()) {
throw ValidationErrorInfo.createException(validationErrors);
}
}
private void validateEventUpdate(Event prevObj) {
List<ValidationError> validationErrors = Lists.newArrayList();
// Check the prev object's state since some of the fields of the current object can be
// manipulated in an update.
if (computeStatus(prevObj) == Status.COMPLETED) {
if (!startTime.equals(prevObj.startTime)) {
validationErrors.add(new ResourceValidationError(
this, ValidationErrorType.RESOURCE_FIELD_VALUE_UNMODIFIABLE, "startTime"));
}
if (!endTime.equals(prevObj.endTime)) {
validationErrors.add(new ResourceValidationError(
this, ValidationErrorType.RESOURCE_FIELD_VALUE_UNMODIFIABLE, "endTime"));
}
// To simplify completion task processing, we don't allow organizations to be modifiable
// after event completion.
if (!organization.equals(prevObj.organization)) {
validationErrors.add(new ResourceValidationError(
this, ValidationErrorType.RESOURCE_FIELD_VALUE_UNMODIFIABLE, "organization"));
}
}
if (!validationErrors.isEmpty()) {
throw ValidationErrorInfo.createException(validationErrors);
}
}
private void processWaitList() {
if ((registeredUsers.size() < maxRegistrations) &&
!waitListedUsers.isEmpty()) {
int numSpots = maxRegistrations - registeredUsers.size();
List<KeyWrapper<User>> usersToRegister =
waitListedUsers.subList(0, Math.min(numSpots, waitListedUsers.size()));
for (KeyWrapper<User> userToRegister : usersToRegister) {
EventParticipant participant = Iterables.find(participants,
EventParticipant.userPredicate(KeyWrapper.toKey(userToRegister)));
participant.setType(ParticipantType.REGISTERED);
}
initParticipantLists();
}
}
private void updateCachedParticipantImages() {
// Prune any deleted or wait listed participants.
Iterator<ParticipantImage> cachedImageIter = cachedParticipantImages.iterator();
while (cachedImageIter.hasNext()) {
ParticipantImage cachedImage = cachedImageIter.next();
Key<User> userKey = KeyWrapper.toKey(cachedImage.getParticipant());
EventParticipant participant = tryFindParticipant(userKey);
if ((participant == null) ||
((participant.getType() != ParticipantType.ORGANIZER) &&
(participant.getType() != ParticipantType.REGISTERED))) {
cachedImageIter.remove();
}
}
// Add images if there is room.
int numParticipantImagesToCache = getNumAttending() - cachedParticipantImages.size();
numParticipantImagesToCache = Math.min(numParticipantImagesToCache,
MAX_CACHED_PARTICIPANT_IMAGES - cachedParticipantImages.size());
if (numParticipantImagesToCache > 0) {
List<Key<User>> usersToFetch = Lists.newArrayList();
for (KeyWrapper<User> participantKey :
getAttendingParticipants(MAX_CACHED_PARTICIPANT_IMAGES)) {
if (!Iterables.any(cachedParticipantImages,
ParticipantImage.userPredicate(participantKey))) {
usersToFetch.add(KeyWrapper.toKey(participantKey));
numParticipantImagesToCache--;
if (numParticipantImagesToCache == 0) {
break;
}
}
}
List<User> participantsToCache = BaseDao.load(usersToFetch, ofy().transactionless());
for (User participantToCache : participantsToCache) {
cachedParticipantImages.add(ParticipantImage.create(participantToCache));
}
}
}
private List<KeyWrapper<User>> getAttendingParticipants(int limit) {
List<KeyWrapper<User>> attendingParticipants = Lists.newArrayList();
for (KeyWrapper<User> organizer : organizers) {
attendingParticipants.add(organizer);
limit--;
if (limit == 0) {
break;
}
}
if (limit > 0) {
for (KeyWrapper<User> registeredUser : registeredUsers) {
attendingParticipants.add(registeredUser);
limit--;
if (limit == 0) {
break;
}
}
}
return attendingParticipants;
}
public int getNumAttending() {
return organizers.size() + registeredUsers.size();
}
public void setNumAttending(int ignore) {
// No-op.
}
private void updateRegistrationInfo() {
EventParticipant participant = tryFindParticipant(getCurrentUserKey());
if (participant == null) {
if (registeredUsers.size() < maxRegistrations) {
registrationInfo = RegistrationInfo.CAN_REGISTER;
} else {
registrationInfo = RegistrationInfo.CAN_WAIT_LIST;
}
// } else if (waitListedUsers.size() < maxWaitingList) {
// registrationInfo = RegistrationInfo.CAN_WAIT_LIST;
// } else {
// registrationInfo = RegistrationInfo.FULL;
// }
} else {
if (participant.type == ParticipantType.ORGANIZER) {
registrationInfo = RegistrationInfo.ORGANIZER;
} else if (participant.type == ParticipantType.REGISTERED) {
registrationInfo = RegistrationInfo.REGISTERED;
} else if (participant.type == ParticipantType.REGISTERED_NO_SHOW) {
registrationInfo = RegistrationInfo.REGISTERED_NO_SHOW;
} else {
checkState(participant.type == ParticipantType.WAIT_LISTED,
"unknown participant type: " + participant.type);
registrationInfo = RegistrationInfo.WAIT_LISTED;
}
}
}
// TODO(avaliani): Always calculating eval permission is expensive in the long run. It results
// in additional loads even for read operations. Since we're fetching the current user
// transactionless the user should be saved in the session cache, so the overhead is not
// terrible. But this should be eliminated if possible.
@Override
protected Permission evalPermission() {
User currentUser = BaseDao.load(getCurrentUserKey(), ofy().transactionless());
if (currentUser.hasOrgMembership(KeyWrapper.toKey(organization),
Organization.Role.ORGANIZER)) {
return Permission.ALL;
}
return Permission.READ;
}
@Data
@EqualsAndHashCode(callSuper=false)
public static class UpsertParticipantTxn extends VoidWork {
private final Key<Event> eventKey;
private final Key<User> userToUpsertKey;
private final ParticipantType participantType;
public void vrun() {
Event event = BaseDao.load(eventKey);
if (event == null) {
throw ErrorResponseMsg.createException("event not found",
ErrorInfo.Type.BAD_REQUEST);
}
EventParticipant participantToUpsert = event.tryFindParticipant(userToUpsertKey);
// Users that can not edit the event are restricted to only adding themselves to the
// registered list or the waiting list. Additionally, users with edit permissions
// bypass all event registration and waiting list limits.
if (!event.permission.canEdit()) {
if (!userToUpsertKey.equals(getCurrentUserKey())) {
throw ErrorResponseMsg.createException(
"only organizers can add any participant to the event",
ErrorInfo.Type.BAD_REQUEST);
}
if (participantType == ParticipantType.ORGANIZER) {
throw ErrorResponseMsg.createException(
"insufficent priveleges to make the current user an organizer of the event",
ErrorInfo.Type.BAD_REQUEST);
}
if (participantType == ParticipantType.REGISTERED_NO_SHOW) {
throw ErrorResponseMsg.createException(
"insufficent priveleges to change the state of the current user to REGISTERED_NO_SHOW",
ErrorInfo.Type.BAD_REQUEST);
}
if ((participantToUpsert != null) && (participantToUpsert.getType() == participantType)) {
// Nothing to do.
return;
}
if (participantType == ParticipantType.REGISTERED) {
if (event.registeredUsers.size() >= event.maxRegistrations) {
throw ErrorResponseMsg.createException(
"the event has reached the max registration limit",
ErrorInfo.Type.LIMIT_REACHED);
}
} else {
checkState(participantType == ParticipantType.WAIT_LISTED);
// if (event.waitListedUsers.size() >= event.maxWaitingList) {
// throw ErrorResponseMsg.createException(
// "the event has reached the max waiting list limit",
// ErrorInfo.Type.LIMIT_REACHED);
// }
}
}
if (event.status == Status.COMPLETED) {
if (participantType == ParticipantType.ORGANIZER) {
throw ErrorResponseMsg.createException(
"organizers can not be added after event completion",
ErrorInfo.Type.BAD_REQUEST);
}
if (participantType == ParticipantType.WAIT_LISTED) {
throw ErrorResponseMsg.createException(
"wait listed users can not be added after event completion",
ErrorInfo.Type.BAD_REQUEST);
}
} else {
if (participantType == ParticipantType.REGISTERED_NO_SHOW) {
throw ErrorResponseMsg.createException(
"users can not be marked no show until the event is marked complete",
ErrorInfo.Type.BAD_REQUEST);
}
}
MutationType mutationType;
if (participantToUpsert == null) {
// TODO(avaliani): organizers should not in theory be allowed to add arbitrary users.
// However, this simplifies testing so we're going to allow it for now.
participantToUpsert = EventParticipant.create(userToUpsertKey, participantType);
event.participants.add(participantToUpsert);
mutationType = MutationType.INSERT;
} else {
ParticipantType prevParticipantType = participantToUpsert.getType();
if (participantType == prevParticipantType) {
// Nothing to do.
return;
}
if ((event.status == Status.COMPLETED) &&
(prevParticipantType == ParticipantType.ORGANIZER)) {
throw ErrorResponseMsg.createException(
"organizers can not be updated after event completion",
ErrorInfo.Type.BAD_REQUEST);
}
participantToUpsert.setType(participantType);
mutationType = MutationType.UPDATE;
}
// validateEvent() ensures that there is at least one organizer.
event.processParticipantMutation(participantToUpsert, mutationType);
BaseDao.partialUpdate(event);
}
}
@Data
@EqualsAndHashCode(callSuper=false)
public static class DeleteParticipantTxn extends VoidWork {
private final Key<Event> eventKey;
private final Key<User> userToRemoveKey;
public void vrun() {
Event event = BaseDao.load(eventKey);
if (event == null) {
throw ErrorResponseMsg.createException("event not found",
ErrorInfo.Type.BAD_REQUEST);
}
if (!event.permission.canEdit() && !userToRemoveKey.equals(getCurrentUserKey())) {
throw ErrorResponseMsg.createException(
"only organizers can remove any participant from the event",
ErrorInfo.Type.BAD_REQUEST);
}
EventParticipant participant = event.tryFindParticipant(userToRemoveKey);
if (participant != null) {
if (event.status == Status.COMPLETED) {
if (participant.getType() == ParticipantType.ORGANIZER) {
throw ErrorResponseMsg.createException(
"organizers can not be removed after event completion",
ErrorInfo.Type.BAD_REQUEST);
}
if (canWriteReview(participant)) {
Review participantReview = BaseDao.load(
Review.getKeyForUser(Key.create(event), KeyWrapper.toKey(participant.getUser())));
if (participantReview != null) {
throw ErrorResponseMsg.createException(
"users that have written a review can not be removed after event completion",
ErrorInfo.Type.BAD_REQUEST);
}
}
}
event.participants.remove(participant);
// validateEvent() ensures that there is at least one organizer.
event.processParticipantMutation(participant, MutationType.DELETE);
BaseDao.partialUpdate(event);
}
}
}
@Embed
@Data
@NoArgsConstructor
public static final class EventParticipant {
@Index
private KeyWrapper<User> user;
private ParticipantType type;
public static EventParticipant create(Key<User> user, ParticipantType type) {
return new EventParticipant(KeyWrapper.create(user), type);
}
private EventParticipant(KeyWrapper<User> user, ParticipantType type) {
this.user = user;
this.type = type;
}
public static Predicate<EventParticipant> userPredicate(final Key<User> userKey) {
return new Predicate<EventParticipant>() {
@Override
public boolean apply(@Nullable EventParticipant input) {
return KeyWrapper.toKey(input.user).equals(userKey);
}
};
}
}
public static void mutateEventReviewForCurrentUser(Key<Event> eventKey, @Nullable Review review) {
ofy().transact(new MutateEventReviewTxn(eventKey, getCurrentUserKey(), review));
}
@Data
@EqualsAndHashCode(callSuper=false)
private static class MutateEventReviewTxn extends VoidWork {
private final Key<Event> eventKey;
private final Key<User> userKey;
@Nullable
private final Review review;
public void vrun() {
Event event = BaseDao.load(eventKey);
if (event == null) {
throw ErrorResponseMsg.createException("event not found", ErrorInfo.Type.BAD_REQUEST);
}
EventParticipant participantDetails = event.tryFindParticipant(userKey);
if ((participantDetails == null) || !canWriteReview(participantDetails)) {
throw ErrorResponseMsg.createException(
"only users that participated in the event (non-organizers) can provide an event review",
ErrorInfo.Type.BAD_REQUEST);
}
if (event.status != Status.COMPLETED) {
throw ErrorResponseMsg.createException(
"only events that have completed can be reviewed", ErrorInfo.Type.BAD_REQUEST);
}
processReviewMutation(event, userKey, review);
BaseDao.partialUpdate(event);
}
}
public static void processReviewMutation(Event event, Key<User> userKey,
@Nullable Review review) {
boolean ratingMutated = false;
Key<Review> expReviewKey = Review.getKeyForUser(Key.create(event), userKey);
if (review != null) {
review.initPreUpsert(Key.create(event), userKey);
if (!Key.create(review).equals(expReviewKey)) {
throw ErrorResponseMsg.createException(
format("review key [%s] does not match expected review key [%s]",
Key.create(review).toString(), expReviewKey.toString()),
ErrorInfo.Type.BAD_REQUEST);
}
}
Review existingReview = BaseDao.load(expReviewKey);
if (existingReview != null) {
event.rating.deleteRating(existingReview.getRating());
ratingMutated = true;
}
if (review == null) {
if (existingReview != null) {
BaseDao.delete(Key.create(existingReview));
}
} else {
event.rating.addRating(review.getRating());
ratingMutated = true;
// An upsert will automatically delete the old review since the key for the new and the
// old review is the same.
BaseDao.upsert(review);
}
if (ratingMutated) {
event.processRatingUpdate();
}
}
private static boolean canWriteReview(EventParticipant participant) {
return participant.getType() == ParticipantType.REGISTERED;
}
/**
* This class updates the organizer event ratings for all organizers associated with an event.
*
* Note that all methods in this class should be invoked from within the context of a transaction.
*/
@Data
@Embed
@NoArgsConstructor
public static class DerivedRatingTracker {
// NOTE: The embedded lists are safe since DerivedRatingWrapper has been modified to avoid
// encountering the objectify serialization bug (issue #127).
List<DerivedRatingWrapper> processed = Lists.newArrayList();
List<DerivedRatingWrapper> pending = Lists.newArrayList();
public DerivedRatingTracker(Event event) {
for (EventParticipant participant : event.participants) {
if (participant.getType() == ParticipantType.ORGANIZER) {
processParticipantMutation(event, participant, MutationType.INSERT);
}
}
processed.add(new DerivedRatingWrapper(
new OrganizationDerivedRating(KeyWrapper.toKey(event.organization))));
}
public void processParticipantMutation(Event event, EventParticipant participant,
MutationType mutationType) {
processParticipantMutation(event, KeyWrapper.toKey(participant.getUser()),
((mutationType == MutationType.DELETE) ? false :
(participant.getType() == ParticipantType.ORGANIZER)));
}
private void processParticipantMutation(Event event, Key<User> userKey, boolean isOrganizer) {
boolean pendingQueueWasEmpty = pending.isEmpty();
DerivedRatingWrapper derivedRating = tryFindOrganizerDerivedRating(pending, userKey);
if (derivedRating != null) {
// Nothing to do, already queued.
return;
}
derivedRating = tryFindOrganizerDerivedRating(processed, userKey);
if (derivedRating == null) {
if (isOrganizer) {
if (event.getRating().getCount() > 0) {
pending.add(new DerivedRatingWrapper(new OrganizerDerivedRating(userKey)));
} else {
processed.add(new DerivedRatingWrapper(new OrganizerDerivedRating(userKey)));
}
}
} else {
if (isOrganizer) {
if (!event.getRating().equals(derivedRating.getOrganizerRating().accumulatedRating)) {
processed.remove(derivedRating);
pending.add(derivedRating);
}
} else {
processed.remove(derivedRating);
if (derivedRating.getOrganizerRating().accumulatedRating.getCount() > 0) {
pending.add(derivedRating);
}
}
}
queueProcessingTask(event, pendingQueueWasEmpty);
}
private static DerivedRatingWrapper tryFindOrganizerDerivedRating(
List<DerivedRatingWrapper> list, Key<User> organizerKey) {
return Iterables.tryFind(list, organizerPredicate(organizerKey)).orNull();
}
public static Predicate<DerivedRatingWrapper> organizerPredicate(
final Key<User> organizerKey) {
return new Predicate<DerivedRatingWrapper>() {
@Override
public boolean apply(@Nullable DerivedRatingWrapper input) {
if (input.getOrganizerRating() != null) {
return KeyWrapper.toKey(input.getOrganizerRating().organizer).equals(organizerKey);
} else {
return false;
}
}
};
}
public void processRatingUpdate(Event event) {
boolean pendingQueueWasEmpty = pending.isEmpty();
pending.addAll(processed);
processed.clear();
queueProcessingTask(event, pendingQueueWasEmpty);
}
private void queueProcessingTask(Event event, boolean pendingQueueWasEmpty) {
if (pendingQueueWasEmpty && !pending.isEmpty()) {
ProcessRatingsServlet.enqueueTask(event);
}
}
public void processPendingRating(Event event) {
DerivedRatingWrapper pendingRating = pending.remove(0);
DerivedRatingWrapper processedRating = pendingRating.processPendingRating(event);
if (processedRating != null) {
processed.add(processedRating);
}
}
public boolean hasPendingRatings() {
return !pending.isEmpty();
}
private interface DerivedRating {
@Nullable
public DerivedRatingWrapper processPendingRating(Event event);
}
/*
* This class works around the objectify limitation that embedded classes can not be
* polymorphic.
*/
@Data
@Embed
@NoArgsConstructor
private static class DerivedRatingWrapper implements DerivedRating {
private OrganizerDerivedRating organizerRating = new OrganizerDerivedRating();
private OrganizationDerivedRating organizationRating = new OrganizationDerivedRating();
public DerivedRatingWrapper(OrganizerDerivedRating organizerRating) {
this.organizerRating = organizerRating;
}
public DerivedRatingWrapper(OrganizationDerivedRating organizationRating) {
this.organizationRating = organizationRating;
}
public OrganizerDerivedRating getOrganizerRating() {
return organizerRating.isNull() ? null : organizerRating;
}
public OrganizationDerivedRating getOrganizationRating() {
return organizationRating.isNull() ? null : organizationRating;
}
@Override
public DerivedRatingWrapper processPendingRating(Event event) {
if (!organizerRating.isNull()) {
return organizerRating.processPendingRating(event);
} else {
return organizationRating.processPendingRating(event);
}
}
}
@Data
@Embed
@NoArgsConstructor
public static class OrganizerDerivedRating implements DerivedRating {
NullableKeyWrapper<User> organizer = NullableKeyWrapper.create();
AggregateRating accumulatedRating = AggregateRating.create();
public OrganizerDerivedRating(Key<User> organizerKey) {
this(organizerKey, null);
}
public OrganizerDerivedRating(Key<User> organizerKey,
@Nullable AggregateRating ratingToCopy) {
this.organizer = NullableKeyWrapper.create(organizerKey);
accumulatedRating = AggregateRating.create(ratingToCopy);
}
@XmlTransient
public boolean isNull() {
return organizer.isNull();
}
@Override
public DerivedRatingWrapper processPendingRating(Event event) {
Key<User> userKey = KeyWrapper.toKey(organizer);
User user = BaseDao.load(userKey);
if (user == null) {
// Nothing to do. User no longer exists.
return null;
}
// Delete the old rating.
user.getEventOrganizerRating().deleteAggregateRating(accumulatedRating);
// Add the new rating.
DerivedRatingWrapper processedRating = null;
EventParticipant eventParticipant = event.tryFindParticipant(userKey);
if ((eventParticipant != null) &&
(eventParticipant.getType() == ParticipantType.ORGANIZER)) {
user.getEventOrganizerRating().addAggregateRating(event.getRating());
processedRating = new DerivedRatingWrapper(
new OrganizerDerivedRating(userKey, event.getRating()));
}
BaseDao.partialUpdate(user);
return processedRating;
}
}
@Data
@Embed
@NoArgsConstructor
public static class OrganizationDerivedRating implements DerivedRating {
NullableKeyWrapper<Organization> organization = NullableKeyWrapper.create();
AggregateRating accumulatedRating = AggregateRating.create();
public OrganizationDerivedRating(Key<Organization> organizerKey) {
this(organizerKey, null);
}
private OrganizationDerivedRating(Key<Organization> organizerKey,
@Nullable AggregateRating ratingToCopy) {
this.organization = NullableKeyWrapper.create(organizerKey);
accumulatedRating = AggregateRating.create(ratingToCopy);
}
@XmlTransient
public boolean isNull() {
return organization.isNull();
}
@Override
public DerivedRatingWrapper processPendingRating(Event event) {
Key<Organization> orgKey = KeyWrapper.toKey(organization);
Organization org = BaseDao.load(orgKey);
if (org == null) {
// Nothing to do. Org no longer exists.
return null;
}
// Delete the old rating.
org.getEventRating().deleteAggregateRating(accumulatedRating);
// Add the new rating.
org.getEventRating().addAggregateRating(event.getRating());
BaseDao.partialUpdate(org);
return new DerivedRatingWrapper(
new OrganizationDerivedRating(orgKey, event.getRating()));
}
}
}
public static void processDerivedRatings(Key<Event> eventKey) {
ProcessDerivedRatingsTxn ratingsTxn;
do {
ratingsTxn = new ProcessDerivedRatingsTxn(eventKey);
ofy().transact(ratingsTxn);
} while (ratingsTxn.isWorkPending());
}
@Data
@EqualsAndHashCode(callSuper=false)
public static class ProcessDerivedRatingsTxn extends VoidWork {
private final Key<Event> eventKey;
private boolean workPending;
public void vrun() {
Event event = BaseDao.load(eventKey);
if ((event == null) || !event.hasPendingRatings()) {
// The event may no longer exist or there may be no work pending.
return;
}
event.processPendingRating();
workPending = event.hasPendingRatings();
BaseDao.partialUpdate(event);
}
}
@Data
@Embed
@NoArgsConstructor
public static class CompletionTaskTracker {
// NOTE: The embedded lists are safe since CompletionTaskWrapper has been modified to avoid
// encountering the objectify serialization bug (issue #127).
List<CompletionTaskWrapper> tasksPending = Lists.newArrayList();
List<CompletionTaskWrapper> tasksProcessed = Lists.newArrayList();
public CompletionTaskTracker(Event event) {
for (EventParticipant participant : event.participants) {
if ((participant.type == ParticipantType.ORGANIZER) ||
(participant.type == ParticipantType.REGISTERED) ||
(participant.type == ParticipantType.REGISTERED_NO_SHOW)) {
tasksPending.add(
new CompletionTaskWrapper(
new ParticipantCompletionTask(KeyWrapper.toKey(participant.user))));
}
}
// Parent orgs also accrue Karma points.
List<Key<Organization>> allOrgs =
Organization.getOrgAndAncestorOrgKeys(KeyWrapper.toKey(event.organization));
for (Key<Organization> orgKey : allOrgs) {
tasksPending.add(
new CompletionTaskWrapper(
new OrganizationCompletionTask(orgKey)));
}
}
public void processParticipantMutation(Event event, EventParticipant participant,
MutationType mutationType) {
// Update org karma points. We only have to update orgs that have been processed.
List<CompletionTaskWrapper> orgCompletionTasks = findOrgCompletionTasks(tasksProcessed);
for (CompletionTaskWrapper completionTask : orgCompletionTasks) {
if (completionTask.getOrganizationTask().updateRequired(event)) {
tasksProcessed.remove(completionTask);
tasksPending.add(completionTask);
}
}
// Process participant.
Key<User> participantKey = KeyWrapper.toKey(participant.getUser());
CompletionTaskWrapper completionTask =
tryFindParticipantCompletionTask(tasksPending, participantKey);
if (completionTask != null) {
// Nothing to do, already queued.
return;
}
completionTask = tryFindParticipantCompletionTask(tasksProcessed, participantKey);
if (completionTask == null) {
// Since participant mutation post-event completion is rare, we'll always take the hit
// of updating the event.
tasksPending.add(new CompletionTaskWrapper(
new ParticipantCompletionTask(participantKey)));
} else {
tasksProcessed.remove(completionTask);
tasksPending.add(completionTask);
}
}
private void processPendingTask(Event event) {
if (tasksPending()) {
CompletionTaskWrapper pendingTask = tasksPending.remove(0);
CompletionTaskWrapper completedTask = pendingTask.processPendingTask(event);
if (completedTask != null) {
tasksProcessed.add(completedTask);
}
}
}
public boolean tasksPending() {
return tasksPending.size() > 0;
}
private static CompletionTaskWrapper tryFindParticipantCompletionTask(
List<CompletionTaskWrapper> list, Key<User> participantKey) {
CompletionTaskWrapper task =
Iterables.tryFind(list, participantPredicate(participantKey)).orNull();
return task;
}
private static Predicate<CompletionTaskWrapper> participantPredicate(
final Key<User> participantKey) {
return new Predicate<CompletionTaskWrapper>() {
@Override
public boolean apply(@Nullable CompletionTaskWrapper input) {
if (input.getParticipantTask() != null) {
return KeyWrapper.toKey(input.getParticipantTask().participant).equals(participantKey);
} else {
return false;
}
}
};
}
private List<CompletionTaskWrapper> findOrgCompletionTasks(
List<CompletionTaskWrapper> list) {
Predicate<CompletionTaskWrapper> orgPredicate = new Predicate<CompletionTaskWrapper>() {
@Override
public boolean apply(@Nullable CompletionTaskWrapper input) {
return input.getOrganizationTask() != null;
}
};
return Lists.newArrayList(Iterables.filter(list, orgPredicate));
}
private interface CompletionTask {
@Nullable
public CompletionTaskWrapper processPendingTask(Event event);
}
/*
* This class works around the objectify limitation that embedded classes can not be
* polymorphic.
*/
@Data
@Embed
@NoArgsConstructor
@VisibleForTesting
static class CompletionTaskWrapper implements CompletionTask {
// Instantiate each object to workaround objectify serialization bug (issue #127).
private ParticipantCompletionTask participantTask = new ParticipantCompletionTask();
private OrganizationCompletionTask organizationTask = new OrganizationCompletionTask();
public CompletionTaskWrapper(ParticipantCompletionTask participantTask) {
this.participantTask = participantTask;
}
public CompletionTaskWrapper(OrganizationCompletionTask organizationTask) {
this.organizationTask = organizationTask;
}
@Override
public CompletionTaskWrapper processPendingTask(Event event) {
if (getParticipantTask() != null) {
return participantTask.processPendingTask(event);
} else {
return organizationTask.processPendingTask(event);
}
}
public ParticipantCompletionTask getParticipantTask() {
return participantTask.isNull() ? null : participantTask;
}
public OrganizationCompletionTask getOrganizationTask() {
return organizationTask.isNull() ? null : organizationTask;
}
}
@Data
@Embed
@NoArgsConstructor
@VisibleForTesting
static class ParticipantCompletionTask implements CompletionTask {
private NullableKeyWrapper<User> participant = NullableKeyWrapper.create();
private int karmaPointsAssigned;
public ParticipantCompletionTask(Key<User> participantKey) {
this(participantKey, 0);
}
public ParticipantCompletionTask(Key<User> participantKey, int karmaPointsAssigned) {
this.participant = NullableKeyWrapper.create(participantKey);
this.karmaPointsAssigned = karmaPointsAssigned;
}
@XmlTransient
public boolean isNull() {
return participant.isNull();
}
@Override
public CompletionTaskWrapper processPendingTask(Event event) {
Key<User> participantKey = KeyWrapper.toKey(participant);
User participant = BaseDao.load(participantKey);
if (participant == null) {
// Nothing to do. User no longer exists.
return null;
}
// Delete the previously assigned karma points and attendance history.
participant.setKarmaPoints(participant.getKarmaPoints() - karmaPointsAssigned);
participant.removeFromEventAttendanceHistory(Key.create(event));
// Assign the new karma points and attendance history if the participant is still part
// of the event.
CompletionTaskWrapper completedTask = null;
EventParticipant eventParticipant = event.tryFindParticipant(participantKey);
if (eventParticipant != null) {
if ((eventParticipant.type == ParticipantType.ORGANIZER) ||
(eventParticipant.type == ParticipantType.REGISTERED)) {
participant.setKarmaPoints(participant.getKarmaPoints() + event.karmaPoints);
participant.addToAttendanceHistory(new AttendanceRecord(event, true));
completedTask = new CompletionTaskWrapper(
new ParticipantCompletionTask(participantKey, event.karmaPoints));
} else if (eventParticipant.type == ParticipantType.REGISTERED_NO_SHOW) {
participant.addToAttendanceHistory(new AttendanceRecord(event, false));
completedTask = new CompletionTaskWrapper(
new ParticipantCompletionTask(participantKey));
}
}
BaseDao.partialUpdate(participant);
return completedTask;
}
}
@Data
@Embed
@NoArgsConstructor
@VisibleForTesting
static class OrganizationCompletionTask implements CompletionTask {
private NullableKeyWrapper<Organization> organization = NullableKeyWrapper.create();
private int karmaPointsAssigned;
public OrganizationCompletionTask(Key<Organization> orgKey) {
this(orgKey, 0);
}
private OrganizationCompletionTask(Key<Organization> orgKey, int karmaPointsAssigned) {
this.organization = NullableKeyWrapper.create(orgKey);
this.karmaPointsAssigned = karmaPointsAssigned;
}
@XmlTransient
public boolean isNull() {
return organization.isNull();
}
@Override
public CompletionTaskWrapper processPendingTask(Event event) {
Key<Organization> orgKey = KeyWrapper.toKey(organization);
Organization org = BaseDao.load(orgKey);
if (org == null) {
// Nothing to do. Org no longer exists.
return null;
}
org.setKarmaPoints(
org.getKarmaPoints() + computeImpactKarmaPoints(event) - karmaPointsAssigned);
BaseDao.partialUpdate(org);
return new CompletionTaskWrapper(
new OrganizationCompletionTask(orgKey, computeImpactKarmaPoints(event)));
}
public boolean updateRequired(Event event) {
return computeImpactKarmaPoints(event) != karmaPointsAssigned;
}
private int computeImpactKarmaPoints(Event event) {
return event.karmaPoints * event.getNumAttending();
}
}
}
public static void processEventCompletionTasks(Key<Event> eventKey) {
ProcessEventCompletionTasksTxn completionTasksTxn;
do {
completionTasksTxn = new ProcessEventCompletionTasksTxn(eventKey);
ofy().transact(completionTasksTxn);
} while (completionTasksTxn.isWorkPending());
}
@Data
@EqualsAndHashCode(callSuper=false)
private static class ProcessEventCompletionTasksTxn extends VoidWork {
private final Key<Event> eventKey;
private boolean workPending;
public void vrun() {
Event event = BaseDao.load(eventKey);
if ((event == null) || event.completionProcessed) {
return;
}
event.processCompletionTasks();
workPending = !event.completionProcessed;
BaseDao.partialUpdate(event);
}
}
}
| src/main/java/org/karmaexchange/dao/Event.java | package org.karmaexchange.dao;
import static java.lang.String.format;
import static org.karmaexchange.util.OfyService.ofy;
import static org.karmaexchange.util.UserService.getCurrentUserKey;
import static com.google.common.base.CharMatcher.WHITESPACE;
import static com.google.common.base.Preconditions.checkState;
import java.util.Collection;
import java.util.Date;
import java.util.EnumSet;
import java.util.Iterator;
import java.util.List;
import javax.annotation.Nullable;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import org.karmaexchange.dao.Organization.Role;
import org.karmaexchange.resources.msg.ErrorResponseMsg;
import org.karmaexchange.resources.msg.ErrorResponseMsg.ErrorInfo;
import org.karmaexchange.resources.msg.ValidationErrorInfo;
import org.karmaexchange.resources.msg.ValidationErrorInfo.ValidationError;
import org.karmaexchange.resources.msg.ValidationErrorInfo.ValidationErrorType;
import org.karmaexchange.task.ProcessRatingsServlet;
import org.karmaexchange.util.BoundedHashSet;
import org.karmaexchange.util.SearchUtil;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.ToString;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.googlecode.objectify.Key;
import com.googlecode.objectify.VoidWork;
import com.googlecode.objectify.annotation.Embed;
import com.googlecode.objectify.annotation.Entity;
import com.googlecode.objectify.annotation.Ignore;
import com.googlecode.objectify.annotation.Index;
// TODO(avaliani):
// - Fix EventSearchView for images once we revamp it.
@XmlRootElement
@Entity
@Data
@EqualsAndHashCode(callSuper=true)
@ToString(callSuper=true)
public final class Event extends IdBaseDao<Event> {
/*
* DESIGN DETAILS
*
* Event permissions
* -----------------
* The current permissions scheme is that there is one organization for each event. And that any
* organizer or admin for the organization can edit the event. This simple model handles the
* 99% usage scenario.
*/
public static final int MAX_EVENT_KARMA_POINTS = 500;
public static final int MAX_CACHED_PARTICIPANT_IMAGES = 10;
/* Each event search token results in an index write. Put a reasonable limit on it. */
public static final int MAX_SEARCH_TOKENS = 100;
/*
* TODO(avaliani):
* - look at volunteer match schema
* - compare this to Meetup, OneBrick, Golden Gate athletic club, etc.
*/
private String title;
private String description;
private String specialInstructions; // See flash volunteer.
@Index
private List<KeyWrapper<CauseType>> causes = Lists.newArrayList();
private Location location;
@Index
private Date startTime;
@Index
private Date endTime;
@Ignore
private Status status;
private AlbumRef album;
// private Image primaryImage;
// BUG: This embedded list is not safe since Image has embedded objects that can be
// optionally null. See objectify serialization bug (issue #127).
// TODO(avaliani): fix this embedded list.
// private List<Image> allImages = Lists.newArrayList();
@Index
private List<KeyWrapper<Skill>> skillsPreferred = Lists.newArrayList();
@Index
private List<KeyWrapper<Skill>> skillsRequired = Lists.newArrayList();
// TODO(avaliani): Organizations can co-host events.
@Index
private KeyWrapper<Organization> organization;
private List<OrganizationNamedKeyWrapper> associatedOrganizations = Lists.newArrayList();
// Can not be explicitly set. Automatically managed.
@Ignore
private List<KeyWrapper<User>> organizers = Lists.newArrayList();
// Can not be explicitly set. Automatically managed.
@Ignore
private RegistrationInfo registrationInfo;
// The maxRegistration limit only applies to participants. The limit does not include organizers.
private int maxRegistrations;
// Can not be explicitly set. Automatically managed.
@Ignore
private List<KeyWrapper<User>> registeredUsers = Lists.newArrayList();
// Can not be explicitly set. Automatically managed.
@Ignore
private List<KeyWrapper<User>> waitListedUsers = Lists.newArrayList();
// NOTE: Embedded list is safe since EventParticipant has embedded objects that are always
// non-null.
private List<EventParticipant> participants = Lists.newArrayList();
// We need a consolidated list because pagination does not support OR queries.
// NOTE: We can try adding a conditional index parameter to EventParticipant in the future.
// Need to make sure that there are no objectify serialization / deserialization bugs with
// that model.
@Index
private List<KeyWrapper<User>> indexedParticipants = Lists.newArrayList();
// Can not be set. Automatically managed. Only includes organizers and registered users. Wait
// listed users images are skipped.
// NOTE: Embedded list is safe since ParticipantImage has embedded objects that are always
// non-null.
private List<ParticipantImage> cachedParticipantImages = Lists.newArrayList();
private IndexedAggregateRating rating;
private DerivedRatingTracker derivedRatings;
/**
* The number of karma points earned by participating in the event. This is derived from the
* start and end time.
*/
@Index
private int karmaPoints;
@Index
private List<String> searchableTokens;
@Index
private boolean completionProcessed;
private CompletionTaskTracker completionTasks;
/*
* If this is false and the event is complete then the organizer should be asked to update
* the attendance info and write an event thank you note.
*/
private boolean organizerProcessedCompletion;
private List<SuitableForType> suitableForTypes = Lists.newArrayList();
public enum RegistrationInfo {
ORGANIZER,
REGISTERED,
REGISTERED_NO_SHOW,
WAIT_LISTED,
CAN_REGISTER,
CAN_WAIT_LIST,
FULL
}
public enum Status {
UPCOMING,
IN_PROGRESS,
COMPLETED
}
public enum ParticipantType {
ORGANIZER,
REGISTERED,
REGISTERED_NO_SHOW,
WAIT_LISTED
}
private enum MutationType {
INSERT,
UPDATE,
DELETE
}
public void setOrganizers(List<KeyWrapper<User>> ignored) {
// No-op it.
}
public void setRegisteredUsers(List<KeyWrapper<User>> ignored) {
// No-op it.
}
public void setWaitListedUsers(List<KeyWrapper<User>> ignored) {
// No-op it.
}
public void setCachedParticipantImages(List<ParticipantImage> ignored) {
// No-op it.
}
public void setRegistrationInfo(RegistrationInfo ignored) {
// No-op it.
}
public static String getParticipantPropertyName() {
return "indexedParticipants.key";
}
@Override
protected void preProcessInsert() {
super.preProcessInsert();
if (title != null) {
title = WHITESPACE.trimFrom(title);
}
for (EventParticipant participant : participants) {
if (participant.type == ParticipantType.REGISTERED_NO_SHOW) {
throw ErrorResponseMsg.createException(
"only events that have completed can have no show participants",
ErrorInfo.Type.BAD_REQUEST);
}
}
initParticipantLists();
// Add the current user as an organizer if there are no organizers registered.
if (organizers.isEmpty()) {
Iterables.removeIf(participants, EventParticipant.userPredicate(getCurrentUserKey()));
participants.add(EventParticipant.create(getCurrentUserKey(), ParticipantType.ORGANIZER));
initParticipantLists();
}
processParticipants();
processSuitableFor();
validateEvent();
initKarmaPoints();
rating = IndexedAggregateRating.create();
initDerivedRatings();
// The list of associated organizations is consumed by initSearchableTokens(), so the
// associated organizations must be set prior to invoking initSearchableTokens().
initAssociatedOrganizations();
initSearchableTokens();
completionProcessed = false;
completionTasks = null;
}
@Override
protected void processUpdate(Event prevObj) {
super.processUpdate(prevObj);
if (title != null) {
title = WHITESPACE.trimFrom(title);
}
initKarmaPoints();
// Rating is independently and transactionally updated.
rating = prevObj.rating;
derivedRatings = prevObj.derivedRatings;
// Participants is independently and transactionally updated.
participants = Lists.newArrayList(prevObj.participants);
processParticipants();
processSuitableFor();
validateEvent();
// The list of associated organizations is consumed by initSearchableTokens(), so the
// associated organizations must be set prior to invoking initSearchableTokens().
associatedOrganizations = prevObj.associatedOrganizations;
initSearchableTokens();
completionProcessed = prevObj.completionProcessed;
completionTasks = prevObj.completionTasks;
// Do event validation that is specific to event updates.
validateEventUpdate(prevObj);
}
private void processParticipantMutation(EventParticipant updatedParticipant,
MutationType mutationType) {
processParticipantMutation(ImmutableList.of(updatedParticipant), mutationType);
}
private void processParticipantMutation(Collection<EventParticipant> mutatedParticipants,
MutationType mutationType) {
processParticipants();
for (EventParticipant participant : mutatedParticipants) {
derivedRatings.processParticipantMutation(this, participant, mutationType);
if (completionTasks != null) {
completionTasks.processParticipantMutation(this, participant, mutationType);
updateCompletionProcessed();
}
}
validateEvent();
}
private void processRatingUpdate() {
derivedRatings.processRatingUpdate(this);
}
private void processPendingRating() {
derivedRatings.processPendingRating(this);
}
private boolean hasPendingRatings() {
return derivedRatings.hasPendingRatings();
}
private void processCompletionTasks() {
// Note that we don't check the time to see if it's okay to process completion tasks.
// Instead we trust that the caller has checked the time. This handles cases where there
// is clock skew and the completion task was aborted and restarted on a different machine.
if (completionTasks == null) {
// This is the first time completion tasks are being processed. On the first pass the
// event object state must be cleaned up.
removeWaitListedUsers();
// After the state is cleaned up we process the remaining event completion tasks.
completionTasks = new CompletionTaskTracker(this);
}
completionTasks.processPendingTask(this);
updateCompletionProcessed();
}
private void updateCompletionProcessed() {
completionProcessed = !completionTasks.tasksPending();
}
private void removeWaitListedUsers() {
List<EventParticipant> participantsRemoved = Lists.newArrayList();
Iterator<EventParticipant> participantIter = participants.iterator();
while (participantIter.hasNext()) {
EventParticipant participant = participantIter.next();
if (participant.getType() == ParticipantType.WAIT_LISTED) {
participantIter.remove();
participantsRemoved.add(participant);
}
}
processParticipantMutation(participantsRemoved, MutationType.DELETE);
}
private void processParticipants() {
initParticipantLists();
processWaitList();
updateCachedParticipantImages();
}
private void processSuitableFor() {
if (!suitableForTypes.isEmpty()) {
// Eliminate any duplicates.
EnumSet<SuitableForType> suitableForSet = EnumSet.copyOf(suitableForTypes);
suitableForTypes = Lists.newArrayList(suitableForSet);
}
}
@Override
protected void processLoad() {
// initParticipantLists() must be called prior to processLoad so that updatePermissions can
// use the participant lists to calculate the permissions.
initParticipantLists();
super.processLoad();
initStatus();
updateRegistrationInfo();
}
private void initStatus() {
status = computeStatus(this);
}
private static Status computeStatus(Event event) {
if (event.completionTasks != null) {
return Status.COMPLETED;
}
Date now = new Date();
if (now.before(event.startTime)) {
return Status.UPCOMING;
} else if (now.before(event.endTime)) {
return Status.IN_PROGRESS;
} else {
return Status.COMPLETED;
}
}
private void initKarmaPoints() {
long eventDurationMins = (endTime.getTime() - startTime.getTime()) / (1000 * 60);
karmaPoints = (int) Math.min(eventDurationMins, MAX_EVENT_KARMA_POINTS);
}
private void initDerivedRatings() {
derivedRatings = new DerivedRatingTracker(this);
}
private void initAssociatedOrganizations() {
associatedOrganizations = Lists.newArrayList();
for (Organization org : Organization.getOrgAndAncestorOrgs(KeyWrapper.toKey(organization))) {
associatedOrganizations.add(new OrganizationNamedKeyWrapper(org));
}
}
private void initSearchableTokens() {
BoundedHashSet<String> searchableTokensSet = BoundedHashSet.create(MAX_SEARCH_TOKENS);
Key<Organization> primaryOrgKey = KeyWrapper.toKey(organization);
// Throw an exception if we can't add the primary org token to the searchableTokensSet.
searchableTokensSet.add(
SearchUtil.ReservedToken.PRIMARY_ORG.create(
Organization.getSearchTokenSuffix(primaryOrgKey)));
for (OrganizationNamedKeyWrapper orgKeyWrapper : associatedOrganizations) {
// Throw an exception if we can't add the org token to the searchableTokensSet.
searchableTokensSet.add(
SearchUtil.ReservedToken.ORG.create(
Organization.getSearchTokenSuffix(KeyWrapper.toKey(orgKeyWrapper))));
}
for (SuitableForType suitableForType : suitableForTypes) {
searchableTokensSet.addIfSpace(suitableForType.getTag());
}
// The lowest priority tokens should be added to the end of the searchableContent. Once the
// token limit is hit the remaining tokens will be discarded.
StringBuilder searchableContent = new StringBuilder();
searchableContent.append(title);
searchableContent.append(' ');
for (KeyWrapper<CauseType> causeKeyWrapper : causes) {
Key<CauseType> causeKey = KeyWrapper.toKey(causeKeyWrapper);
// We add causes both as tags and text strings to be parsed since keywords like
// homeless and animals are good for non-tag based keyword search.
searchableContent.append(CauseType.getCauseTypeAsString(causeKey));
searchableContent.append(' ');
searchableTokensSet.addIfSpace(CauseType.getTag(causeKey));
}
if ((location != null) && (location.getTitle() != null)) {
searchableContent.append(location.getTitle());
searchableContent.append(' ');
}
searchableContent.append(description);
SearchUtil.addSearchableTokens(searchableTokensSet, searchableContent.toString(),
EnumSet.of(SearchUtil.ParseOptions.EXCLUDE_RESERVED_TOKENS));
searchableTokens = Lists.newArrayList(searchableTokensSet);
}
private void initParticipantLists() {
organizers = Lists.newArrayList();
registeredUsers = Lists.newArrayList();
waitListedUsers = Lists.newArrayList();;
indexedParticipants = Lists.newArrayList();;
for (EventParticipant participant : participants) {
switch (participant.getType()) {
case ORGANIZER:
organizers.add(participant.getUser());
indexedParticipants.add(participant.getUser());
break;
case REGISTERED:
registeredUsers.add(participant.getUser());
indexedParticipants.add(participant.getUser());
break;
case REGISTERED_NO_SHOW:
// Do nothing.
break;
case WAIT_LISTED:
waitListedUsers.add(participant.getUser());
indexedParticipants.add(participant.getUser());
break;
default:
checkState(false, "unknown participant type: " + participant.getType());
}
}
}
@Nullable
private EventParticipant tryFindParticipant(Key<User> userKey) {
return Iterables.tryFind(participants, EventParticipant.userPredicate(userKey)).orNull();
}
public List<KeyWrapper<User>> getParticipants(ParticipantType participantType) {
List<KeyWrapper<User>> participantSubset = Lists.newArrayList();
for (EventParticipant participant : participants) {
if (participant.type == participantType) {
participantSubset.add(participant.user);
}
}
return participantSubset;
}
private void validateEvent() {
List<ValidationError> validationErrors = Lists.newArrayList();
if ((null == title) || title.isEmpty()) {
validationErrors.add(new ResourceValidationError(
this, ValidationErrorType.RESOURCE_FIELD_VALUE_REQUIRED, "title"));
}
// TODO(avaliani): make sure the description has a minimum length. Avoiding this for now
// since we don't have auto event creation.
if (null == startTime) {
validationErrors.add(new ResourceValidationError(
this, ValidationErrorType.RESOURCE_FIELD_VALUE_REQUIRED, "startTime"));
}
if (null == endTime) {
validationErrors.add(new ResourceValidationError(
this, ValidationErrorType.RESOURCE_FIELD_VALUE_REQUIRED, "endTime"));
}
if ((startTime != null) && (endTime != null) && !startTime.before(endTime)) {
validationErrors.add(new MultiFieldResourceValidationError(
this, ValidationErrorType.RESOURCE_FIELD_VALUE_MUST_BE_GT_SPECIFIED_FIELD,
"endTime", "startTime"));
}
if (maxRegistrations < 1) {
validationErrors.add(new LimitResourceValidationError(
this, ValidationErrorType.RESOURCE_FIELD_VALUE_MUST_BE_GTEQ_LIMIT,
"maxRegistrations", 1));
}
if (organization == null) {
validationErrors.add(new ResourceValidationError(
this, ValidationErrorType.RESOURCE_FIELD_VALUE_REQUIRED, "organization"));
} else {
if (organizers.isEmpty()) {
validationErrors.add(new ResourceValidationError(
this, ValidationErrorType.RESOURCE_FIELD_VALUE_REQUIRED, "organizers"));
List<User> organizerEntities =
BaseDao.load(KeyWrapper.toKeys(organizers), ofy().transactionless());
for (User organizer : organizerEntities) {
if (!organizer.hasOrgMembership(KeyWrapper.toKey(organization), Role.ORGANIZER)) {
validationErrors.add(new ListValueValidationError(
this, ValidationErrorType.RESOURCE_FIELD_LIST_VALUE_INVALID_PERMISSIONS, "organizers",
organizer.getKey()));
}
}
}
}
if (!validationErrors.isEmpty()) {
throw ValidationErrorInfo.createException(validationErrors);
}
}
private void validateEventUpdate(Event prevObj) {
List<ValidationError> validationErrors = Lists.newArrayList();
// Check the prev object's state since some of the fields of the current object can be
// manipulated in an update.
if (computeStatus(prevObj) == Status.COMPLETED) {
if (!startTime.equals(prevObj.startTime)) {
validationErrors.add(new ResourceValidationError(
this, ValidationErrorType.RESOURCE_FIELD_VALUE_UNMODIFIABLE, "startTime"));
}
if (!endTime.equals(prevObj.endTime)) {
validationErrors.add(new ResourceValidationError(
this, ValidationErrorType.RESOURCE_FIELD_VALUE_UNMODIFIABLE, "endTime"));
}
// To simplify completion task processing, we don't allow organizations to be modifiable
// after event completion.
if (!organization.equals(prevObj.organization)) {
validationErrors.add(new ResourceValidationError(
this, ValidationErrorType.RESOURCE_FIELD_VALUE_UNMODIFIABLE, "organization"));
}
}
if (!validationErrors.isEmpty()) {
throw ValidationErrorInfo.createException(validationErrors);
}
}
private void processWaitList() {
if ((registeredUsers.size() < maxRegistrations) &&
!waitListedUsers.isEmpty()) {
int numSpots = maxRegistrations - registeredUsers.size();
List<KeyWrapper<User>> usersToRegister =
waitListedUsers.subList(0, Math.min(numSpots, waitListedUsers.size()));
for (KeyWrapper<User> userToRegister : usersToRegister) {
EventParticipant participant = Iterables.find(participants,
EventParticipant.userPredicate(KeyWrapper.toKey(userToRegister)));
participant.setType(ParticipantType.REGISTERED);
}
initParticipantLists();
}
}
private void updateCachedParticipantImages() {
// Prune any deleted or wait listed participants.
Iterator<ParticipantImage> cachedImageIter = cachedParticipantImages.iterator();
while (cachedImageIter.hasNext()) {
ParticipantImage cachedImage = cachedImageIter.next();
Key<User> userKey = KeyWrapper.toKey(cachedImage.getParticipant());
EventParticipant participant = tryFindParticipant(userKey);
if ((participant == null) ||
((participant.getType() != ParticipantType.ORGANIZER) &&
(participant.getType() != ParticipantType.REGISTERED))) {
cachedImageIter.remove();
}
}
// Add images if there is room.
int numParticipantImagesToCache = getNumAttending() - cachedParticipantImages.size();
numParticipantImagesToCache = Math.min(numParticipantImagesToCache,
MAX_CACHED_PARTICIPANT_IMAGES - cachedParticipantImages.size());
if (numParticipantImagesToCache > 0) {
List<Key<User>> usersToFetch = Lists.newArrayList();
for (KeyWrapper<User> participantKey :
getAttendingParticipants(MAX_CACHED_PARTICIPANT_IMAGES)) {
if (!Iterables.any(cachedParticipantImages,
ParticipantImage.userPredicate(participantKey))) {
usersToFetch.add(KeyWrapper.toKey(participantKey));
numParticipantImagesToCache--;
if (numParticipantImagesToCache == 0) {
break;
}
}
}
List<User> participantsToCache = BaseDao.load(usersToFetch, ofy().transactionless());
for (User participantToCache : participantsToCache) {
cachedParticipantImages.add(ParticipantImage.create(participantToCache));
}
}
}
private List<KeyWrapper<User>> getAttendingParticipants(int limit) {
List<KeyWrapper<User>> attendingParticipants = Lists.newArrayList();
for (KeyWrapper<User> organizer : organizers) {
attendingParticipants.add(organizer);
limit--;
if (limit == 0) {
break;
}
}
if (limit > 0) {
for (KeyWrapper<User> registeredUser : registeredUsers) {
attendingParticipants.add(registeredUser);
limit--;
if (limit == 0) {
break;
}
}
}
return attendingParticipants;
}
public int getNumAttending() {
return organizers.size() + registeredUsers.size();
}
public void setNumAttending(int ignore) {
// No-op.
}
private void updateRegistrationInfo() {
EventParticipant participant = tryFindParticipant(getCurrentUserKey());
if (participant == null) {
if (registeredUsers.size() < maxRegistrations) {
registrationInfo = RegistrationInfo.CAN_REGISTER;
} else {
registrationInfo = RegistrationInfo.CAN_WAIT_LIST;
}
// } else if (waitListedUsers.size() < maxWaitingList) {
// registrationInfo = RegistrationInfo.CAN_WAIT_LIST;
// } else {
// registrationInfo = RegistrationInfo.FULL;
// }
} else {
if (participant.type == ParticipantType.ORGANIZER) {
registrationInfo = RegistrationInfo.ORGANIZER;
} else if (participant.type == ParticipantType.REGISTERED) {
registrationInfo = RegistrationInfo.REGISTERED;
} else if (participant.type == ParticipantType.REGISTERED_NO_SHOW) {
registrationInfo = RegistrationInfo.REGISTERED_NO_SHOW;
} else {
checkState(participant.type == ParticipantType.WAIT_LISTED,
"unknown participant type: " + participant.type);
registrationInfo = RegistrationInfo.WAIT_LISTED;
}
}
}
// TODO(avaliani): Always calculating eval permission is expensive in the long run. It results
// in additional loads even for read operations. Since we're fetching the current user
// transactionless the user should be saved in the session cache, so the overhead is not
// terrible. But this should be eliminated if possible.
@Override
protected Permission evalPermission() {
User currentUser = BaseDao.load(getCurrentUserKey(), ofy().transactionless());
if (currentUser.hasOrgMembership(KeyWrapper.toKey(organization),
Organization.Role.ORGANIZER)) {
return Permission.ALL;
}
return Permission.READ;
}
@Data
@EqualsAndHashCode(callSuper=false)
public static class UpsertParticipantTxn extends VoidWork {
private final Key<Event> eventKey;
private final Key<User> userToUpsertKey;
private final ParticipantType participantType;
public void vrun() {
Event event = BaseDao.load(eventKey);
if (event == null) {
throw ErrorResponseMsg.createException("event not found",
ErrorInfo.Type.BAD_REQUEST);
}
EventParticipant participantToUpsert = event.tryFindParticipant(userToUpsertKey);
// Users that can not edit the event are restricted to only adding themselves to the
// registered list or the waiting list. Additionally, users with edit permissions
// bypass all event registration and waiting list limits.
if (!event.permission.canEdit()) {
if (!userToUpsertKey.equals(getCurrentUserKey())) {
throw ErrorResponseMsg.createException(
"only organizers can add any participant to the event",
ErrorInfo.Type.BAD_REQUEST);
}
if (participantType == ParticipantType.ORGANIZER) {
throw ErrorResponseMsg.createException(
"insufficent priveleges to make the current user an organizer of the event",
ErrorInfo.Type.BAD_REQUEST);
}
if (participantType == ParticipantType.REGISTERED_NO_SHOW) {
throw ErrorResponseMsg.createException(
"insufficent priveleges to change the state of the current user to REGISTERED_NO_SHOW",
ErrorInfo.Type.BAD_REQUEST);
}
if ((participantToUpsert != null) && (participantToUpsert.getType() == participantType)) {
// Nothing to do.
return;
}
if (participantType == ParticipantType.REGISTERED) {
if (event.registeredUsers.size() >= event.maxRegistrations) {
throw ErrorResponseMsg.createException(
"the event has reached the max registration limit",
ErrorInfo.Type.LIMIT_REACHED);
}
} else {
checkState(participantType == ParticipantType.WAIT_LISTED);
// if (event.waitListedUsers.size() >= event.maxWaitingList) {
// throw ErrorResponseMsg.createException(
// "the event has reached the max waiting list limit",
// ErrorInfo.Type.LIMIT_REACHED);
// }
}
}
if (event.status == Status.COMPLETED) {
if (participantType == ParticipantType.ORGANIZER) {
throw ErrorResponseMsg.createException(
"organizers can not be added after event completion",
ErrorInfo.Type.BAD_REQUEST);
}
if (participantType == ParticipantType.WAIT_LISTED) {
throw ErrorResponseMsg.createException(
"wait listed users can not be added after event completion",
ErrorInfo.Type.BAD_REQUEST);
}
} else {
if (participantType == ParticipantType.REGISTERED_NO_SHOW) {
throw ErrorResponseMsg.createException(
"users can not be marked no show until the event is marked complete",
ErrorInfo.Type.BAD_REQUEST);
}
}
MutationType mutationType;
if (participantToUpsert == null) {
// TODO(avaliani): organizers should not in theory be allowed to add arbitrary users.
// However, this simplifies testing so we're going to allow it for now.
participantToUpsert = EventParticipant.create(userToUpsertKey, participantType);
event.participants.add(participantToUpsert);
mutationType = MutationType.INSERT;
} else {
ParticipantType prevParticipantType = participantToUpsert.getType();
if (participantType == prevParticipantType) {
// Nothing to do.
return;
}
if ((event.status == Status.COMPLETED) &&
(prevParticipantType == ParticipantType.ORGANIZER)) {
throw ErrorResponseMsg.createException(
"organizers can not be updated after event completion",
ErrorInfo.Type.BAD_REQUEST);
}
participantToUpsert.setType(participantType);
mutationType = MutationType.UPDATE;
}
// validateEvent() ensures that there is at least one organizer.
event.processParticipantMutation(participantToUpsert, mutationType);
BaseDao.partialUpdate(event);
}
}
@Data
@EqualsAndHashCode(callSuper=false)
public static class DeleteParticipantTxn extends VoidWork {
private final Key<Event> eventKey;
private final Key<User> userToRemoveKey;
public void vrun() {
Event event = BaseDao.load(eventKey);
if (event == null) {
throw ErrorResponseMsg.createException("event not found",
ErrorInfo.Type.BAD_REQUEST);
}
if (!event.permission.canEdit() && !userToRemoveKey.equals(getCurrentUserKey())) {
throw ErrorResponseMsg.createException(
"only organizers can remove any participant from the event",
ErrorInfo.Type.BAD_REQUEST);
}
EventParticipant participant = event.tryFindParticipant(userToRemoveKey);
if (participant != null) {
if (event.status == Status.COMPLETED) {
if (participant.getType() == ParticipantType.ORGANIZER) {
throw ErrorResponseMsg.createException(
"organizers can not be removed after event completion",
ErrorInfo.Type.BAD_REQUEST);
}
if (canWriteReview(participant)) {
Review participantReview = BaseDao.load(
Review.getKeyForUser(Key.create(event), KeyWrapper.toKey(participant.getUser())));
if (participantReview != null) {
throw ErrorResponseMsg.createException(
"users that have written a review can not be removed after event completion",
ErrorInfo.Type.BAD_REQUEST);
}
}
}
event.participants.remove(participant);
// validateEvent() ensures that there is at least one organizer.
event.processParticipantMutation(participant, MutationType.DELETE);
BaseDao.partialUpdate(event);
}
}
}
@Embed
@Data
@NoArgsConstructor
public static final class EventParticipant {
@Index
private KeyWrapper<User> user;
private ParticipantType type;
public static EventParticipant create(Key<User> user, ParticipantType type) {
return new EventParticipant(KeyWrapper.create(user), type);
}
private EventParticipant(KeyWrapper<User> user, ParticipantType type) {
this.user = user;
this.type = type;
}
public static Predicate<EventParticipant> userPredicate(final Key<User> userKey) {
return new Predicate<EventParticipant>() {
@Override
public boolean apply(@Nullable EventParticipant input) {
return KeyWrapper.toKey(input.user).equals(userKey);
}
};
}
}
public static void mutateEventReviewForCurrentUser(Key<Event> eventKey, @Nullable Review review) {
ofy().transact(new MutateEventReviewTxn(eventKey, getCurrentUserKey(), review));
}
@Data
@EqualsAndHashCode(callSuper=false)
private static class MutateEventReviewTxn extends VoidWork {
private final Key<Event> eventKey;
private final Key<User> userKey;
@Nullable
private final Review review;
public void vrun() {
Event event = BaseDao.load(eventKey);
if (event == null) {
throw ErrorResponseMsg.createException("event not found", ErrorInfo.Type.BAD_REQUEST);
}
EventParticipant participantDetails = event.tryFindParticipant(userKey);
if ((participantDetails == null) || !canWriteReview(participantDetails)) {
throw ErrorResponseMsg.createException(
"only users that participated in the event (non-organizers) can provide an event review",
ErrorInfo.Type.BAD_REQUEST);
}
if (event.status != Status.COMPLETED) {
throw ErrorResponseMsg.createException(
"only events that have completed can be reviewed", ErrorInfo.Type.BAD_REQUEST);
}
processReviewMutation(event, userKey, review);
BaseDao.partialUpdate(event);
}
}
public static void processReviewMutation(Event event, Key<User> userKey,
@Nullable Review review) {
boolean ratingMutated = false;
Key<Review> expReviewKey = Review.getKeyForUser(Key.create(event), userKey);
if (review != null) {
review.initPreUpsert(Key.create(event), userKey);
if (!Key.create(review).equals(expReviewKey)) {
throw ErrorResponseMsg.createException(
format("review key [%s] does not match expected review key [%s]",
Key.create(review).toString(), expReviewKey.toString()),
ErrorInfo.Type.BAD_REQUEST);
}
}
Review existingReview = BaseDao.load(expReviewKey);
if (existingReview != null) {
event.rating.deleteRating(existingReview.getRating());
ratingMutated = true;
}
if (review == null) {
if (existingReview != null) {
BaseDao.delete(Key.create(existingReview));
}
} else {
event.rating.addRating(review.getRating());
ratingMutated = true;
// An upsert will automatically delete the old review since the key for the new and the
// old review is the same.
BaseDao.upsert(review);
}
if (ratingMutated) {
event.processRatingUpdate();
}
}
private static boolean canWriteReview(EventParticipant participant) {
return participant.getType() == ParticipantType.REGISTERED;
}
/**
* This class updates the organizer event ratings for all organizers associated with an event.
*
* Note that all methods in this class should be invoked from within the context of a transaction.
*/
@Data
@Embed
@NoArgsConstructor
public static class DerivedRatingTracker {
// NOTE: The embedded lists are safe since DerivedRatingWrapper has been modified to avoid
// encountering the objectify serialization bug (issue #127).
List<DerivedRatingWrapper> processed = Lists.newArrayList();
List<DerivedRatingWrapper> pending = Lists.newArrayList();
public DerivedRatingTracker(Event event) {
for (EventParticipant participant : event.participants) {
if (participant.getType() == ParticipantType.ORGANIZER) {
processParticipantMutation(event, participant, MutationType.INSERT);
}
}
processed.add(new DerivedRatingWrapper(
new OrganizationDerivedRating(KeyWrapper.toKey(event.organization))));
}
public void processParticipantMutation(Event event, EventParticipant participant,
MutationType mutationType) {
processParticipantMutation(event, KeyWrapper.toKey(participant.getUser()),
((mutationType == MutationType.DELETE) ? false :
(participant.getType() == ParticipantType.ORGANIZER)));
}
private void processParticipantMutation(Event event, Key<User> userKey, boolean isOrganizer) {
boolean pendingQueueWasEmpty = pending.isEmpty();
DerivedRatingWrapper derivedRating = tryFindOrganizerDerivedRating(pending, userKey);
if (derivedRating != null) {
// Nothing to do, already queued.
return;
}
derivedRating = tryFindOrganizerDerivedRating(processed, userKey);
if (derivedRating == null) {
if (isOrganizer) {
if (event.getRating().getCount() > 0) {
pending.add(new DerivedRatingWrapper(new OrganizerDerivedRating(userKey)));
} else {
processed.add(new DerivedRatingWrapper(new OrganizerDerivedRating(userKey)));
}
}
} else {
if (isOrganizer) {
if (!event.getRating().equals(derivedRating.getOrganizerRating().accumulatedRating)) {
processed.remove(derivedRating);
pending.add(derivedRating);
}
} else {
processed.remove(derivedRating);
if (derivedRating.getOrganizerRating().accumulatedRating.getCount() > 0) {
pending.add(derivedRating);
}
}
}
queueProcessingTask(event, pendingQueueWasEmpty);
}
private static DerivedRatingWrapper tryFindOrganizerDerivedRating(
List<DerivedRatingWrapper> list, Key<User> organizerKey) {
return Iterables.tryFind(list, organizerPredicate(organizerKey)).orNull();
}
public static Predicate<DerivedRatingWrapper> organizerPredicate(
final Key<User> organizerKey) {
return new Predicate<DerivedRatingWrapper>() {
@Override
public boolean apply(@Nullable DerivedRatingWrapper input) {
if (input.getOrganizerRating() != null) {
return KeyWrapper.toKey(input.getOrganizerRating().organizer).equals(organizerKey);
} else {
return false;
}
}
};
}
public void processRatingUpdate(Event event) {
boolean pendingQueueWasEmpty = pending.isEmpty();
pending.addAll(processed);
processed.clear();
queueProcessingTask(event, pendingQueueWasEmpty);
}
private void queueProcessingTask(Event event, boolean pendingQueueWasEmpty) {
if (pendingQueueWasEmpty && !pending.isEmpty()) {
ProcessRatingsServlet.enqueueTask(event);
}
}
public void processPendingRating(Event event) {
DerivedRatingWrapper pendingRating = pending.remove(0);
DerivedRatingWrapper processedRating = pendingRating.processPendingRating(event);
if (processedRating != null) {
processed.add(processedRating);
}
}
public boolean hasPendingRatings() {
return !pending.isEmpty();
}
private interface DerivedRating {
@Nullable
public DerivedRatingWrapper processPendingRating(Event event);
}
/*
* This class works around the objectify limitation that embedded classes can not be
* polymorphic.
*/
@Data
@Embed
@NoArgsConstructor
private static class DerivedRatingWrapper implements DerivedRating {
private OrganizerDerivedRating organizerRating = new OrganizerDerivedRating();
private OrganizationDerivedRating organizationRating = new OrganizationDerivedRating();
public DerivedRatingWrapper(OrganizerDerivedRating organizerRating) {
this.organizerRating = organizerRating;
}
public DerivedRatingWrapper(OrganizationDerivedRating organizationRating) {
this.organizationRating = organizationRating;
}
public OrganizerDerivedRating getOrganizerRating() {
return organizerRating.isNull() ? null : organizerRating;
}
public OrganizationDerivedRating getOrganizationRating() {
return organizationRating.isNull() ? null : organizationRating;
}
@Override
public DerivedRatingWrapper processPendingRating(Event event) {
if (!organizerRating.isNull()) {
return organizerRating.processPendingRating(event);
} else {
return organizationRating.processPendingRating(event);
}
}
}
@Data
@Embed
@NoArgsConstructor
public static class OrganizerDerivedRating implements DerivedRating {
NullableKeyWrapper<User> organizer = NullableKeyWrapper.create();
AggregateRating accumulatedRating = AggregateRating.create();
public OrganizerDerivedRating(Key<User> organizerKey) {
this(organizerKey, null);
}
public OrganizerDerivedRating(Key<User> organizerKey,
@Nullable AggregateRating ratingToCopy) {
this.organizer = NullableKeyWrapper.create(organizerKey);
accumulatedRating = AggregateRating.create(ratingToCopy);
}
@XmlTransient
public boolean isNull() {
return organizer.isNull();
}
@Override
public DerivedRatingWrapper processPendingRating(Event event) {
Key<User> userKey = KeyWrapper.toKey(organizer);
User user = BaseDao.load(userKey);
if (user == null) {
// Nothing to do. User no longer exists.
return null;
}
// Delete the old rating.
user.getEventOrganizerRating().deleteAggregateRating(accumulatedRating);
// Add the new rating.
DerivedRatingWrapper processedRating = null;
EventParticipant eventParticipant = event.tryFindParticipant(userKey);
if ((eventParticipant != null) &&
(eventParticipant.getType() == ParticipantType.ORGANIZER)) {
user.getEventOrganizerRating().addAggregateRating(event.getRating());
processedRating = new DerivedRatingWrapper(
new OrganizerDerivedRating(userKey, event.getRating()));
}
BaseDao.partialUpdate(user);
return processedRating;
}
}
@Data
@Embed
@NoArgsConstructor
public static class OrganizationDerivedRating implements DerivedRating {
NullableKeyWrapper<Organization> organization = NullableKeyWrapper.create();
AggregateRating accumulatedRating = AggregateRating.create();
public OrganizationDerivedRating(Key<Organization> organizerKey) {
this(organizerKey, null);
}
private OrganizationDerivedRating(Key<Organization> organizerKey,
@Nullable AggregateRating ratingToCopy) {
this.organization = NullableKeyWrapper.create(organizerKey);
accumulatedRating = AggregateRating.create(ratingToCopy);
}
@XmlTransient
public boolean isNull() {
return organization.isNull();
}
@Override
public DerivedRatingWrapper processPendingRating(Event event) {
Key<Organization> orgKey = KeyWrapper.toKey(organization);
Organization org = BaseDao.load(orgKey);
if (org == null) {
// Nothing to do. Org no longer exists.
return null;
}
// Delete the old rating.
org.getEventRating().deleteAggregateRating(accumulatedRating);
// Add the new rating.
org.getEventRating().addAggregateRating(event.getRating());
BaseDao.partialUpdate(org);
return new DerivedRatingWrapper(
new OrganizationDerivedRating(orgKey, event.getRating()));
}
}
}
public static void processDerivedRatings(Key<Event> eventKey) {
ProcessDerivedRatingsTxn ratingsTxn;
do {
ratingsTxn = new ProcessDerivedRatingsTxn(eventKey);
ofy().transact(ratingsTxn);
} while (ratingsTxn.isWorkPending());
}
@Data
@EqualsAndHashCode(callSuper=false)
public static class ProcessDerivedRatingsTxn extends VoidWork {
private final Key<Event> eventKey;
private boolean workPending;
public void vrun() {
Event event = BaseDao.load(eventKey);
if ((event == null) || !event.hasPendingRatings()) {
// The event may no longer exist or there may be no work pending.
return;
}
event.processPendingRating();
workPending = event.hasPendingRatings();
BaseDao.partialUpdate(event);
}
}
@Data
@Embed
@NoArgsConstructor
public static class CompletionTaskTracker {
// NOTE: The embedded lists are safe since CompletionTaskWrapper has been modified to avoid
// encountering the objectify serialization bug (issue #127).
List<CompletionTaskWrapper> tasksPending = Lists.newArrayList();
List<CompletionTaskWrapper> tasksProcessed = Lists.newArrayList();
public CompletionTaskTracker(Event event) {
for (EventParticipant participant : event.participants) {
if ((participant.type == ParticipantType.ORGANIZER) ||
(participant.type == ParticipantType.REGISTERED) ||
(participant.type == ParticipantType.REGISTERED_NO_SHOW)) {
tasksPending.add(
new CompletionTaskWrapper(
new ParticipantCompletionTask(KeyWrapper.toKey(participant.user))));
}
}
// Parent orgs also accrue Karma points.
List<Key<Organization>> allOrgs =
Organization.getOrgAndAncestorOrgKeys(KeyWrapper.toKey(event.organization));
for (Key<Organization> orgKey : allOrgs) {
tasksPending.add(
new CompletionTaskWrapper(
new OrganizationCompletionTask(orgKey)));
}
}
public void processParticipantMutation(Event event, EventParticipant participant,
MutationType mutationType) {
Key<User> participantKey = KeyWrapper.toKey(participant.getUser());
CompletionTaskWrapper completionTask =
tryFindParticipantCompletionTask(tasksPending, participantKey);
if (completionTask != null) {
// Nothing to do, already queued.
return;
}
completionTask = tryFindParticipantCompletionTask(tasksProcessed, participantKey);
if (completionTask == null) {
// Since participant mutation post-event completion is rare, we'll always take the hit
// of updating the event.
tasksPending.add(new CompletionTaskWrapper(
new ParticipantCompletionTask(participantKey)));
} else {
tasksProcessed.remove(completionTask);
tasksPending.add(completionTask);
}
}
private void processPendingTask(Event event) {
if (tasksPending()) {
CompletionTaskWrapper pendingTask = tasksPending.remove(0);
CompletionTaskWrapper completedTask = pendingTask.processPendingTask(event);
if (completedTask != null) {
tasksProcessed.add(completedTask);
}
}
}
public boolean tasksPending() {
return tasksPending.size() > 0;
}
private static CompletionTaskWrapper tryFindParticipantCompletionTask(
List<CompletionTaskWrapper> list, Key<User> participantKey) {
CompletionTaskWrapper task =
Iterables.tryFind(list, participantPredicate(participantKey)).orNull();
return task;
}
private static Predicate<CompletionTaskWrapper> participantPredicate(
final Key<User> participantKey) {
return new Predicate<CompletionTaskWrapper>() {
@Override
public boolean apply(@Nullable CompletionTaskWrapper input) {
if (input.getParticipantTask() != null) {
return KeyWrapper.toKey(input.getParticipantTask().participant).equals(participantKey);
} else {
return false;
}
}
};
}
private interface CompletionTask {
@Nullable
public CompletionTaskWrapper processPendingTask(Event event);
}
/*
* This class works around the objectify limitation that embedded classes can not be
* polymorphic.
*/
@Data
@Embed
@NoArgsConstructor
@VisibleForTesting
static class CompletionTaskWrapper implements CompletionTask {
// Instantiate each object to workaround objectify serialization bug (issue #127).
private ParticipantCompletionTask participantTask = new ParticipantCompletionTask();
private OrganizationCompletionTask organizationTask = new OrganizationCompletionTask();
public CompletionTaskWrapper(ParticipantCompletionTask participantTask) {
this.participantTask = participantTask;
}
public CompletionTaskWrapper(OrganizationCompletionTask organizationTask) {
this.organizationTask = organizationTask;
}
@Override
public CompletionTaskWrapper processPendingTask(Event event) {
if (getParticipantTask() != null) {
return participantTask.processPendingTask(event);
} else {
return organizationTask.processPendingTask(event);
}
}
public ParticipantCompletionTask getParticipantTask() {
return participantTask.isNull() ? null : participantTask;
}
public OrganizationCompletionTask getOrganizationTask() {
return organizationTask.isNull() ? null : organizationTask;
}
}
@Data
@Embed
@NoArgsConstructor
@VisibleForTesting
static class ParticipantCompletionTask implements CompletionTask {
private NullableKeyWrapper<User> participant = NullableKeyWrapper.create();
private int karmaPointsAssigned;
public ParticipantCompletionTask(Key<User> participantKey) {
this(participantKey, 0);
}
public ParticipantCompletionTask(Key<User> participantKey, int karmaPointsAssigned) {
this.participant = NullableKeyWrapper.create(participantKey);
this.karmaPointsAssigned = karmaPointsAssigned;
}
@XmlTransient
public boolean isNull() {
return participant.isNull();
}
@Override
public CompletionTaskWrapper processPendingTask(Event event) {
Key<User> participantKey = KeyWrapper.toKey(participant);
User participant = BaseDao.load(participantKey);
if (participant == null) {
// Nothing to do. User no longer exists.
return null;
}
// Delete the previously assigned karma points and attendance history.
participant.setKarmaPoints(participant.getKarmaPoints() - karmaPointsAssigned);
participant.removeFromEventAttendanceHistory(Key.create(event));
// Assign the new karma points and attendance history if the participant is still part
// of the event.
CompletionTaskWrapper completedTask = null;
EventParticipant eventParticipant = event.tryFindParticipant(participantKey);
if (eventParticipant != null) {
if ((eventParticipant.type == ParticipantType.ORGANIZER) ||
(eventParticipant.type == ParticipantType.REGISTERED)) {
participant.setKarmaPoints(participant.getKarmaPoints() + event.karmaPoints);
participant.addToAttendanceHistory(new AttendanceRecord(event, true));
completedTask = new CompletionTaskWrapper(
new ParticipantCompletionTask(participantKey, event.karmaPoints));
} else if (eventParticipant.type == ParticipantType.REGISTERED_NO_SHOW) {
participant.addToAttendanceHistory(new AttendanceRecord(event, false));
completedTask = new CompletionTaskWrapper(
new ParticipantCompletionTask(participantKey));
}
}
BaseDao.partialUpdate(participant);
return completedTask;
}
}
@Data
@Embed
@NoArgsConstructor
@VisibleForTesting
static class OrganizationCompletionTask implements CompletionTask {
private NullableKeyWrapper<Organization> organization = NullableKeyWrapper.create();
private int karmaPointsAssigned;
public OrganizationCompletionTask(Key<Organization> orgKey) {
this(orgKey, 0);
}
private OrganizationCompletionTask(Key<Organization> orgKey, int karmaPointsAssigned) {
this.organization = NullableKeyWrapper.create(orgKey);
this.karmaPointsAssigned = karmaPointsAssigned;
}
@XmlTransient
public boolean isNull() {
return organization.isNull();
}
@Override
public CompletionTaskWrapper processPendingTask(Event event) {
Key<Organization> orgKey = KeyWrapper.toKey(organization);
Organization org = BaseDao.load(orgKey);
if (org == null) {
// Nothing to do. Org no longer exists.
return null;
}
org.setKarmaPoints(org.getKarmaPoints() + event.karmaPoints);
BaseDao.partialUpdate(org);
return new CompletionTaskWrapper(new OrganizationCompletionTask(orgKey, event.karmaPoints));
}
}
}
public static void processEventCompletionTasks(Key<Event> eventKey) {
ProcessEventCompletionTasksTxn completionTasksTxn;
do {
completionTasksTxn = new ProcessEventCompletionTasksTxn(eventKey);
ofy().transact(completionTasksTxn);
} while (completionTasksTxn.isWorkPending());
}
@Data
@EqualsAndHashCode(callSuper=false)
private static class ProcessEventCompletionTasksTxn extends VoidWork {
private final Key<Event> eventKey;
private boolean workPending;
public void vrun() {
Event event = BaseDao.load(eventKey);
if ((event == null) || event.completionProcessed) {
return;
}
event.processCompletionTasks();
workPending = !event.completionProcessed;
BaseDao.partialUpdate(event);
}
}
}
| Switch org karma points to total org impact.
| src/main/java/org/karmaexchange/dao/Event.java | Switch org karma points to total org impact. | <ide><path>rc/main/java/org/karmaexchange/dao/Event.java
<ide>
<ide> public void processParticipantMutation(Event event, EventParticipant participant,
<ide> MutationType mutationType) {
<add> // Update org karma points. We only have to update orgs that have been processed.
<add> List<CompletionTaskWrapper> orgCompletionTasks = findOrgCompletionTasks(tasksProcessed);
<add> for (CompletionTaskWrapper completionTask : orgCompletionTasks) {
<add> if (completionTask.getOrganizationTask().updateRequired(event)) {
<add> tasksProcessed.remove(completionTask);
<add> tasksPending.add(completionTask);
<add> }
<add> }
<add>
<add> // Process participant.
<ide> Key<User> participantKey = KeyWrapper.toKey(participant.getUser());
<ide> CompletionTaskWrapper completionTask =
<ide> tryFindParticipantCompletionTask(tasksPending, participantKey);
<ide> }
<ide> }
<ide> };
<add> }
<add>
<add> private List<CompletionTaskWrapper> findOrgCompletionTasks(
<add> List<CompletionTaskWrapper> list) {
<add> Predicate<CompletionTaskWrapper> orgPredicate = new Predicate<CompletionTaskWrapper>() {
<add> @Override
<add> public boolean apply(@Nullable CompletionTaskWrapper input) {
<add> return input.getOrganizationTask() != null;
<add> }
<add> };
<add> return Lists.newArrayList(Iterables.filter(list, orgPredicate));
<ide> }
<ide>
<ide> private interface CompletionTask {
<ide> // Nothing to do. Org no longer exists.
<ide> return null;
<ide> }
<del> org.setKarmaPoints(org.getKarmaPoints() + event.karmaPoints);
<add> org.setKarmaPoints(
<add> org.getKarmaPoints() + computeImpactKarmaPoints(event) - karmaPointsAssigned);
<ide> BaseDao.partialUpdate(org);
<del> return new CompletionTaskWrapper(new OrganizationCompletionTask(orgKey, event.karmaPoints));
<add> return new CompletionTaskWrapper(
<add> new OrganizationCompletionTask(orgKey, computeImpactKarmaPoints(event)));
<add> }
<add>
<add> public boolean updateRequired(Event event) {
<add> return computeImpactKarmaPoints(event) != karmaPointsAssigned;
<add> }
<add>
<add> private int computeImpactKarmaPoints(Event event) {
<add> return event.karmaPoints * event.getNumAttending();
<ide> }
<ide> }
<ide> } |
|
Java | apache-2.0 | fa0d6f8126dae4e3858681b28856054de2ad3478 | 0 | whitesource/fs-agent,whitesource/fs-agent,whitesource/fs-agent,whitesource/fs-agent,whitesource/fs-agent,whitesource/fs-agent | package org.whitesource.agent.dependency.resolver;
import org.slf4j.Logger;
import org.whitesource.agent.Constants;
import org.whitesource.agent.utils.FilesScanner;
import org.whitesource.agent.utils.LoggerFactory;
import java.io.*;
import java.util.*;
import java.util.stream.Collectors;
/**
* @author raz.nitzan
*/
public class ViaMultiModuleAnalyzer {
/* --- Static Members --- */
private static final String APP_PATH = "AppPath";
private static final String DEPENDENCY_MANAGER_PATH = "DependencyManagerFilePath";
private static final String PROJECT_FOLDER_PATH = "ProjectFolderPath";
private static final String DEFAULT_NAME = "defaultName";
private static final String ALT_NAME = "altName";
/* --- Members --- */
private final Logger logger = LoggerFactory.getLogger(ViaMultiModuleAnalyzer.class);
private final Collection<String> buildExtensions = new HashSet<>(Arrays.asList(".jar", ".war", ".zip"));
private AbstractDependencyResolver dependencyResolver;
private String suffixOfBuild;
private String scanDirectory;
private String contentFileAppPaths;
private Collection<String> bomFiles = new HashSet<>();
/* --- Constructor --- */
public ViaMultiModuleAnalyzer(String scanDirectory, AbstractDependencyResolver dependencyResolver, String suffixOfBuild, String contentFileAppPaths) {
this.dependencyResolver = dependencyResolver;
this.suffixOfBuild = suffixOfBuild;
this.scanDirectory = scanDirectory;
this.contentFileAppPaths = contentFileAppPaths;
findBomFiles();
}
private void findBomFiles() {
Collection<String> scanDirectoryCollection = new LinkedList<>();
scanDirectoryCollection.add(scanDirectory);
Collection<ResolvedFolder> topFolders = new FilesScanner().findTopFolders(scanDirectoryCollection, dependencyResolver.getBomPattern(), dependencyResolver.getExcludes());
topFolders.forEach(topFolder -> topFolder.getTopFoldersFound().forEach((folder, bomFilesFound) -> this.bomFiles.addAll(bomFilesFound)));
}
public void writeFile() {
try {
File outputFile = new File(this.contentFileAppPaths);
FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(fileOutputStream));
bufferedWriter.write(replaceAllSlashes(DEPENDENCY_MANAGER_PATH + Constants.EQUALS + this.scanDirectory));
bufferedWriter.write(System.lineSeparator());
int counter = 1;
boolean printMessageAppPath = true;
HashMap<String, Integer> folderNameCounter = new HashMap<String, Integer>();
for (String bomFile : bomFiles) {
File parentFileOfBom = new File(bomFile).getParentFile();
String parentFileName = parentFileOfBom.getName();
File buildFolder = new File(parentFileOfBom.getPath() + File.separator + this.suffixOfBuild);
if (buildFolder.exists() && buildFolder.isDirectory() && buildFolder.listFiles() != null) {
Collection<File> filesWithBuildExtensions = Arrays.stream(buildFolder.listFiles()).filter(file -> {
for (String extension : buildExtensions) {
if (file.getName().endsWith(extension)) {
return true;
}
}
return false;
}).collect(Collectors.toList());
try {
if (filesWithBuildExtensions.size() >= 1) {
bufferedWriter.write(replaceAllSlashes(PROJECT_FOLDER_PATH + counter + Constants.EQUALS + parentFileOfBom.getAbsolutePath()));
bufferedWriter.write(System.lineSeparator());
String appPathProperty = APP_PATH + counter + Constants.EQUALS;
if (filesWithBuildExtensions.size() == 1) {
File appPath = filesWithBuildExtensions.stream().findFirst().get();
appPathProperty += appPath.getAbsolutePath();
} else if (printMessageAppPath) {
logger.warn("Analysis found multiple candidates for one or more appPath settings that are listed in the multi-module analysis setup file. Please review the setup file and set the appropriate appPath parameters.");
printMessageAppPath = false;
}
bufferedWriter.write(replaceAllSlashes(appPathProperty));
bufferedWriter.write(System.lineSeparator());
bufferedWriter.write(replaceAllSlashes(DEFAULT_NAME + counter + Constants.EQUALS + parentFileName));
bufferedWriter.write(System.lineSeparator());
if (folderNameCounter.get(parentFileName) == null){
folderNameCounter.put(parentFileName,0);
bufferedWriter.write(replaceAllSlashes(ALT_NAME + counter + Constants.EQUALS + parentFileName));
} else {
int i = folderNameCounter.get(parentFileName) + 1;
folderNameCounter.put(parentFileName,i);
bufferedWriter.write(replaceAllSlashes(ALT_NAME + counter + Constants.EQUALS + parentFileName + i));
}
bufferedWriter.write(System.lineSeparator());
counter++;
}
} catch (IOException e) {
logger.warn("Failed to write to file: {}", this.contentFileAppPaths);
}
}
}
bufferedWriter.flush();
bufferedWriter.close();
} catch (IOException e) {
logger.warn("Failed to write to file: {}", this.contentFileAppPaths);
}
}
public Collection<String> getBomFiles() {
return this.bomFiles;
}
private String replaceAllSlashes(String line) {
return line.replaceAll("\\\\", "/");
}
}
| src/main/java/org/whitesource/agent/dependency/resolver/ViaMultiModuleAnalyzer.java | package org.whitesource.agent.dependency.resolver;
import org.slf4j.Logger;
import org.whitesource.agent.Constants;
import org.whitesource.agent.utils.FilesScanner;
import org.whitesource.agent.utils.LoggerFactory;
import java.io.*;
import java.util.*;
import java.util.stream.Collectors;
/**
* @author raz.nitzan
*/
public class ViaMultiModuleAnalyzer {
/* --- Static Members --- */
private static final String APP_PATH = "AppPath";
private static final String DEPENDENCY_MANAGER_PATH = "DependencyManagerFilePath";
private static final String PROJECT_FOLDER_PATH = "ProjectFolderPath";
/* --- Members --- */
private final Logger logger = LoggerFactory.getLogger(ViaMultiModuleAnalyzer.class);
private final Collection<String> buildExtensions = new HashSet<>(Arrays.asList(".jar", ".war", ".zip"));
private AbstractDependencyResolver dependencyResolver;
private String suffixOfBuild;
private String scanDirectory;
private String contentFileAppPaths;
private Collection<String> bomFiles = new HashSet<>();
/* --- Constructor --- */
public ViaMultiModuleAnalyzer(String scanDirectory, AbstractDependencyResolver dependencyResolver, String suffixOfBuild, String contentFileAppPaths) {
this.dependencyResolver = dependencyResolver;
this.suffixOfBuild = suffixOfBuild;
this.scanDirectory = scanDirectory;
this.contentFileAppPaths = contentFileAppPaths;
findBomFiles();
}
private void findBomFiles() {
Collection<String> scanDirectoryCollection = new LinkedList<>();
scanDirectoryCollection.add(scanDirectory);
Collection<ResolvedFolder> topFolders = new FilesScanner().findTopFolders(scanDirectoryCollection, dependencyResolver.getBomPattern(), dependencyResolver.getExcludes());
topFolders.forEach(topFolder -> topFolder.getTopFoldersFound().forEach((folder, bomFilesFound) -> this.bomFiles.addAll(bomFilesFound)));
}
public void writeFile() {
try {
File outputFile = new File(this.contentFileAppPaths);
FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(fileOutputStream));
bufferedWriter.write(replaceAllSlashes(DEPENDENCY_MANAGER_PATH + Constants.EQUALS + this.scanDirectory));
bufferedWriter.write(System.lineSeparator());
int counter = 1;
boolean printMessageAppPath = true;
HashMap<String, Integer> folderNameCounter = new HashMap<String, Integer>();
for (String bomFile : bomFiles) {
File parentFileOfBom = new File(bomFile).getParentFile();
String parentFileName = parentFileOfBom.getName();
File buildFolder = new File(parentFileOfBom.getPath() + File.separator + this.suffixOfBuild);
if (buildFolder.exists() && buildFolder.isDirectory() && buildFolder.listFiles() != null) {
Collection<File> filesWithBuildExtensions = Arrays.stream(buildFolder.listFiles()).filter(file -> {
for (String extension : buildExtensions) {
if (file.getName().endsWith(extension)) {
return true;
}
}
return false;
}).collect(Collectors.toList());
try {
if (filesWithBuildExtensions.size() >= 1) {
bufferedWriter.write(replaceAllSlashes(PROJECT_FOLDER_PATH + counter + Constants.EQUALS + parentFileOfBom.getAbsolutePath()));
bufferedWriter.write(System.lineSeparator());
String appPathProperty = APP_PATH + counter + Constants.EQUALS;
if (filesWithBuildExtensions.size() == 1) {
File appPath = filesWithBuildExtensions.stream().findFirst().get();
appPathProperty += appPath.getAbsolutePath();
} else if (printMessageAppPath) {
logger.warn("Analysis found multiple candidates for one or more appPath settings that are listed in the multi-module analysis setup file. Please review the setup file and set the appropriate appPath parameters.");
printMessageAppPath = false;
}
bufferedWriter.write(replaceAllSlashes(appPathProperty));
bufferedWriter.write(System.lineSeparator());
bufferedWriter.write(replaceAllSlashes("defaultName" + Constants.EQUALS + parentFileName));
bufferedWriter.write(System.lineSeparator());
if (folderNameCounter.get(parentFileName) == null){
folderNameCounter.put(parentFileName,0);
bufferedWriter.write(replaceAllSlashes("altName" + Constants.EQUALS + parentFileName));
} else {
int i = folderNameCounter.get(parentFileName) + 1;
folderNameCounter.put(parentFileName,i);
bufferedWriter.write(replaceAllSlashes("altName" + Constants.EQUALS + parentFileName + i));
}
bufferedWriter.write(System.lineSeparator());
counter++;
}
} catch (IOException e) {
logger.warn("Failed to write to file: {}", this.contentFileAppPaths);
}
}
}
bufferedWriter.flush();
bufferedWriter.close();
} catch (IOException e) {
logger.warn("Failed to write to file: {}", this.contentFileAppPaths);
}
}
public Collection<String> getBomFiles() {
return this.bomFiles;
}
private String replaceAllSlashes(String line) {
return line.replaceAll("\\\\", "/");
}
}
| WSE-1176 - improved output of FSA
| src/main/java/org/whitesource/agent/dependency/resolver/ViaMultiModuleAnalyzer.java | WSE-1176 - improved output of FSA | <ide><path>rc/main/java/org/whitesource/agent/dependency/resolver/ViaMultiModuleAnalyzer.java
<ide> private static final String APP_PATH = "AppPath";
<ide> private static final String DEPENDENCY_MANAGER_PATH = "DependencyManagerFilePath";
<ide> private static final String PROJECT_FOLDER_PATH = "ProjectFolderPath";
<add> private static final String DEFAULT_NAME = "defaultName";
<add> private static final String ALT_NAME = "altName";
<ide>
<ide> /* --- Members --- */
<ide>
<ide> }
<ide> bufferedWriter.write(replaceAllSlashes(appPathProperty));
<ide> bufferedWriter.write(System.lineSeparator());
<del> bufferedWriter.write(replaceAllSlashes("defaultName" + Constants.EQUALS + parentFileName));
<add> bufferedWriter.write(replaceAllSlashes(DEFAULT_NAME + counter + Constants.EQUALS + parentFileName));
<ide> bufferedWriter.write(System.lineSeparator());
<ide> if (folderNameCounter.get(parentFileName) == null){
<ide> folderNameCounter.put(parentFileName,0);
<del> bufferedWriter.write(replaceAllSlashes("altName" + Constants.EQUALS + parentFileName));
<add> bufferedWriter.write(replaceAllSlashes(ALT_NAME + counter + Constants.EQUALS + parentFileName));
<ide> } else {
<ide> int i = folderNameCounter.get(parentFileName) + 1;
<ide> folderNameCounter.put(parentFileName,i);
<del> bufferedWriter.write(replaceAllSlashes("altName" + Constants.EQUALS + parentFileName + i));
<add> bufferedWriter.write(replaceAllSlashes(ALT_NAME + counter + Constants.EQUALS + parentFileName + i));
<ide> }
<ide> bufferedWriter.write(System.lineSeparator());
<ide> counter++; |
|
JavaScript | apache-2.0 | 82c3f1f5933025908a8ebf62cdbadf3a5104ead0 | 0 | coolaj86/formaline,coolaj86/formaline |
var http = require( 'http' ),
formaline = require( '../../lib/formaline' ).formaline,
connect = require( 'connect' ),
server,
log = console.log,
dir = '/tmp/';
getHtmlForm = function( req, res, next ) {
if (req.url === '/test/') {
log( ' -> req url :', req.url );
res.writeHead( 200, { 'content-type': 'text/html' } );
res.end( '<html><head></head><body>\
<b>Multiple File Upload:</b><br/><br/>\
<form action="/test/upload" enctype="multipart/form-data" method="post">\
<input type="text" name="demotitle1"/><br/>\
<input type="file" name="multiplefield1" multiple="multiple"><br/>\
<input type="text" name="demotitle2"><br/>\
<input type="file" name="multiplefield2" multiple="multiple"><br/>\
<input type="text" name="demotitle3"/><br/>\
<input type="file" name="multiplefield3" multiple="multiple"><br/>\
<input type="submit" value="Upload"/>\
</form><br/>\
<b>Simple Post:</b><br/><br/>\
<form action="/test/post" method="post">\
<input type="text" name="simplefield1"/><br/>\
<input type="text" name="simplefield2"/><br/>\
<input type="text" name="simplefield3"/><br/>\
<input type="submit" value="Submit">\
</form><br/>\
<b>Iframe Multiple File Upload:</b><br/><br/>\
<form action="/test/upload" method="post" enctype="multipart/form-data" target="iframe">\
<input type="text" name="iframefield1"/><br/>\
<input type="file" name="iframefile1" multiple src="" frameborder="1" /><br/>\
<input type="text" name="iframefield"/><br/>\
<input type="file" name="iframefile2" multiple src="" frameborder="1" /><br/>\
<input type="submit" />\
</form>\
<iframe name="iframe" width="100%" height="400px"></iframe>\
</form>\
</body></html>'
);
} else {
next();
}
},
handleFormRequest = function( req, res, next ){
var receivedFields = {},
form = null,
config = {
// default is true -->
holdFilesExtensions : true,
// default is /tmp/ -->
uploadRootDir: dir,
// retrieve session ID for creating unique upload directory for authenticated users
// the upload directory gets its name from the returned session identifier,
// and will remain the same across multiple posts ( for the authenticated user with this session identifier )
// this function have to return the request property that holds session id
// the returned session id param, must contain a String, not a function or an object
// the function takes http request as a parameter at run-time
getSessionID: function( req ){
return ( ( req.sessionID ) || ( req.sid ) || ( ( req.session && req.session.id ) ? req.session.id : null ) );
},
// default is false
// return sha1 digests for files received?
sha1sum: true,
// default is false, or integer chunk factor,
// every n chunk emits a dataprogress event: 1 + ( 0 * n ) 1 + ( 1 * n ), 1 + ( 2 * n ), 1 + ( 3 * n ),
// minimum factor value is 2
emitDataProgress: false, // 3, 10, 100
// max bytes allowed, this is the max bytes written to disk before stop to write
// this is also true for serialzed fields not only for files upload
uploadThreshold: 1024 * 1024 * 1024, // bytes ex.: 1024*1024*1024, 512
// default false, bypass headers value, continue to write to disk
// until uploadThreshold bytes are written.
// if true -> stop receiving data, when headers content length exceeds uploadThreshold
checkContentLength: false,
// remove file not completed due to uploadThreshold,
// if true formaline emit fileremoved event,
// otherwise return a path array of incomplete files
removeIncompleteFiles : true,
// default is 'debug:off,1:on,2:on,3:off';
// enable various logging levels
// it is possible to switch on/off one or more levels at the same time
// debug: 'off' turn off logging
logging: 'debug:on,1:on,2:on,3:off', // <-- turn off 2nd level to see only warnings, and parser overall results
// listeners
listeners: {
'exception': function( json ){ // json:{ type: '..', isupload: true/false , msg: '..', fatal: true/false }
},
'dataprogress': function( json ) {
},
'field': function( json ){
},
'filereceived': function( json ) {
},
'fileremoved': function( json ) {
},
'end': function( json, res, next ) {
log( '\n-> Post Done' );
res.writeHead( 200, { 'content-type': 'text/plain' } );
res.write( '-> ' + new Date() + '\n' );
res.write( '-> request processed! \n' );
res.write( '\n-> stats -> ' + JSON.stringify( json.stats ) + '\n' );
res.write( '\n-> upload dir: ' + form.uploadRootDir + ' \n' );
res.write( '-> upload threshold : ' + ( form.uploadThreshold ) + ' bytes \n' );
res.write( '-> checkContentLength: ' + form.checkContentLength + '\n' );
res.write( '-> holdFilesExtensions: ' + form.holdFilesExtensions + '\n' );
res.write( '-> sha1sum: ' + form.sha1sum + '\n');
res.write( '-> removeIncompleteFiles: ' + form.removeIncompleteFiles + '\n' );
res.write( '-> emitDataProgress: ' + form.emitDataProgress + '\n');
res.write( '-> logging: "' + form.logging + '"\n' );
res.write( '\n-> fields received: \n ****************\n' + JSON.stringify( json.fields ) + '\n' );
res.write( '\n-> files received: ( { sha1 filename: {..} }, { .. } )\n ***************\n ' + JSON.stringify( json.completed ) + '\n' );
if( form.removeIncompleteFiles ){
res.write( '\n-> files removed: ( { sha1 filename: {..} }, { .. } )\n **************\n '+ JSON.stringify( json.incomplete ) + '\n' );
}else{
if( json.incomplete.length !== 0 ){
res.write( '\n-> incomplete files (not removed): \n ****************\n' + JSON.stringify( json.incomplete ) + '\n' );
}
}
res.end();
next(); // test callback
}
}
};//end config obj
if ( (req.url === '/test/upload') || (req.url === '/test/post') ){
log( ' -> req url :', req.url );
form = new formaline( config ) ;
form.parse( req, res, next );
} else {
log( ' -> req url 404 error :', req.url );
res.writeHead( 404, { 'content-type': 'text/plain' } );
res.end( '404' );
}
};
server = connect( getHtmlForm , handleFormRequest, function(){ console.log( '\nHi!, I\'m the next() callback function!'); } );
server.listen( 3000 );
log( '\nlistening on http://localhost:3000/' );
log( ' -> upload directory is:', dir );
| examples/simple/simpleUpload.js |
var http = require( 'http' ),
formaline = require( '../../lib/formaline' ).formaline,
connect = require( 'connect' ),
server,
log = console.log,
dir = '/tmp/';
getHtmlForm = function( req, res, next ) {
if (req.url === '/test/') {
log( ' -> req url :', req.url );
res.writeHead( 200, { 'content-type': 'text/html' } );
res.end( '<html><head></head><body>\
<b>Multiple File Upload:</b><br/><br/>\
<form action="/test/upload" enctype="multipart/form-data" method="post">\
<input type="text" name="demotitle1"/><br/>\
<input type="file" name="multiplefield1" multiple="multiple"><br/>\
<input type="text" name="demotitle2/"><br/>\
<input type="file" name="multiplefield2" multiple="multiple"><br/>\
<input type="text" name="demotitle3"/><br/>\
<input type="file" name="multiplefield3" multiple="multiple"><br/>\
<input type="submit" value="Upload"/>\
</form><br/>\
<b>Simple Post:</b><br/><br/>\
<form action="/test/post" method="post">\
<input type="text" name="simplefield1"/><br/>\
<input type="text" name="simplefield2"/><br/>\
<input type="text" name="simplefield3"/><br/>\
<input type="submit" value="Submit">\
</form><br/>\
<b>Iframe Multiple File Upload:</b><br/><br/>\
<form action="/test/upload" method="post" enctype="multipart/form-data" target="iframe">\
<input type="text" name="iframefield1"/><br/>\
<input type="file" name="iframefile1" multiple src="" frameborder="1" /><br/>\
<input type="text" name="iframefield"/><br/>\
<input type="file" name="iframefile2" multiple src="" frameborder="1" /><br/>\
<input type="submit" />\
</form>\
<iframe name="iframe" width="100%" height="400px"></iframe>\
</form>\
</body></html>'
);
} else {
next();
}
},
handleFormRequest = function( req, res, next ){
var receivedFields = {},
form = null,
config = {
// default is true -->
holdFilesExtensions : true,
// default is /tmp/ -->
uploadRootDir: dir,
// retrieve session ID for creating unique upload directory for authenticated users
// the upload directory gets its name from the returned session identifier,
// and will remain the same across multiple posts ( for the authenticated user with this session identifier )
// this function have to return the request property that holds session id
// the returned session id param, must contain a String, not a function or an object
// the function takes http request as a parameter at run-time
getSessionID: function( req ){
return ( ( req.sessionID ) || ( req.sid ) || ( ( req.session && req.session.id ) ? req.session.id : null ) );
},
// default is false
// return sha1 digests for files received?
sha1sum: true,
// default is false, or integer chunk factor,
// every n chunk emits a dataprogress event: 1 + ( 0 * n ) 1 + ( 1 * n ), 1 + ( 2 * n ), 1 + ( 3 * n ),
// minimum factor value is 2
emitDataProgress: false, // 3, 10, 100
// max bytes allowed, this is the max bytes written to disk before stop to write
// this is also true for serialzed fields not only for files upload
uploadThreshold: 1024 * 1024 * 1024, // bytes ex.: 1024*1024*1024, 512
// default false, bypass headers value, continue to write to disk
// until uploadThreshold bytes are written.
// if true -> stop receiving data, when headers content length exceeds uploadThreshold
checkContentLength: false,
// remove file not completed due to uploadThreshold,
// if true formaline emit fileremoved event,
// otherwise return a path array of incomplete files
removeIncompleteFiles : true,
// default is 'debug:off,1:on,2:on,3:off';
// enable various logging levels
// it is possible to switch on/off one or more levels at the same time
// debug: 'off' turn off logging
logging: 'debug:on,1:on,2:on,3:off', // <-- turn off 2nd level to see only warnings, and parser overall results
// listeners
listeners: {
'exception': function( json ){ // json:{ type: '..', isupload: true/false , msg: '..', fatal: true/false }
},
'dataprogress': function( json ) {
},
'field': function( json ){
},
'filereceived': function( json ) {
},
'fileremoved': function( json ) {
},
'end': function( json, res, next ) {
log( '\n-> Post Done' );
res.writeHead( 200, { 'content-type': 'text/plain' } );
res.write( '-> ' + new Date() + '\n' );
res.write( '-> request processed! \n' );
res.write( '\n-> stats -> ' + JSON.stringify( json.stats ) + '\n' );
res.write( '\n-> upload dir: ' + form.uploadRootDir + ' \n' );
res.write( '-> upload threshold : ' + ( form.uploadThreshold ) + ' bytes \n' );
res.write( '-> checkContentLength: ' + form.checkContentLength + '\n' );
res.write( '-> holdFilesExtensions: ' + form.holdFilesExtensions + '\n' );
res.write( '-> sha1sum: ' + form.sha1sum + '\n');
res.write( '-> removeIncompleteFiles: ' + form.removeIncompleteFiles + '\n' );
res.write( '-> emitDataProgress: ' + form.emitDataProgress + '\n');
res.write( '-> logging: "' + form.logging + '"\n' );
res.write( '\n-> fields received: \n ****************\n' + JSON.stringify( json.fields ) + '\n' );
res.write( '\n-> files received: ( { sha1 filename: {..} }, { .. } )\n ***************\n ' + JSON.stringify( json.completed ) + '\n' );
if( form.removeIncompleteFiles ){
res.write( '\n-> files removed: ( { sha1 filename: {..} }, { .. } )\n **************\n '+ JSON.stringify( json.incomplete ) + '\n' );
}else{
if( json.incomplete.length !== 0 ){
res.write( '\n-> incomplete files (not removed): \n ****************\n' + JSON.stringify( json.incomplete ) + '\n' );
}
}
res.end();
next(); // test callback
}
}
};//end config obj
if ( (req.url === '/test/upload') || (req.url === '/test/post') ){
log( ' -> req url :', req.url );
form = new formaline( config ) ;
form.parse( req, res, next );
} else {
log( ' -> req url 404 error :', req.url );
res.writeHead( 404, { 'content-type': 'text/plain' } );
res.end( '404' );
}
};
server = connect( getHtmlForm , handleFormRequest, function(){ console.log( '\nHi!, I\'m the next() callback function!'); } );
server.listen( 3000 );
log( '\nlistening on http://localhost:3000/' );
log( ' -> upload directory is:', dir );
| modified: examples/simple/simpleUpload.js
| examples/simple/simpleUpload.js | modified: examples/simple/simpleUpload.js | <ide><path>xamples/simple/simpleUpload.js
<ide> <form action="/test/upload" enctype="multipart/form-data" method="post">\
<ide> <input type="text" name="demotitle1"/><br/>\
<ide> <input type="file" name="multiplefield1" multiple="multiple"><br/>\
<del> <input type="text" name="demotitle2/"><br/>\
<add> <input type="text" name="demotitle2"><br/>\
<ide> <input type="file" name="multiplefield2" multiple="multiple"><br/>\
<ide> <input type="text" name="demotitle3"/><br/>\
<ide> <input type="file" name="multiplefield3" multiple="multiple"><br/>\ |
|
JavaScript | mit | 3a88812e82ecdf4ac179465c7768c50c207275bf | 0 | ccxt/ccxt,ccxt/ccxt,ccxt/ccxt,ccxt/ccxt,ccxt/ccxt | 'use strict';
// ---------------------------------------------------------------------------
const bittrex = require ('./bittrex.js');
const { ExchangeError, InvalidOrder, AuthenticationError, InsufficientFunds, BadRequest } = require ('./base/errors');
// ---------------------------------------------------------------------------
module.exports = class bleutrade extends bittrex {
describe () {
const timeframes = {
'15m': '15m',
'20m': '20m',
'30m': '30m',
'1h': '1h',
'2h': '2h',
'3h': '3h',
'4h': '4h',
'6h': '6h',
'8h': '8h',
'12h': '12h',
'1d': '1d',
};
const result = this.deepExtend (super.describe (), {
'id': 'bleutrade',
'name': 'Bleutrade',
'countries': [ 'BR' ], // Brazil
'rateLimit': 1000,
'version': 'v2',
'certified': false,
'has': {
'CORS': true,
'fetchTickers': true,
'fetchOrders': false,
'fetchWithdrawals': true,
'fetchClosedOrders': false,
'fetchOrderTrades': false,
'fetchLedger': true,
'fetchDepositAddress': true,
},
'timeframes': timeframes,
'hostname': 'bleutrade.com',
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/30303000-b602dbe6-976d-11e7-956d-36c5049c01e7.jpg',
'api': {
'public': 'https://{hostname}/api/v2',
'market': 'https://{hostname}/api/v2',
'v3Private': 'https://{hostname}/api/v3/private',
'v3Public': 'https://{hostname}/api/v3/public',
},
'www': 'https://bleutrade.com',
'doc': [
'https://app.swaggerhub.com/apis-docs/bleu/white-label/3.0.0',
],
'fees': 'https://bleutrade.com/fees/',
},
'api': {
'public': {
'get': [
'candles',
'markethistory',
'marketsummaries',
'marketsummary',
'orderbook',
'ticker',
],
},
'v3Public': {
'get': [
'getassets',
'getmarkets',
'getticker',
'getmarketsummary',
'getmarketsummaries',
'getorderbook',
'getmarkethistory',
'getcandles',
],
},
'v3Private': {
'post': [
'getbalance',
'getbalances',
'buylimit',
'selllimit',
'buylimitami',
'selllimitami',
'buystoplimit',
'sellstoplimit',
'ordercancel',
'getopenorders',
'getdeposithistory',
'getdepositaddress',
'getmytransactions',
'withdraw',
'directtransfer',
'getwithdrawhistory',
'getlimits',
],
},
},
'commonCurrencies': {
'EPC': 'Epacoin',
},
'exceptions': {
'exact': {
'ERR_INSUFICIENT_BALANCE': InsufficientFunds,
'ERR_LOW_VOLUME': BadRequest,
},
'broad': {
'Order is not open': InvalidOrder,
'Invalid Account / Api KEY / Api Secret': AuthenticationError,
},
},
'fees': {
'trading': {
'tierBased': false,
'percentage': true,
'taker': 0.25 / 100,
'maker': 0.25 / 100,
},
},
'options': {
'parseOrderStatus': true,
'disableNonce': false,
'symbolSeparator': '_',
},
});
// bittrex inheritance override
result['timeframes'] = timeframes;
return result;
}
async fetchCurrencies (params = {}) {
const response = await this.v3PublicGetGetassets (params);
const items = response['result'];
const result = {};
for (let i = 0; i < items.length; i++) {
// { Asset: 'USDT',
// AssetLong: 'Tether',
// MinConfirmation: 4,
// WithdrawTxFee: 1,
// WithdrawTxFeePercent: 0,
// SystemProtocol: 'ETHERC20',
// IsActive: true,
// InfoMessage: '',
// MaintenanceMode: false,
// MaintenanceMessage: '',
// FormatPrefix: '',
// FormatSufix: '',
// DecimalSeparator: '.',
// ThousandSeparator: ',',
// DecimalPlaces: 8,
// Currency: 'USDT',
// CurrencyLong: 'Tether',
// CoinType: 'ETHERC20' }
const item = items[i];
const id = this.safeString (item, 'Asset');
const code = this.safeCurrencyCode (id);
result[code] = {
'id': id,
'code': code,
'name': this.safeString (item, 'AssetLong'),
'active': this.safeValue (item, 'IsActive') && !this.safeValue (item, 'MaintenanceMode'),
'fee': this.safeFloat (item, 'WithdrawTxFee'),
'precision': this.safeFloat (item, 'DecimalPlaces'),
'info': item,
};
}
return result;
}
async fetchMarkets (params = {}) {
// https://github.com/ccxt/ccxt/issues/5668
const response = await this.v3PublicGetGetmarkets (params);
const result = [];
const markets = this.safeValue (response, 'result');
for (let i = 0; i < markets.length; i++) {
const market = markets[i];
// { MarketName: 'LTC_USDT',
// MarketAsset: 'LTC',
// BaseAsset: 'USDT',
// MarketAssetLong: 'Litecoin',
// BaseAssetLong: 'Tether',
// IsActive: true,
// MinTradeSize: 0.0001,
// InfoMessage: '',
// MarketCurrency: 'LTC',
// BaseCurrency: 'USDT',
// MarketCurrencyLong: 'Litecoin',
// BaseCurrencyLong: 'Tether' }
const id = this.safeString (market, 'MarketName');
const baseId = this.safeString (market, 'MarketCurrency');
const quoteId = this.safeString (market, 'BaseCurrency');
const base = this.safeCurrencyCode (baseId);
const quote = this.safeCurrencyCode (quoteId);
const symbol = base + '/' + quote;
const precision = {
'amount': 8,
'price': 8,
};
const active = this.safeValue (market, 'IsActive', false);
result.push ({
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'baseId': baseId,
'quoteId': quoteId,
'active': active,
'info': market,
'precision': precision,
'maker': this.fees['trading']['maker'],
'taker': this.fees['trading']['taker'],
'limits': {
'amount': {
'min': this.safeFloat (market, 'MinTradeSize'),
'max': undefined,
},
'price': {
'min': Math.pow (10, -precision['price']),
'max': undefined,
},
},
});
}
return result;
}
parseOrderStatus (status) {
const statuses = {
'OK': 'closed',
'OPEN': 'open',
'CANCELED': 'canceled',
};
return this.safeString (statuses, status, status);
}
async fetchBalance (params = {}) {
await this.loadMarkets ();
const response = await this.v3PrivatePostGetbalances (params);
const result = { 'info': response };
const items = response['result'];
for (let i = 0; i < items.length; i++) {
const item = items[i];
const currencyId = this.safeString (item, 'Asset');
const code = this.safeCurrencyCode (currencyId);
const account = this.account ();
account['free'] = this.safeFloat (item, 'Available');
account['total'] = this.safeFloat (item, 'Balance');
result[code] = account;
}
return this.parseBalance (result);
}
getOrderIdField () {
return 'orderid';
}
parseSymbol (id) {
let [ base, quote ] = id.split (this.options['symbolSeparator']);
base = this.safeCurrencyCode (base);
quote = this.safeCurrencyCode (quote);
return base + '/' + quote;
}
async fetchOrderBook (symbol, limit = undefined, params = {}) {
await this.loadMarkets ();
const request = {
'market': this.marketId (symbol),
'type': 'ALL',
};
if (limit !== undefined) {
request['depth'] = limit; // 50
}
const response = await this.publicGetOrderbook (this.extend (request, params));
const orderbook = this.safeValue (response, 'result');
if (!orderbook) {
throw new ExchangeError (this.id + ' publicGetOrderbook() returneded no result ' + this.json (response));
}
return this.parseOrderBook (orderbook, undefined, 'buy', 'sell', 'Rate', 'Quantity');
}
async fetchTransactionsByType (type, code = undefined, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
const method = (type === 'deposit') ? 'v3PrivatePostGetdeposithistory' : 'v3PrivatePostGetwithdrawhistory';
const response = await this[method] (params);
const result = this.parseTransactions (response['result']);
return this.filterByCurrencySinceLimit (result, code, since, limit);
}
async fetchDeposits (code = undefined, since = undefined, limit = undefined, params = {}) {
return await this.fetchTransactionsByType ('deposit', code, since, limit, params);
}
async fetchWithdrawals (code = undefined, since = undefined, limit = undefined, params = {}) {
return await this.fetchTransactionsByType ('withdrawal', code, since, limit, params);
}
async fetchDepositAddress (code, params = {}) {
await this.loadMarkets ();
const currency = this.currency (code);
const request = {
'asset': currency['id'],
};
const response = await this.v3PrivatePostGetdepositaddress (this.extend (request, params));
// { success: true,
// message: '',
// result:
// { Asset: 'ETH',
// AssetName: 'Ethereum',
// DepositAddress: '0x748c5c8jhksjdfhd507d3aa9',
// Currency: 'ETH',
// CurrencyName: 'Ethereum' } }
const item = response['result'];
const address = this.safeString (item, 'DepositAddress');
return {
'currency': code,
'address': this.checkAddress (address),
// 'tag': tag,
'info': item,
};
}
parseOHLCV (ohlcv, market = undefined, timeframe = '1d', since = undefined, limit = undefined) {
const timestamp = this.parse8601 (ohlcv['TimeStamp'] + '+00:00');
return [
timestamp,
this.safeFloat (ohlcv, 'Open'),
this.safeFloat (ohlcv, 'High'),
this.safeFloat (ohlcv, 'Low'),
this.safeFloat (ohlcv, 'Close'),
this.safeFloat (ohlcv, 'Volume'),
];
}
async fetchOHLCV (symbol, timeframe = '15m', since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
const request = {
'period': this.timeframes[timeframe],
'market': market['id'],
'count': limit,
};
const response = await this.publicGetCandles (this.extend (request, params));
if ('result' in response) {
if (response['result']) {
return this.parseOHLCVs (response['result'], market, timeframe, since, limit);
}
}
}
parseTrade (trade, market = undefined) {
const timestamp = this.parse8601 (trade['TimeStamp'] + '+00:00');
let side = undefined;
if (trade['OrderType'] === 'BUY') {
side = 'buy';
} else if (trade['OrderType'] === 'SELL') {
side = 'sell';
}
const id = this.safeString2 (trade, 'TradeID', 'ID');
let symbol = undefined;
if (market !== undefined) {
symbol = market['symbol'];
}
let cost = undefined;
const price = this.safeFloat (trade, 'Price');
const amount = this.safeFloat (trade, 'Quantity');
if (amount !== undefined) {
if (price !== undefined) {
cost = price * amount;
}
}
return {
'id': id,
'info': trade,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'symbol': symbol,
'type': 'limit',
'side': side,
'order': undefined,
'takerOrMaker': undefined,
'price': price,
'amount': amount,
'cost': cost,
'fee': undefined,
};
}
parseLedgerEntryType (type) {
// deposits don't seem to appear in here
const types = {
'TRADE': 'trade',
'WITHDRAW': 'transaction',
};
return this.safeString (types, type, type);
}
parseLedgerEntry (item, currency = undefined) {
//
// trade (both sides)
//
// {
// ID: 109660527,
// TimeStamp: '2018-11-14 15:12:57.140776',
// Asset: 'ETH',
// AssetName: 'Ethereum',
// Amount: 0.01,
// Type: 'TRADE',
// Description: 'Trade +, order id 133111123',
// Comments: '',
// CoinSymbol: 'ETH',
// CoinName: 'Ethereum'
// }
//
// {
// ID: 109660526,
// TimeStamp: '2018-11-14 15:12:57.140776',
// Asset: 'BTC',
// AssetName: 'Bitcoin',
// Amount: -0.00031776,
// Type: 'TRADE',
// Description: 'Trade -, order id 133111123, fee -0.00000079',
// Comments: '',
// CoinSymbol: 'BTC',
// CoinName: 'Bitcoin'
// }
//
// withdrawal
//
// {
// ID: 104672316,
// TimeStamp: '2018-05-03 08:18:19.031831',
// Asset: 'DOGE',
// AssetName: 'Dogecoin',
// Amount: -61893.87864686,
// Type: 'WITHDRAW',
// Description: 'Withdraw: 61883.87864686 to address DD8tgehNNyYB2iqVazi2W1paaztgcWXtF6; fee 10.00000000',
// Comments: '',
// CoinSymbol: 'DOGE',
// CoinName: 'Dogecoin'
// }
//
const code = this.safeCurrencyCode (this.safeString (item, 'CoinSymbol'), currency);
const description = this.safeString (item, 'Description');
const type = this.parseLedgerEntryType (this.safeString (item, 'Type'));
let referenceId = undefined;
let fee = undefined;
const delimiter = (type === 'trade') ? ', ' : '; ';
const parts = description.split (delimiter);
for (let i = 0; i < parts.length; i++) {
let part = parts[i];
if (part.indexOf ('fee') === 0) {
part = part.replace ('fee ', '');
let feeCost = parseFloat (part);
if (feeCost < 0) {
feeCost = -feeCost;
}
fee = {
'cost': feeCost,
'currency': code,
};
} else if (part.indexOf ('order id') === 0) {
referenceId = part.replace ('order id', '');
}
//
// does not belong to Ledger, related to parseTransaction
//
// if (part.indexOf ('Withdraw') === 0) {
// const details = part.split (' to address ');
// if (details.length > 1) {
// address = details[1];
// }
//
}
const timestamp = this.parse8601 (this.safeString (item, 'TimeStamp'));
let amount = this.safeFloat (item, 'Amount');
let direction = undefined;
if (amount !== undefined) {
direction = 'in';
if (amount < 0) {
direction = 'out';
amount = -amount;
}
}
const id = this.safeString (item, 'ID');
return {
'id': id,
'info': item,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'direction': direction,
'account': undefined,
'referenceId': referenceId,
'referenceAccount': undefined,
'type': type,
'currency': code,
'amount': amount,
'before': undefined,
'after': undefined,
'status': 'ok',
'fee': fee,
};
}
async fetchLedger (code = undefined, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
// only seems to return 100 items and there is no documented way to change page size or offset
const request = {
};
const response = await this.v3PrivatePostGetmytransactions (this.extend (request, params));
const items = response['result'];
return this.parseLedger (items, code, since, limit);
}
parseOrder (order, market = undefined) {
//
// fetchOrders
//
// {
// OrderId: '107220258',
// Exchange: 'LTC_BTC',
// Type: 'SELL',
// Quantity: '2.13040000',
// QuantityRemaining: '0.00000000',
// Price: '0.01332672',
// Status: 'OK',
// Created: '2018-06-30 04:55:50',
// QuantityBaseTraded: '0.02839125',
// Comments: ''
// }
//
let side = this.safeString2 (order, 'OrderType', 'Type');
const isBuyOrder = (side === 'LIMIT_BUY') || (side === 'BUY');
const isSellOrder = (side === 'LIMIT_SELL') || (side === 'SELL');
if (isBuyOrder) {
side = 'buy';
}
if (isSellOrder) {
side = 'sell';
}
// We parse different fields in a very specific order.
// Order might well be closed and then canceled.
let status = undefined;
if (('Opened' in order) && order['Opened']) {
status = 'open';
}
if (('Closed' in order) && order['Closed']) {
status = 'closed';
}
if (('CancelInitiated' in order) && order['CancelInitiated']) {
status = 'canceled';
}
if (('Status' in order) && this.options['parseOrderStatus']) {
status = this.parseOrderStatus (this.safeString (order, 'Status'));
}
let symbol = undefined;
const marketId = this.safeString (order, 'Exchange');
if (marketId === undefined) {
if (market !== undefined) {
symbol = market['symbol'];
}
} else {
if (marketId in this.markets_by_id) {
market = this.markets_by_id[marketId];
symbol = market['symbol'];
} else {
symbol = this.parseSymbol (marketId);
}
}
let timestamp = undefined;
if ('Opened' in order) {
timestamp = this.parse8601 (order['Opened'] + '+00:00');
}
if ('Created' in order) {
timestamp = this.parse8601 (order['Created'] + '+00:00');
}
let lastTradeTimestamp = undefined;
if (('TimeStamp' in order) && (order['TimeStamp'] !== undefined)) {
lastTradeTimestamp = this.parse8601 (order['TimeStamp'] + '+00:00');
}
if (('Closed' in order) && (order['Closed'] !== undefined)) {
lastTradeTimestamp = this.parse8601 (order['Closed'] + '+00:00');
}
if (timestamp === undefined) {
timestamp = lastTradeTimestamp;
}
let fee = undefined;
let commission = undefined;
if ('Commission' in order) {
commission = 'Commission';
} else if ('CommissionPaid' in order) {
commission = 'CommissionPaid';
}
if (commission) {
fee = {
'cost': this.safeFloat (order, commission),
};
if (market !== undefined) {
fee['currency'] = market['quote'];
} else if (symbol !== undefined) {
const currencyIds = symbol.split ('/');
const quoteCurrencyId = currencyIds[1];
fee['currency'] = this.safeCurrencyCode (quoteCurrencyId);
}
}
let price = this.safeFloat (order, 'Price');
let cost = undefined;
const amount = this.safeFloat (order, 'Quantity');
const remaining = this.safeFloat (order, 'QuantityRemaining');
let filled = undefined;
if (amount !== undefined && remaining !== undefined) {
filled = amount - remaining;
}
if (!cost) {
if (price && filled) {
cost = price * filled;
}
}
if (!price) {
if (cost && filled) {
price = cost / filled;
}
}
const average = this.safeFloat (order, 'PricePerUnit');
const id = this.safeString2 (order, 'OrderUuid', 'OrderId');
return {
'info': order,
'id': id,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'lastTradeTimestamp': lastTradeTimestamp,
'symbol': symbol,
'type': 'limit',
'side': side,
'price': price,
'cost': cost,
'average': average,
'amount': amount,
'filled': filled,
'remaining': remaining,
'status': status,
'fee': fee,
};
}
parseTransaction (transaction, currency = undefined) {
//
// deposit:
//
// {
// Id: '96974373',
// Coin: 'DOGE',
// Amount: '12.05752192',
// TimeStamp: '2017-09-29 08:10:09',
// Label: 'DQqSjjhzCm3ozT4vAevMUHgv4vsi9LBkoE',
// }
//
// withdrawal:
//
// { ID: 689281,
// Timestamp: '2019-07-05 13:14:43',
// Asset: 'BTC',
// Amount: -0.108959,
// TransactionID: 'da48d6901fslfjsdjflsdjfls852b87e362cad1',
// Status: 'CONFIRMED',
// Label: '0.1089590;35wztHPMgrebFvvlisuhfasuf;0.00100000',
// Symbol: 'BTC' }
//
// {
// "Id": "95820181",
// "Coin": "BTC",
// "Amount": "-0.71300000",
// "TimeStamp": "2017-07-19 17:14:24",
// "Label": "0.71200000;PER9VM2txt4BTdfyWgvv3GziECRdVEPN63;0.00100000",
// "TransactionId": "CANCELED"
// }
//
const id = this.safeString (transaction, 'ID');
let amount = this.safeFloat (transaction, 'Amount');
let type = 'deposit';
if (amount < 0) {
amount = Math.abs (amount);
type = 'withdrawal';
}
const currencyId = this.safeString (transaction, 'Asset');
const code = this.safeCurrencyCode (currencyId, currency);
const label = this.safeString (transaction, 'Label');
const timestamp = this.parse8601 (this.safeString (transaction, 'Timestamp'));
let txid = this.safeString (transaction, 'TransactionID');
let address = undefined;
let feeCost = undefined;
const labelParts = label.split (';');
if (labelParts.length === 3) {
amount = parseFloat (labelParts[0]);
address = labelParts[1];
feeCost = parseFloat (labelParts[2]);
} else {
address = label;
}
let fee = undefined;
if (feeCost !== undefined) {
fee = {
'currency': code,
'cost': feeCost,
};
}
let status = 'ok';
if (txid === 'CANCELED') {
txid = undefined;
status = 'canceled';
}
return {
'info': transaction,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'id': id,
'currency': code,
'amount': amount,
'address': address,
'tag': undefined,
'status': status,
'type': type,
'updated': undefined,
'txid': txid,
'fee': fee,
};
}
sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
let url = this.implodeParams (this.urls['api'][api], {
'hostname': this.hostname,
}) + '/';
if (api === 'v3Private') {
this.checkRequiredCredentials ();
const request = {
'apikey': this.apiKey,
'nonce': this.nonce (),
};
url += path + '?' + this.urlencode (this.extend (request, params));
const signature = this.hmac (this.encode (url), this.encode (this.secret), 'sha512');
headers = { 'apisign': signature };
} else if (api === 'v3Public') {
const request = {
};
url += path + '?' + this.urlencode (this.extend (request, params));
} else {
url += api + '/' + method.toLowerCase () + path;
if (Object.keys (params).length) {
url += '?' + this.urlencode (params);
}
}
return { 'url': url, 'method': method, 'body': body, 'headers': headers };
}
handleErrors (code, reason, url, method, headers, body, response, requestHeaders, requestBody) {
if (response === undefined) {
return; // fallback to default error handler
}
// examples...
// {"success":false,"message":"Erro: Order is not open.","result":""} <-- 'error' is spelt wrong
// {"success":false,"message":"Error: Very low volume.","result":"ERR_LOW_VOLUME"}
// {"success":false,"message":"Error: Insuficient Balance","result":"ERR_INSUFICIENT_BALANCE"}
//
if (body[0] === '{') {
const success = this.safeValue (response, 'success');
if (success === undefined) {
throw new ExchangeError (this.id + ': malformed response: ' + this.json (response));
}
if (!success) {
const feedback = this.id + ' ' + body;
const errorCode = this.safeString (response, 'result');
this.throwBroadlyMatchedException (this.exceptions['broad'], errorCode, feedback);
this.throwExactlyMatchedException (this.exceptions['exact'], errorCode, feedback);
const errorMessage = this.safeString (response, 'message');
this.throwBroadlyMatchedException (this.exceptions['broad'], errorMessage, feedback);
this.throwExactlyMatchedException (this.exceptions['exact'], errorMessage, feedback);
throw new ExchangeError (feedback);
}
}
}
};
| js/bleutrade.js | 'use strict';
// ---------------------------------------------------------------------------
const bittrex = require ('./bittrex.js');
const { ExchangeError, InvalidOrder, AuthenticationError, InsufficientFunds, BadRequest } = require ('./base/errors');
// ---------------------------------------------------------------------------
module.exports = class bleutrade extends bittrex {
describe () {
const timeframes = {
'15m': '15m',
'20m': '20m',
'30m': '30m',
'1h': '1h',
'2h': '2h',
'3h': '3h',
'4h': '4h',
'6h': '6h',
'8h': '8h',
'12h': '12h',
'1d': '1d',
};
const result = this.deepExtend (super.describe (), {
'id': 'bleutrade',
'name': 'Bleutrade',
'countries': [ 'BR' ], // Brazil
'rateLimit': 1000,
'version': 'v2',
'certified': false,
'has': {
'CORS': true,
'fetchTickers': true,
'fetchOrders': false,
'fetchWithdrawals': true,
'fetchClosedOrders': false,
'fetchOrderTrades': false,
'fetchLedger': true,
'fetchDepositAddress': true,
},
'timeframes': timeframes,
'hostname': 'bleutrade.com',
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/30303000-b602dbe6-976d-11e7-956d-36c5049c01e7.jpg',
'api': {
'public': 'https://{hostname}/api/v2',
'market': 'https://{hostname}/api/v2',
'v3Private': 'https://{hostname}/api/v3/private',
'v3Public': 'https://{hostname}/api/v3/public',
},
'www': 'https://bleutrade.com',
'doc': [
'https://app.swaggerhub.com/apis-docs/bleu/white-label/3.0.0',
],
'fees': 'https://bleutrade.com/fees/',
},
'api': {
'public': {
'get': [
'candles',
'markethistory',
'marketsummaries',
'marketsummary',
'orderbook',
'ticker',
],
},
'v3Public': {
'get': [
'getassets',
'getmarkets',
'getticker',
'getmarketsummary',
'getmarketsummaries',
'getorderbook',
'getmarkethistory',
'getcandles',
],
},
'v3Private': {
'post': [
'getbalance',
'getbalances',
'buylimit',
'selllimit',
'buylimitami',
'selllimitami',
'buystoplimit',
'sellstoplimit',
'ordercancel',
'getopenorders',
'getdeposithistory',
'getdepositaddress',
'getmytransactions',
'withdraw',
'directtransfer',
'getwithdrawhistory',
'getlimits',
],
},
},
'commonCurrencies': {
'EPC': 'Epacoin',
},
'exceptions': {
'exact': {
'ERR_INSUFICIENT_BALANCE': InsufficientFunds,
'ERR_LOW_VOLUME': BadRequest,
},
'broad': {
'Order is not open': InvalidOrder,
'Invalid Account / Api KEY / Api Secret': AuthenticationError,
},
},
'fees': {
'trading': {
'tierBased': false,
'percentage': true,
'taker': 0.25 / 100,
'maker': 0.25 / 100,
},
},
'options': {
// price precision by quote currency code
'pricePrecisionByCode': {
'USD': 3,
},
'parseOrderStatus': true,
'disableNonce': false,
'symbolSeparator': '_',
},
});
// bittrex inheritance override
result['timeframes'] = timeframes;
return result;
}
async fetchCurrencies (params = {}) {
const response = await this.v3PublicGetGetassets (params);
const items = response['result'];
const result = {};
for (let i = 0; i < items.length; i++) {
// { Asset: 'USDT',
// AssetLong: 'Tether',
// MinConfirmation: 4,
// WithdrawTxFee: 1,
// WithdrawTxFeePercent: 0,
// SystemProtocol: 'ETHERC20',
// IsActive: true,
// InfoMessage: '',
// MaintenanceMode: false,
// MaintenanceMessage: '',
// FormatPrefix: '',
// FormatSufix: '',
// DecimalSeparator: '.',
// ThousandSeparator: ',',
// DecimalPlaces: 8,
// Currency: 'USDT',
// CurrencyLong: 'Tether',
// CoinType: 'ETHERC20' }
const item = items[i];
const id = this.safeString (item, 'Asset');
const code = this.safeCurrencyCode (id);
result[code] = {
'id': id,
'code': code,
'name': this.safeString (item, 'AssetLong'),
'active': this.safeValue (item, 'IsActive') && !this.safeValue (item, 'MaintenanceMode'),
'fee': this.safeFloat (item, 'WithdrawTxFee'),
'precision': this.safeFloat (item, 'DecimalPlaces'),
'info': item,
};
}
return result;
}
async fetchMarkets (params = {}) {
// https://github.com/ccxt/ccxt/issues/5668
const response = await this.v3PublicGetGetmarkets (params);
const result = [];
const markets = this.safeValue (response, 'result');
for (let i = 0; i < markets.length; i++) {
const market = markets[i];
// { MarketName: 'LTC_USDT',
// MarketAsset: 'LTC',
// BaseAsset: 'USDT',
// MarketAssetLong: 'Litecoin',
// BaseAssetLong: 'Tether',
// IsActive: true,
// MinTradeSize: 0.0001,
// InfoMessage: '',
// MarketCurrency: 'LTC',
// BaseCurrency: 'USDT',
// MarketCurrencyLong: 'Litecoin',
// BaseCurrencyLong: 'Tether' }
const id = this.safeString (market, 'MarketName');
const baseId = this.safeString (market, 'MarketCurrency');
const quoteId = this.safeString (market, 'BaseCurrency');
const base = this.safeCurrencyCode (baseId);
const quote = this.safeCurrencyCode (quoteId);
const symbol = base + '/' + quote;
let pricePrecision = 8;
if (quote in this.options['pricePrecisionByCode']) {
pricePrecision = this.options['pricePrecisionByCode'][quote];
}
const precision = {
'amount': 8,
'price': pricePrecision,
};
const active = this.safeValue (market, 'IsActive', false);
result.push ({
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'baseId': baseId,
'quoteId': quoteId,
'active': active,
'info': market,
'precision': precision,
'maker': this.fees['trading']['maker'],
'taker': this.fees['trading']['taker'],
'limits': {
'amount': {
'min': this.safeFloat (market, 'MinTradeSize'),
'max': undefined,
},
'price': {
'min': Math.pow (10, -precision['price']),
'max': undefined,
},
},
});
}
return result;
}
parseOrderStatus (status) {
const statuses = {
'OK': 'closed',
'OPEN': 'open',
'CANCELED': 'canceled',
};
return this.safeString (statuses, status, status);
}
async fetchBalance (params = {}) {
await this.loadMarkets ();
const response = await this.v3PrivatePostGetbalances (params);
const result = { 'info': response };
const items = response['result'];
for (let i = 0; i < items.length; i++) {
const item = items[i];
const currencyId = this.safeString (item, 'Asset');
const code = this.safeCurrencyCode (currencyId);
const account = this.account ();
account['free'] = this.safeFloat (item, 'Available');
account['total'] = this.safeFloat (item, 'Balance');
result[code] = account;
}
return this.parseBalance (result);
}
getOrderIdField () {
return 'orderid';
}
parseSymbol (id) {
let [ base, quote ] = id.split (this.options['symbolSeparator']);
base = this.safeCurrencyCode (base);
quote = this.safeCurrencyCode (quote);
return base + '/' + quote;
}
async fetchOrderBook (symbol, limit = undefined, params = {}) {
await this.loadMarkets ();
const request = {
'market': this.marketId (symbol),
'type': 'ALL',
};
if (limit !== undefined) {
request['depth'] = limit; // 50
}
const response = await this.publicGetOrderbook (this.extend (request, params));
const orderbook = this.safeValue (response, 'result');
if (!orderbook) {
throw new ExchangeError (this.id + ' publicGetOrderbook() returneded no result ' + this.json (response));
}
return this.parseOrderBook (orderbook, undefined, 'buy', 'sell', 'Rate', 'Quantity');
}
async fetchTransactionsByType (type, code = undefined, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
const method = (type === 'deposit') ? 'v3PrivatePostGetdeposithistory' : 'v3PrivatePostGetwithdrawhistory';
const response = await this[method] (params);
const result = this.parseTransactions (response['result']);
return this.filterByCurrencySinceLimit (result, code, since, limit);
}
async fetchDeposits (code = undefined, since = undefined, limit = undefined, params = {}) {
return await this.fetchTransactionsByType ('deposit', code, since, limit, params);
}
async fetchWithdrawals (code = undefined, since = undefined, limit = undefined, params = {}) {
return await this.fetchTransactionsByType ('withdrawal', code, since, limit, params);
}
async fetchDepositAddress (code, params = {}) {
await this.loadMarkets ();
const currency = this.currency (code);
const request = {
'asset': currency['id'],
};
const response = await this.v3PrivatePostGetdepositaddress (this.extend (request, params));
// { success: true,
// message: '',
// result:
// { Asset: 'ETH',
// AssetName: 'Ethereum',
// DepositAddress: '0x748c5c8jhksjdfhd507d3aa9',
// Currency: 'ETH',
// CurrencyName: 'Ethereum' } }
const item = response['result'];
const address = this.safeString (item, 'DepositAddress');
return {
'currency': code,
'address': this.checkAddress (address),
// 'tag': tag,
'info': item,
};
}
parseOHLCV (ohlcv, market = undefined, timeframe = '1d', since = undefined, limit = undefined) {
const timestamp = this.parse8601 (ohlcv['TimeStamp'] + '+00:00');
return [
timestamp,
this.safeFloat (ohlcv, 'Open'),
this.safeFloat (ohlcv, 'High'),
this.safeFloat (ohlcv, 'Low'),
this.safeFloat (ohlcv, 'Close'),
this.safeFloat (ohlcv, 'Volume'),
];
}
async fetchOHLCV (symbol, timeframe = '15m', since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
const request = {
'period': this.timeframes[timeframe],
'market': market['id'],
'count': limit,
};
const response = await this.publicGetCandles (this.extend (request, params));
if ('result' in response) {
if (response['result']) {
return this.parseOHLCVs (response['result'], market, timeframe, since, limit);
}
}
}
parseTrade (trade, market = undefined) {
const timestamp = this.parse8601 (trade['TimeStamp'] + '+00:00');
let side = undefined;
if (trade['OrderType'] === 'BUY') {
side = 'buy';
} else if (trade['OrderType'] === 'SELL') {
side = 'sell';
}
const id = this.safeString2 (trade, 'TradeID', 'ID');
let symbol = undefined;
if (market !== undefined) {
symbol = market['symbol'];
}
let cost = undefined;
const price = this.safeFloat (trade, 'Price');
const amount = this.safeFloat (trade, 'Quantity');
if (amount !== undefined) {
if (price !== undefined) {
cost = price * amount;
}
}
return {
'id': id,
'info': trade,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'symbol': symbol,
'type': 'limit',
'side': side,
'order': undefined,
'takerOrMaker': undefined,
'price': price,
'amount': amount,
'cost': cost,
'fee': undefined,
};
}
parseLedgerEntryType (type) {
// deposits don't seem to appear in here
const types = {
'TRADE': 'trade',
'WITHDRAW': 'transaction',
};
return this.safeString (types, type, type);
}
parseLedgerEntry (item, currency = undefined) {
//
// trade (both sides)
//
// {
// ID: 109660527,
// TimeStamp: '2018-11-14 15:12:57.140776',
// Asset: 'ETH',
// AssetName: 'Ethereum',
// Amount: 0.01,
// Type: 'TRADE',
// Description: 'Trade +, order id 133111123',
// Comments: '',
// CoinSymbol: 'ETH',
// CoinName: 'Ethereum'
// }
//
// {
// ID: 109660526,
// TimeStamp: '2018-11-14 15:12:57.140776',
// Asset: 'BTC',
// AssetName: 'Bitcoin',
// Amount: -0.00031776,
// Type: 'TRADE',
// Description: 'Trade -, order id 133111123, fee -0.00000079',
// Comments: '',
// CoinSymbol: 'BTC',
// CoinName: 'Bitcoin'
// }
//
// withdrawal
//
// {
// ID: 104672316,
// TimeStamp: '2018-05-03 08:18:19.031831',
// Asset: 'DOGE',
// AssetName: 'Dogecoin',
// Amount: -61893.87864686,
// Type: 'WITHDRAW',
// Description: 'Withdraw: 61883.87864686 to address DD8tgehNNyYB2iqVazi2W1paaztgcWXtF6; fee 10.00000000',
// Comments: '',
// CoinSymbol: 'DOGE',
// CoinName: 'Dogecoin'
// }
//
const code = this.safeCurrencyCode (this.safeString (item, 'CoinSymbol'), currency);
const description = this.safeString (item, 'Description');
const type = this.parseLedgerEntryType (this.safeString (item, 'Type'));
let referenceId = undefined;
let fee = undefined;
const delimiter = (type === 'trade') ? ', ' : '; ';
const parts = description.split (delimiter);
for (let i = 0; i < parts.length; i++) {
let part = parts[i];
if (part.indexOf ('fee') === 0) {
part = part.replace ('fee ', '');
let feeCost = parseFloat (part);
if (feeCost < 0) {
feeCost = -feeCost;
}
fee = {
'cost': feeCost,
'currency': code,
};
} else if (part.indexOf ('order id') === 0) {
referenceId = part.replace ('order id', '');
}
//
// does not belong to Ledger, related to parseTransaction
//
// if (part.indexOf ('Withdraw') === 0) {
// const details = part.split (' to address ');
// if (details.length > 1) {
// address = details[1];
// }
//
}
const timestamp = this.parse8601 (this.safeString (item, 'TimeStamp'));
let amount = this.safeFloat (item, 'Amount');
let direction = undefined;
if (amount !== undefined) {
direction = 'in';
if (amount < 0) {
direction = 'out';
amount = -amount;
}
}
const id = this.safeString (item, 'ID');
return {
'id': id,
'info': item,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'direction': direction,
'account': undefined,
'referenceId': referenceId,
'referenceAccount': undefined,
'type': type,
'currency': code,
'amount': amount,
'before': undefined,
'after': undefined,
'status': 'ok',
'fee': fee,
};
}
async fetchLedger (code = undefined, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
// only seems to return 100 items and there is no documented way to change page size or offset
const request = {
};
const response = await this.v3PrivatePostGetmytransactions (this.extend (request, params));
const items = response['result'];
return this.parseLedger (items, code, since, limit);
}
parseOrder (order, market = undefined) {
//
// fetchOrders
//
// {
// OrderId: '107220258',
// Exchange: 'LTC_BTC',
// Type: 'SELL',
// Quantity: '2.13040000',
// QuantityRemaining: '0.00000000',
// Price: '0.01332672',
// Status: 'OK',
// Created: '2018-06-30 04:55:50',
// QuantityBaseTraded: '0.02839125',
// Comments: ''
// }
//
let side = this.safeString2 (order, 'OrderType', 'Type');
const isBuyOrder = (side === 'LIMIT_BUY') || (side === 'BUY');
const isSellOrder = (side === 'LIMIT_SELL') || (side === 'SELL');
if (isBuyOrder) {
side = 'buy';
}
if (isSellOrder) {
side = 'sell';
}
// We parse different fields in a very specific order.
// Order might well be closed and then canceled.
let status = undefined;
if (('Opened' in order) && order['Opened']) {
status = 'open';
}
if (('Closed' in order) && order['Closed']) {
status = 'closed';
}
if (('CancelInitiated' in order) && order['CancelInitiated']) {
status = 'canceled';
}
if (('Status' in order) && this.options['parseOrderStatus']) {
status = this.parseOrderStatus (this.safeString (order, 'Status'));
}
let symbol = undefined;
const marketId = this.safeString (order, 'Exchange');
if (marketId === undefined) {
if (market !== undefined) {
symbol = market['symbol'];
}
} else {
if (marketId in this.markets_by_id) {
market = this.markets_by_id[marketId];
symbol = market['symbol'];
} else {
symbol = this.parseSymbol (marketId);
}
}
let timestamp = undefined;
if ('Opened' in order) {
timestamp = this.parse8601 (order['Opened'] + '+00:00');
}
if ('Created' in order) {
timestamp = this.parse8601 (order['Created'] + '+00:00');
}
let lastTradeTimestamp = undefined;
if (('TimeStamp' in order) && (order['TimeStamp'] !== undefined)) {
lastTradeTimestamp = this.parse8601 (order['TimeStamp'] + '+00:00');
}
if (('Closed' in order) && (order['Closed'] !== undefined)) {
lastTradeTimestamp = this.parse8601 (order['Closed'] + '+00:00');
}
if (timestamp === undefined) {
timestamp = lastTradeTimestamp;
}
let fee = undefined;
let commission = undefined;
if ('Commission' in order) {
commission = 'Commission';
} else if ('CommissionPaid' in order) {
commission = 'CommissionPaid';
}
if (commission) {
fee = {
'cost': this.safeFloat (order, commission),
};
if (market !== undefined) {
fee['currency'] = market['quote'];
} else if (symbol !== undefined) {
const currencyIds = symbol.split ('/');
const quoteCurrencyId = currencyIds[1];
fee['currency'] = this.safeCurrencyCode (quoteCurrencyId);
}
}
let price = this.safeFloat (order, 'Price');
let cost = undefined;
const amount = this.safeFloat (order, 'Quantity');
const remaining = this.safeFloat (order, 'QuantityRemaining');
let filled = undefined;
if (amount !== undefined && remaining !== undefined) {
filled = amount - remaining;
}
if (!cost) {
if (price && filled) {
cost = price * filled;
}
}
if (!price) {
if (cost && filled) {
price = cost / filled;
}
}
const average = this.safeFloat (order, 'PricePerUnit');
const id = this.safeString2 (order, 'OrderUuid', 'OrderId');
return {
'info': order,
'id': id,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'lastTradeTimestamp': lastTradeTimestamp,
'symbol': symbol,
'type': 'limit',
'side': side,
'price': price,
'cost': cost,
'average': average,
'amount': amount,
'filled': filled,
'remaining': remaining,
'status': status,
'fee': fee,
};
}
parseTransaction (transaction, currency = undefined) {
//
// deposit:
//
// {
// Id: '96974373',
// Coin: 'DOGE',
// Amount: '12.05752192',
// TimeStamp: '2017-09-29 08:10:09',
// Label: 'DQqSjjhzCm3ozT4vAevMUHgv4vsi9LBkoE',
// }
//
// withdrawal:
//
// { ID: 689281,
// Timestamp: '2019-07-05 13:14:43',
// Asset: 'BTC',
// Amount: -0.108959,
// TransactionID: 'da48d6901fslfjsdjflsdjfls852b87e362cad1',
// Status: 'CONFIRMED',
// Label: '0.1089590;35wztHPMgrebFvvlisuhfasuf;0.00100000',
// Symbol: 'BTC' }
//
// {
// "Id": "95820181",
// "Coin": "BTC",
// "Amount": "-0.71300000",
// "TimeStamp": "2017-07-19 17:14:24",
// "Label": "0.71200000;PER9VM2txt4BTdfyWgvv3GziECRdVEPN63;0.00100000",
// "TransactionId": "CANCELED"
// }
//
const id = this.safeString (transaction, 'ID');
let amount = this.safeFloat (transaction, 'Amount');
let type = 'deposit';
if (amount < 0) {
amount = Math.abs (amount);
type = 'withdrawal';
}
const currencyId = this.safeString (transaction, 'Asset');
const code = this.safeCurrencyCode (currencyId, currency);
const label = this.safeString (transaction, 'Label');
const timestamp = this.parse8601 (this.safeString (transaction, 'Timestamp'));
let txid = this.safeString (transaction, 'TransactionID');
let address = undefined;
let feeCost = undefined;
const labelParts = label.split (';');
if (labelParts.length === 3) {
amount = parseFloat (labelParts[0]);
address = labelParts[1];
feeCost = parseFloat (labelParts[2]);
} else {
address = label;
}
let fee = undefined;
if (feeCost !== undefined) {
fee = {
'currency': code,
'cost': feeCost,
};
}
let status = 'ok';
if (txid === 'CANCELED') {
txid = undefined;
status = 'canceled';
}
return {
'info': transaction,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'id': id,
'currency': code,
'amount': amount,
'address': address,
'tag': undefined,
'status': status,
'type': type,
'updated': undefined,
'txid': txid,
'fee': fee,
};
}
sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
let url = this.implodeParams (this.urls['api'][api], {
'hostname': this.hostname,
}) + '/';
if (api === 'v3Private') {
this.checkRequiredCredentials ();
const request = {
'apikey': this.apiKey,
'nonce': this.nonce (),
};
url += path + '?' + this.urlencode (this.extend (request, params));
const signature = this.hmac (this.encode (url), this.encode (this.secret), 'sha512');
headers = { 'apisign': signature };
} else if (api === 'v3Public') {
const request = {
};
url += path + '?' + this.urlencode (this.extend (request, params));
} else {
url += api + '/' + method.toLowerCase () + path;
if (Object.keys (params).length) {
url += '?' + this.urlencode (params);
}
}
return { 'url': url, 'method': method, 'body': body, 'headers': headers };
}
handleErrors (code, reason, url, method, headers, body, response, requestHeaders, requestBody) {
if (response === undefined) {
return; // fallback to default error handler
}
// examples...
// {"success":false,"message":"Erro: Order is not open.","result":""} <-- 'error' is spelt wrong
// {"success":false,"message":"Error: Very low volume.","result":"ERR_LOW_VOLUME"}
// {"success":false,"message":"Error: Insuficient Balance","result":"ERR_INSUFICIENT_BALANCE"}
//
if (body[0] === '{') {
const success = this.safeValue (response, 'success');
if (success === undefined) {
throw new ExchangeError (this.id + ': malformed response: ' + this.json (response));
}
if (!success) {
const feedback = this.id + ' ' + body;
const errorCode = this.safeString (response, 'result');
this.throwBroadlyMatchedException (this.exceptions['broad'], errorCode, feedback);
this.throwExactlyMatchedException (this.exceptions['exact'], errorCode, feedback);
const errorMessage = this.safeString (response, 'message');
this.throwBroadlyMatchedException (this.exceptions['broad'], errorMessage, feedback);
this.throwExactlyMatchedException (this.exceptions['exact'], errorMessage, feedback);
throw new ExchangeError (feedback);
}
}
}
};
| [bleutrade] removed redundant price precision stuff
| js/bleutrade.js | [bleutrade] removed redundant price precision stuff | <ide><path>s/bleutrade.js
<ide> },
<ide> },
<ide> 'options': {
<del> // price precision by quote currency code
<del> 'pricePrecisionByCode': {
<del> 'USD': 3,
<del> },
<ide> 'parseOrderStatus': true,
<ide> 'disableNonce': false,
<ide> 'symbolSeparator': '_',
<ide> const base = this.safeCurrencyCode (baseId);
<ide> const quote = this.safeCurrencyCode (quoteId);
<ide> const symbol = base + '/' + quote;
<del> let pricePrecision = 8;
<del> if (quote in this.options['pricePrecisionByCode']) {
<del> pricePrecision = this.options['pricePrecisionByCode'][quote];
<del> }
<ide> const precision = {
<ide> 'amount': 8,
<del> 'price': pricePrecision,
<add> 'price': 8,
<ide> };
<ide> const active = this.safeValue (market, 'IsActive', false);
<ide> result.push ({ |
|
Java | lgpl-2.1 | 4d654f9ae220c088579ea09db836952557165607 | 0 | bjalon/nuxeo-features,nuxeo-archives/nuxeo-features,nuxeo-archives/nuxeo-features,deadcyclo/nuxeo-features,deadcyclo/nuxeo-features,nuxeo-archives/nuxeo-features,deadcyclo/nuxeo-features,bjalon/nuxeo-features,nuxeo-archives/nuxeo-features,deadcyclo/nuxeo-features,bjalon/nuxeo-features,deadcyclo/nuxeo-features,bjalon/nuxeo-features,bjalon/nuxeo-features,deadcyclo/nuxeo-features,nuxeo-archives/nuxeo-features,bjalon/nuxeo-features | /*
* (C) Copyright 2009 Nuxeo SA (http://nuxeo.com/) and contributors.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* (LGPL) version 2.1 which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl.html
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
*/
package org.nuxeo.ecm.platform.tag;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.persistence.EntityManager;
import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.nuxeo.common.utils.IdUtils;
import org.nuxeo.ecm.core.api.ClientException;
import org.nuxeo.ecm.core.api.CoreSession;
import org.nuxeo.ecm.core.api.DocumentModel;
import org.nuxeo.ecm.core.api.DocumentModelList;
import org.nuxeo.ecm.core.api.IdRef;
import org.nuxeo.ecm.core.api.UnrestrictedSessionRunner;
import org.nuxeo.ecm.core.api.impl.DocumentModelImpl;
import org.nuxeo.ecm.core.api.repository.RepositoryManager;
import org.nuxeo.ecm.core.persistence.HibernateConfiguration;
import org.nuxeo.ecm.core.persistence.HibernateConfigurator;
import org.nuxeo.ecm.core.persistence.PersistenceProvider;
import org.nuxeo.ecm.core.persistence.PersistenceProviderFactory;
import org.nuxeo.ecm.core.persistence.PersistenceProvider.RunCallback;
import org.nuxeo.ecm.core.persistence.PersistenceProvider.RunVoid;
import org.nuxeo.ecm.platform.tag.entity.DublincoreEntity;
import org.nuxeo.ecm.platform.tag.entity.TagEntity;
import org.nuxeo.ecm.platform.tag.entity.TaggingEntity;
import org.nuxeo.ecm.platform.tag.persistence.TagSchemaUpdater;
import org.nuxeo.ecm.platform.tag.persistence.TaggingProvider;
import org.nuxeo.runtime.api.Framework;
import org.nuxeo.runtime.model.ComponentContext;
import org.nuxeo.runtime.model.ComponentInstance;
import org.nuxeo.runtime.model.DefaultComponent;
import org.osgi.framework.FrameworkEvent;
import org.osgi.framework.FrameworkListener;
/**
* The implementation of tag service. For the API see {@link #TagService}
*
* @author rux
*/
public class TagServiceImpl extends DefaultComponent implements TagService,
TagConfigurator {
private static final Log log = LogFactory.getLog(TagServiceImpl.class);
private static Boolean enabled = null;
@Override
public void activate(ComponentContext context) throws Exception {
enabled = null;
context.getRuntimeContext().getBundle().getBundleContext().addFrameworkListener(
new FrameworkListener() {
public void frameworkEvent(FrameworkEvent event) {
if (event.getType() != FrameworkEvent.STARTED) {
return;
}
ClassLoader jbossCL = Thread.currentThread().getContextClassLoader();
ClassLoader nuxeoCL = TagServiceImpl.class.getClassLoader();
try {
// needs to be in Nuxeo ClassLoader to do a Login !
Thread.currentThread().setContextClassLoader(nuxeoCL);
if (isEnabled()) {
updateSchema();
}
}
finally {
Thread.currentThread().setContextClassLoader(jbossCL);
log.debug("JBoss ClassLoader restored");
}
}
});
TagServiceInitializer tagServiceInitializer = new TagServiceInitializer();
tagServiceInitializer.install();
}
protected void checkEnable() {
LoginContext lc = null;
try {
lc = Framework.login();
RepositoryManager rm = Framework.getService(RepositoryManager.class);
if (rm.getDefaultRepository().supportsTags()) {
log.info("Activating tag service");
enabled = true;
} else {
enabled = false;
log.warn("Default repository does not support Tag feature : Tag service won't be available.");
}
} catch (Exception e) {
enabled = false;
log.error("Unable to test repository for Tag feature.", e);
} finally {
if (lc != null) {
try {
lc.logout();
} catch (LoginException e) {
log.error("Error during Framework.logout", e);
}
}
}
}
@Override
public void deactivate(ComponentContext context) throws Exception {
deactivatePersistenceProvider();
super.deactivate(context);
}
@Override
public void registerContribution(Object contribution,
String extensionPoint, ComponentInstance contributor)
throws Exception {
if ("configs".equals(extensionPoint)) {
setConfig((TagConfig) contribution);
}
}
protected TagConfig config = new TagConfig();
public void setConfig(TagConfig config) {
this.config = config;
}
public TagConfig getConfig() {
return config;
}
protected PersistenceProvider persistenceProvider;
public PersistenceProvider getOrCreatePersistenceProvider() {
if (persistenceProvider != null) {
return persistenceProvider;
}
PersistenceProviderFactory persistenceProviderFactory = Framework.getLocalService(PersistenceProviderFactory.class);
persistenceProvider = persistenceProviderFactory.newProvider("nxtags");
return persistenceProvider;
}
protected void deactivatePersistenceProvider() {
if (persistenceProvider == null) {
return;
}
persistenceProvider.closePersistenceUnit();
persistenceProvider = null;
}
public DocumentModel getRootTag(final CoreSession session)
throws ClientException {
return getOrCreatePersistenceProvider().run(true,
new RunCallback<DocumentModel>() {
public DocumentModel runWith(EntityManager em)
throws ClientException {
return getRootTag(em, session);
}
});
}
public DocumentModel getRootTag(EntityManager em, CoreSession session)
throws ClientException {
if (log.isDebugEnabled()) {
log.debug("Going to look for root tag");
}
// use unrestricted session to get / create RootTag
UnrestrictedSessionCreateRootTag runner = new UnrestrictedSessionCreateRootTag(
session);
runner.runUnrestricted();
if (runner.rootTagDocumentId == null) {
throw new ClientException("Error creating the root tag document");
}
return session.getDocument(new IdRef(runner.rootTagDocumentId));
}
public void tagDocument(final CoreSession session,
final DocumentModel document, final String tagId,
final boolean privateFlag) throws ClientException {
getOrCreatePersistenceProvider().run(true, new RunVoid() {
public void runWith(EntityManager em) throws ClientException {
tagDocument(em, session, document, tagId, privateFlag);
}
});
}
public void tagDocument(EntityManager em, CoreSession session,
DocumentModel document, String tagId, boolean privateFlag)
throws ClientException {
if (null == document) {
throw new ClientException("Can't tag document null.");
}
TaggingProvider provider = TaggingProvider.createProvider(em);
TagEntity tagEntity = provider.getTagById(tagId);
if (tagEntity == null) {
throw new ClientException("Tag " + tagId + " doesn't exist");
}
if (log.isDebugEnabled()) {
log.debug("Going to tag document " + document.getTitle() + " with "
+ tagEntity.getLabel());
}
String user = getUserName(session);
// check if already tag applied
if (provider.existTagging(tagId, document.getId(), user)) {
log.warn(String.format(
"Tag %s already applied on %s by %s, don't create it",
tagEntity.getLabel(), document.getTitle(), user));
return;
}
TaggingEntity taggingEntry = new TaggingEntity();
String targetDocId = document.getId();
if (document.isProxy()) {
targetDocId = document.getSourceId();
}
DublincoreEntity dc = provider.getDcById(targetDocId);
taggingEntry.setId(IdUtils.generateStringId());
taggingEntry.setTag(tagEntity);
taggingEntry.setTargetDocument(dc);
taggingEntry.setCreationDate(new Date());
taggingEntry.setAuthor(user);
taggingEntry.setIsPrivate(privateFlag ? 1 : 0);
TaggingProvider.createProvider(em).addTagging(taggingEntry);
}
protected static String getUserName(CoreSession session)
throws ClientException {
if (session == null) {
throw new ClientException("No session available");
}
return session.getPrincipal().getName();
}
public DocumentModel getOrCreateTag(final CoreSession session,
final DocumentModel parent, final String label,
final boolean privateFlag) throws ClientException {
return getOrCreatePersistenceProvider().run(true,
new RunCallback<DocumentModel>() {
public DocumentModel runWith(EntityManager em)
throws ClientException {
return getOrCreateTag(em, session, parent, label,
privateFlag);
}
});
}
public DocumentModel getOrCreateTag(EntityManager em, CoreSession session,
DocumentModel parent, String label, boolean privateFlag)
throws ClientException {
if (parent == null) {
log.warn("Can't create tag in null parent");
throw new ClientException("Need a parent to create a tag");
}
if (log.isDebugEnabled()) {
log.debug("Going to look for label " + label);
}
UnrestrictedSessionCreateTag runner = new UnrestrictedSessionCreateTag(
session, parent, label, privateFlag);
runner.runUnrestricted();
if (runner.tagDocument == null) {
throw new ClientException("Error creating the tag document");
}
return runner.tagDocument;
}
public List<WeightedTag> getPopularCloud(final CoreSession session,
final DocumentModel document) throws ClientException {
return getOrCreatePersistenceProvider().run(false,
new RunCallback<List<WeightedTag>>() {
public List<WeightedTag> runWith(EntityManager em)
throws ClientException {
return getPopularCloud(em, session, document);
}
});
}
public List<WeightedTag> getPopularCloud(EntityManager em,
CoreSession session, DocumentModel document) throws ClientException {
// the NXSQL queries can't be used together with the native queries, for
// moment the queries are performed sequentially
if (null == document) {
throw new ClientException("Can't get cloud for domain null.");
}
if (log.isDebugEnabled()) {
log.debug("Going for popular cloud for " + document.getTitle());
}
String query = String.format(
"SELECT * FROM Document WHERE ecm:path STARTSWITH '%s' AND ecm:isProxy = %d",
document.getPathAsString(), config.isQueryingForProxy() ? 1 : 0);
UnrestrictedSessionRunQuery runner = new UnrestrictedSessionRunQuery(
session, query);
runner.runUnrestricted();
// add the current doc also
runner.result.add(document);
return TaggingProvider.createProvider(em).getPopularCloud(
runner.result, getUserName(session));
}
public List<WeightedTag> getPopularCloudOnAllDocuments(final CoreSession session) throws ClientException {
return getOrCreatePersistenceProvider().run(false,
new RunCallback<List<WeightedTag>>() {
public List<WeightedTag> runWith(EntityManager em)
throws ClientException {
return getPopularCloudOnAllDocuments(em, session);
}
});
}
public List<WeightedTag> getPopularCloudOnAllDocuments(EntityManager em,
CoreSession session) throws ClientException {
return TaggingProvider.createProvider(em).getPopularCloudOnAllDocuments(getUserName(session));
}
public WeightedTag getPopularTag(final CoreSession session,
final DocumentModel document, final String tagId)
throws ClientException {
return getOrCreatePersistenceProvider().run(false,
new RunCallback<WeightedTag>() {
public WeightedTag runWith(EntityManager em)
throws ClientException {
return getPopularTag(em, session, document, tagId);
}
});
}
public WeightedTag getPopularTag(EntityManager em, CoreSession session,
DocumentModel document, String tagId) throws ClientException {
if (null == document || null == tagId) {
throw new ClientException(
"Can't get popular for document or tag null.");
}
String user = getUserName(session);
DocumentModel tag = session.getDocument(new IdRef(tagId));
if (log.isDebugEnabled()) {
log.debug("Going to look for popularity of " + tag.getTitle()
+ " for " + document.getTitle());
}
if (!isTagAllowed(tag, user)) {
log.warn("Tag " + tag.getTitle() + " not allowed for " + user);
return new WeightedTag(tag.getId(), tag.getTitle(), 0);
}
// TODO int weight =
// getTaggingProvider().getPopularTag(document.getId(), tag.getId(),
// user);
return new WeightedTag(tag.getId(),
(String) tag.getPropertyValue(TagConstants.TAG_LABEL_FIELD), 0);
}
public List<WeightedTag> getVoteCloud(final CoreSession session,
final DocumentModel document) throws ClientException {
return getOrCreatePersistenceProvider().run(false,
new RunCallback<List<WeightedTag>>() {
public List<WeightedTag> runWith(EntityManager em)
throws ClientException {
return getVoteCloud(em, session, document);
}
});
}
public List<WeightedTag> getVoteCloud(EntityManager em,
CoreSession session, DocumentModel document) throws ClientException {
throw new UnsupportedOperationException();
}
public WeightedTag getVoteTag(final CoreSession session,
final DocumentModel document, final String tagId)
throws ClientException {
return getOrCreatePersistenceProvider().run(false,
new RunCallback<WeightedTag>() {
public WeightedTag runWith(EntityManager em)
throws ClientException {
return getVoteTag(em, session, document, tagId);
}
});
}
public WeightedTag getVoteTag(EntityManager em, CoreSession session,
DocumentModel document, String tagId) throws ClientException {
if (null == document) {
throw new ClientException(
"Can't get list of documents from domain null.");
}
String user = getUserName(session);
DocumentModel tag = session.getDocument(new IdRef(tagId));
if (log.isDebugEnabled()) {
log.debug("Going to look for votes of " + tag.getTitle() + " for "
+ document.getTitle());
}
if (!isTagAllowed(tag, user)) {
log.warn("Tag " + tag.getTitle() + " not allowed for " + user);
return new WeightedTag(tag.getId(), tag.getTitle(), 0);
}
TaggingProvider taggingProvider = TaggingProvider.createProvider(em);
Long result = taggingProvider.getVoteTag(document.getId(), tag.getId(),
user);
return new WeightedTag(tag.getId(),
(String) tag.getPropertyValue(TagConstants.TAG_LABEL_FIELD),
result.intValue());
}
public List<Tag> listTagsAppliedOnDocument(final CoreSession session,
final DocumentModel document) throws ClientException {
return getOrCreatePersistenceProvider().run(false,
new RunCallback<List<Tag>>() {
public List<Tag> runWith(EntityManager em)
throws ClientException {
return listTagsAppliedOnDocument(em, session, document);
}
});
}
public List<Tag> listTagsAppliedOnDocument(EntityManager em,
CoreSession session, DocumentModel document) throws ClientException {
if (null == document) {
throw new ClientException("Can't get list of tags from group null.");
}
if (log.isDebugEnabled()) {
log.debug("Going to look for tags applied on "
+ document.getTitle());
}
return TaggingProvider.createProvider(em).listTagsForDocument(
document.getId(), getUserName(session));
}
public List<Tag> listTagsAppliedOnDocumentByUser(final CoreSession session,
final DocumentModel document) throws ClientException {
return getOrCreatePersistenceProvider().run(false,
new RunCallback<List<Tag>>() {
public List<Tag> runWith(EntityManager em)
throws ClientException {
return listTagsAppliedOnDocumentByUser(em, session,
document);
}
});
}
public List<Tag> listTagsAppliedOnDocumentByUser(EntityManager em,
CoreSession session, DocumentModel document) throws ClientException {
if (null == document) {
throw new ClientException("Can't get list of tags from group null.");
}
if (log.isDebugEnabled()) {
log.debug("Going to look only current user tags applied on "
+ document.getTitle());
}
return TaggingProvider.createProvider(em).listTagsForDocumentAndUser(
document.getId(), getUserName(session));
}
public DocumentModelList listTagsInGroup(final CoreSession session,
final DocumentModel tag) throws ClientException {
return getOrCreatePersistenceProvider().run(false,
new RunCallback<DocumentModelList>() {
public DocumentModelList runWith(EntityManager em)
throws ClientException {
return listTagsInGroup(em, session, tag);
}
});
}
public DocumentModelList listTagsInGroup(final DocumentModel tag)
throws ClientException {
return listTagsInGroup(tag.getCoreSession(), tag);
}
public DocumentModelList listTagsInGroup(EntityManager em,
CoreSession session, DocumentModel tag) throws ClientException {
if (null == tag) {
throw new ClientException("Can't get list of tags from group null.");
}
if (log.isDebugEnabled()) {
log.debug("Going to list tags in " + tag.getTitle());
}
String user = getUserName(session);
String query = String.format(
"SELECT * FROM Tag WHERE ecm:path STARTSWITH '%s' AND (tag:private = 0 or dc:creator = '%s') AND ecm:isProxy = %d",
tag.getPathAsString(), user, config.isQueryingForProxy() ? 1
: 0);
UnrestrictedSessionRunQuery runner = new UnrestrictedSessionRunQuery(
session, query);
runner.runUnrestricted();
return runner.result;
}
public void untagDocument(final CoreSession session,
final DocumentModel document, final String tagId)
throws ClientException {
getOrCreatePersistenceProvider().run(true, new RunVoid() {
public void runWith(EntityManager em) throws ClientException {
untagDocument(em, session, document, tagId);
}
});
}
public void untagDocument(EntityManager em, CoreSession session,
DocumentModel document, String tagId) throws ClientException {
if (null == document || tagId == null) {
throw new ClientException("Can't untag document or tag null.");
}
if (log.isDebugEnabled()) {
log.debug("Going to untag " + tagId + " for " + document.getTitle());
}
TaggingProvider.createProvider(em).removeTagging(document.getId(),
tagId, getUserName(session));
}
public void completeUntagDocument(final CoreSession session,
final DocumentModel document, final String tagId)
throws ClientException {
getOrCreatePersistenceProvider().run(true, new RunVoid() {
public void runWith(EntityManager em) throws ClientException {
completeUntagDocument(em, session, document, tagId);
}
});
}
public void completeUntagDocument(EntityManager em, CoreSession session,
DocumentModel document, String tagId) throws ClientException {
if (null == document || tagId == null) {
throw new ClientException("Can't untag document or tag null.");
}
if (log.isDebugEnabled()) {
log.debug("Going to untag " + tagId + " for " + document.getTitle());
}
TaggingProvider.createProvider(em).removeAllTagging(document.getId(),
tagId);
}
public List<String> listDocumentsForTag(final CoreSession session,
final String tagId, final String user) throws ClientException {
return getOrCreatePersistenceProvider().run(true,
new RunCallback<List<String>>() {
public List<String> runWith(EntityManager em)
throws ClientException {
return listDocumentsForTag(em, session, tagId, user);
}
});
}
public List<String> listDocumentsForTag(EntityManager em,
CoreSession session, String tagId, String user)
throws ClientException {
if (null == tagId) {
throw new ClientException(
"Can't get list of documents for tag null.");
}
return TaggingProvider.createProvider(em).getDocumentsForTag(tagId,
user);
}
/**
* Checks if the tag is allowed to be used by the user.
*/
protected static boolean isTagAllowed(DocumentModel tag, String user)
throws ClientException {
if (tag == null) {
throw new ClientException(
"Can't get list of documents from tag null.");
}
Long isPrivate = (Long) tag.getPropertyValue(TagConstants.TAG_IS_PRIVATE_FIELD);
if (isPrivate == null || isPrivate == 0) {
return true;
}
String owner = (String) tag.getPropertyValue("dc:creator");
return user != null && user.equals(owner);
}
/**
* The unrestricted session runner to find / create root tag document.
*
* @author rux
*/
protected static class UnrestrictedSessionCreateRootTag extends
UnrestrictedSessionRunner {
public UnrestrictedSessionCreateRootTag(CoreSession session) {
super(session.getRepositoryName()); // always open new session
rootTagDocumentId = null;
}
// need to return somehow the result
public String rootTagDocumentId;
@Override
public void run() throws ClientException {
DocumentModel documentRoot = session.getRootDocument();
DocumentModelList rootHiddenChildren = session.getChildren(
documentRoot.getRef(), TagConstants.HIDDEN_FOLDER_TYPE);
if (null != rootHiddenChildren) {
for (DocumentModel hiddenFolder : rootHiddenChildren) {
if (TagConstants.TAGS_DIRECTORY.equals(hiddenFolder.getTitle())) {
rootTagDocumentId = hiddenFolder.getId();
return;
}
}
}
}
}
/**
* The unrestricted runner to find / create a tag document.
*
* @author rux
*/
protected class UnrestrictedSessionCreateTag extends
UnrestrictedSessionRunner {
// need to return somehow the result
public DocumentModel tagDocument;
// and to store the arguments
private final DocumentModel parent;
private final String label;
private final String user;
private final boolean privateFlag;
public UnrestrictedSessionCreateTag(CoreSession session,
DocumentModel parent, String label, boolean privateFlag)
throws ClientException {
super(session.getRepositoryName()); // always open new session
this.parent = parent;
tagDocument = null;
this.label = label;
user = TagServiceImpl.getUserName(session);
this.privateFlag = privateFlag;
}
@Override
public void run() throws ClientException {
// label can be in fact a composed label: labels separated by /
String[] labels = label.split("/");
DocumentModel relativeParent = parent;
for (String atomicLabel : labels) {
// for each label look for a public or user owned tag. If not,
// create it
String query = String.format(
"SELECT * FROM Tag WHERE ecm:parentId = '%s' AND tag:label = '%s' AND ecm:isProxy = %d",
relativeParent.getId(), atomicLabel,
config.queryProxy ? 1 : 0);
DocumentModelList tags = session.query(query);
DocumentModel foundTag = null;
if (tags != null && tags.size() > 0) {
// it should be only one, but it is possible to have more
// than one tag with the specified label in a group. Need to
// check the flag / user
for (DocumentModel aTag : tags) {
Long isPrivate = (Long) aTag.getPropertyValue(TagConstants.TAG_IS_PRIVATE_FIELD);
if (isPrivate == null || isPrivate == 0) {
// public tag, should be ok
foundTag = aTag;
break;
}
String tagUser = (String) aTag.getPropertyValue("dc:creator");
if (user.equals(tagUser)) {
// it pertains to this user
foundTag = aTag;
break;
}
}
}
if (foundTag != null) {
relativeParent = foundTag;
} else {
// couldn't find the tag, create it
relativeParent = createTagModel(session, relativeParent,
atomicLabel, user, privateFlag);
}
}
// and set ID for retrieval
tagDocument = relativeParent;
((DocumentModelImpl) tagDocument).detach(true);
}
}
/**
* The unrestricted runner for running a query.
*
* @author rux
*/
protected static class UnrestrictedSessionRunQuery extends
UnrestrictedSessionRunner {
// need to have somehow result
public DocumentModelList result;
// need to provide somehow the arguments
private final String query;
public UnrestrictedSessionRunQuery(CoreSession session, String query) {
super(session);
this.query = query;
result = null;
}
@Override
public void run() throws ClientException {
result = session.query(query);
}
}
protected static DocumentModel createTagModel(CoreSession session,
DocumentModel parent, String label, String user, boolean privateFlag)
throws ClientException {
DocumentModel tagDocument = session.createDocumentModel(
parent.getPathAsString(), IdUtils.generateId(label), "Tag");
tagDocument = session.createDocument(tagDocument);
tagDocument.setPropertyValue("dc:title", label);
tagDocument.setPropertyValue("dc:description", "");
tagDocument.setPropertyValue("dc:created", Calendar.getInstance());
tagDocument.setPropertyValue("dc:creator", user);
tagDocument.setPropertyValue(TagConstants.TAG_LABEL_FIELD, label);
tagDocument.setPropertyValue(TagConstants.TAG_IS_PRIVATE_FIELD,
privateFlag ? 1 : 0);
tagDocument = session.saveDocument(tagDocument);
session.save();
return tagDocument;
}
public String getTaggingId(final CoreSession session, final String docId,
final String tagLabel, final String author) throws ClientException {
return getOrCreatePersistenceProvider().run(false,
new RunCallback<String>() {
public String runWith(EntityManager em)
throws ClientException {
return getTaggingId(em, session, docId, tagLabel,
author);
}
});
}
public String getTaggingId(EntityManager em, CoreSession session,
String docId, String tagLabel, String author) {
return TaggingProvider.createProvider(em).getTaggingId(docId, tagLabel,
author);
}
public void updateSchema() {
HibernateConfigurator configurator = Framework.getLocalService(HibernateConfigurator.class);
HibernateConfiguration configuration = configurator.getHibernateConfiguration("nxtags");
TagSchemaUpdater updater = new TagSchemaUpdater(
configuration.hibernateProperties);
updater.update();
}
public boolean isEnabled() {
if (enabled == null) {
checkEnable();
}
return enabled;
}
}
| nuxeo-platform-tag-service/nuxeo-platform-tag-core/src/main/java/org/nuxeo/ecm/platform/tag/TagServiceImpl.java | /*
* (C) Copyright 2009 Nuxeo SA (http://nuxeo.com/) and contributors.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* (LGPL) version 2.1 which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl.html
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
*/
package org.nuxeo.ecm.platform.tag;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.persistence.EntityManager;
import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.nuxeo.common.utils.IdUtils;
import org.nuxeo.ecm.core.api.ClientException;
import org.nuxeo.ecm.core.api.CoreSession;
import org.nuxeo.ecm.core.api.DocumentModel;
import org.nuxeo.ecm.core.api.DocumentModelList;
import org.nuxeo.ecm.core.api.IdRef;
import org.nuxeo.ecm.core.api.UnrestrictedSessionRunner;
import org.nuxeo.ecm.core.api.impl.DocumentModelImpl;
import org.nuxeo.ecm.core.api.repository.RepositoryManager;
import org.nuxeo.ecm.core.persistence.HibernateConfiguration;
import org.nuxeo.ecm.core.persistence.HibernateConfigurator;
import org.nuxeo.ecm.core.persistence.PersistenceProvider;
import org.nuxeo.ecm.core.persistence.PersistenceProviderFactory;
import org.nuxeo.ecm.core.persistence.PersistenceProvider.RunCallback;
import org.nuxeo.ecm.core.persistence.PersistenceProvider.RunVoid;
import org.nuxeo.ecm.platform.tag.entity.DublincoreEntity;
import org.nuxeo.ecm.platform.tag.entity.TagEntity;
import org.nuxeo.ecm.platform.tag.entity.TaggingEntity;
import org.nuxeo.ecm.platform.tag.persistence.TagSchemaUpdater;
import org.nuxeo.ecm.platform.tag.persistence.TaggingProvider;
import org.nuxeo.runtime.api.Framework;
import org.nuxeo.runtime.model.ComponentContext;
import org.nuxeo.runtime.model.ComponentInstance;
import org.nuxeo.runtime.model.DefaultComponent;
import org.osgi.framework.FrameworkEvent;
import org.osgi.framework.FrameworkListener;
/**
* The implementation of tag service. For the API see {@link #TagService}
*
* @author rux
*/
public class TagServiceImpl extends DefaultComponent implements TagService,
TagConfigurator {
private static final Log log = LogFactory.getLog(TagServiceImpl.class);
private static Boolean enabled = null;
@Override
public void activate(ComponentContext context) throws Exception {
enabled = null;
context.getRuntimeContext().getBundle().getBundleContext().addFrameworkListener(
new FrameworkListener() {
public void frameworkEvent(FrameworkEvent event) {
if (event.getType() != FrameworkEvent.STARTED) {
return;
}
ClassLoader jbossCL = Thread.currentThread().getContextClassLoader();
ClassLoader nuxeoCL = TagServiceImpl.class.getClassLoader();
try {
// needs to be in Nuxeo ClassLoader to do a Login !
Thread.currentThread().setContextClassLoader(nuxeoCL);
if (isEnabled()) {
updateSchema();
}
}
finally {
Thread.currentThread().setContextClassLoader(jbossCL);
log.debug("JBoss ClassLoader restored");
}
}
});
TagServiceInitializer tagServiceInitializer = new TagServiceInitializer();
tagServiceInitializer.install();
}
protected void checkEnable() {
LoginContext lc = null;
try {
lc = Framework.login();
RepositoryManager rm = Framework.getService(RepositoryManager.class);
if (rm.getDefaultRepository().supportsTags()) {
log.info("Activating tag service");
enabled = true;
} else {
enabled = false;
log.warn("Default repository does not support Tag feature : Tag service won't be available.");
}
} catch (Exception e) {
enabled = false;
log.error("Unable to test repository for Tag feature.", e);
} finally {
if (lc != null) {
try {
lc.logout();
} catch (LoginException e) {
log.error("Error during Framework.logout", e);
}
}
}
}
@Override
public void deactivate(ComponentContext context) throws Exception {
deactivatePersistenceProvider();
super.deactivate(context);
}
@Override
public void registerContribution(Object contribution,
String extensionPoint, ComponentInstance contributor)
throws Exception {
if ("configs".equals(extensionPoint)) {
setConfig((TagConfig) contribution);
}
}
protected TagConfig config = new TagConfig();
public void setConfig(TagConfig config) {
this.config = config;
}
public TagConfig getConfig() {
return config;
}
protected PersistenceProvider persistenceProvider;
public PersistenceProvider getOrCreatePersistenceProvider() {
if (persistenceProvider != null) {
return persistenceProvider;
}
PersistenceProviderFactory persistenceProviderFactory = Framework.getLocalService(PersistenceProviderFactory.class);
persistenceProvider = persistenceProviderFactory.newProvider("nxtags");
return persistenceProvider;
}
protected void deactivatePersistenceProvider() {
if (persistenceProvider == null) {
return;
}
persistenceProvider.closePersistenceUnit();
persistenceProvider = null;
}
public DocumentModel getRootTag(final CoreSession session)
throws ClientException {
return getOrCreatePersistenceProvider().run(true,
new RunCallback<DocumentModel>() {
public DocumentModel runWith(EntityManager em)
throws ClientException {
return getRootTag(em, session);
}
});
}
public DocumentModel getRootTag(EntityManager em, CoreSession session)
throws ClientException {
if (log.isDebugEnabled()) {
log.debug("Going to look for root tag");
}
// use unrestricted session to get / create RootTag
UnrestrictedSessionCreateRootTag runner = new UnrestrictedSessionCreateRootTag(
session);
runner.runUnrestricted();
if (runner.rootTagDocumentId == null) {
throw new ClientException("Error creating the root tag document");
}
return session.getDocument(new IdRef(runner.rootTagDocumentId));
}
public void tagDocument(final CoreSession session,
final DocumentModel document, final String tagId,
final boolean privateFlag) throws ClientException {
getOrCreatePersistenceProvider().run(true, new RunVoid() {
public void runWith(EntityManager em) throws ClientException {
tagDocument(em, session, document, tagId, privateFlag);
}
});
}
public void tagDocument(EntityManager em, CoreSession session,
DocumentModel document, String tagId, boolean privateFlag)
throws ClientException {
if (null == document) {
throw new ClientException("Can't tag document null.");
}
TaggingProvider provider = TaggingProvider.createProvider(em);
TagEntity tagEntity = provider.getTagById(tagId);
if (tagEntity == null) {
throw new ClientException("Tag " + tagId + " doesn't exist");
}
if (log.isDebugEnabled()) {
log.debug("Going to tag document " + document.getTitle() + " with "
+ tagEntity.getLabel());
}
String user = getUserName(session);
// check if already tag applied
if (provider.existTagging(tagId, document.getId(), user)) {
log.warn(String.format(
"Tag %s already applied on %s by %s, don't create it",
tagEntity.getLabel(), document.getTitle(), user));
return;
}
TaggingEntity taggingEntry = new TaggingEntity();
String targetDocId = document.getId();
if (document.isProxy()) {
targetDocId = document.getSourceId();
}
DublincoreEntity dc = provider.getDcById(targetDocId);
taggingEntry.setId(IdUtils.generateStringId());
taggingEntry.setTag(tagEntity);
taggingEntry.setTargetDocument(dc);
taggingEntry.setCreationDate(new Date());
taggingEntry.setAuthor(user);
taggingEntry.setIsPrivate(privateFlag ? 1 : 0);
TaggingProvider.createProvider(em).addTagging(taggingEntry);
}
protected static String getUserName(CoreSession session)
throws ClientException {
if (session == null) {
throw new ClientException("No session available");
}
return session.getPrincipal().getName();
}
public DocumentModel getOrCreateTag(final CoreSession session,
final DocumentModel parent, final String label,
final boolean privateFlag) throws ClientException {
return getOrCreatePersistenceProvider().run(true,
new RunCallback<DocumentModel>() {
public DocumentModel runWith(EntityManager em)
throws ClientException {
return getOrCreateTag(em, session, parent, label,
privateFlag);
}
});
}
public DocumentModel getOrCreateTag(EntityManager em, CoreSession session,
DocumentModel parent, String label, boolean privateFlag)
throws ClientException {
if (parent == null) {
log.warn("Can't create tag in null parent");
throw new ClientException("Need a parent to create a tag");
}
if (log.isDebugEnabled()) {
log.debug("Going to look for label " + label);
}
UnrestrictedSessionCreateTag runner = new UnrestrictedSessionCreateTag(
session, parent, label, privateFlag);
runner.runUnrestricted();
if (runner.tagDocument == null) {
throw new ClientException("Error creating the tag document");
}
return runner.tagDocument;
}
public List<WeightedTag> getPopularCloud(final CoreSession session,
final DocumentModel document) throws ClientException {
return getOrCreatePersistenceProvider().run(false,
new RunCallback<List<WeightedTag>>() {
public List<WeightedTag> runWith(EntityManager em)
throws ClientException {
return getPopularCloud(em, session, document);
}
});
}
public List<WeightedTag> getPopularCloud(EntityManager em,
CoreSession session, DocumentModel document) throws ClientException {
// the NXSQL queries can't be used together with the native queries, for
// moment the queries are performed sequentially
if (null == document) {
throw new ClientException("Can't get cloud for domain null.");
}
if (log.isDebugEnabled()) {
log.debug("Going for popular cloud for " + document.getTitle());
}
String query = String.format(
"SELECT * FROM Document WHERE ecm:path STARTSWITH '%s' AND ecm:isProxy = %d",
document.getPathAsString(), config.isQueryingForProxy() ? 1 : 0);
UnrestrictedSessionRunQuery runner = new UnrestrictedSessionRunQuery(
session, query);
runner.runUnrestricted();
// add the current doc also
runner.result.add(document);
return TaggingProvider.createProvider(em).getPopularCloud(
runner.result, getUserName(session));
}
public List<WeightedTag> getPopularCloudOnAllDocuments(final CoreSession session) throws ClientException {
return getOrCreatePersistenceProvider().run(false,
new RunCallback<List<WeightedTag>>() {
public List<WeightedTag> runWith(EntityManager em)
throws ClientException {
return getPopularCloudOnAllDocuments(em, session);
}
});
}
public List<WeightedTag> getPopularCloudOnAllDocuments(EntityManager em,
CoreSession session) throws ClientException {
return TaggingProvider.createProvider(em).getPopularCloudOnAllDocuments(getUserName(session));
}
public WeightedTag getPopularTag(final CoreSession session,
final DocumentModel document, final String tagId)
throws ClientException {
return getOrCreatePersistenceProvider().run(false,
new RunCallback<WeightedTag>() {
public WeightedTag runWith(EntityManager em)
throws ClientException {
return getPopularTag(em, session, document, tagId);
}
});
}
public WeightedTag getPopularTag(EntityManager em, CoreSession session,
DocumentModel document, String tagId) throws ClientException {
if (null == document || null == tagId) {
throw new ClientException(
"Can't get popular for document or tag null.");
}
String user = getUserName(session);
DocumentModel tag = session.getDocument(new IdRef(tagId));
if (log.isDebugEnabled()) {
log.debug("Going to look for popularity of " + tag.getTitle()
+ " for " + document.getTitle());
}
if (!isTagAllowed(tag, user)) {
log.warn("Tag " + tag.getTitle() + " not allowed for " + user);
return new WeightedTag(tag.getId(), tag.getTitle(), 0);
}
// TODO int weight =
// getTaggingProvider().getPopularTag(document.getId(), tag.getId(),
// user);
return new WeightedTag(tag.getId(),
(String) tag.getPropertyValue(TagConstants.TAG_LABEL_FIELD), 0);
}
public List<WeightedTag> getVoteCloud(final CoreSession session,
final DocumentModel document) throws ClientException {
return getOrCreatePersistenceProvider().run(false,
new RunCallback<List<WeightedTag>>() {
public List<WeightedTag> runWith(EntityManager em)
throws ClientException {
return getVoteCloud(em, session, document);
}
});
}
public List<WeightedTag> getVoteCloud(EntityManager em,
CoreSession session, DocumentModel document) throws ClientException {
throw new UnsupportedOperationException();
}
public WeightedTag getVoteTag(final CoreSession session,
final DocumentModel document, final String tagId)
throws ClientException {
return getOrCreatePersistenceProvider().run(false,
new RunCallback<WeightedTag>() {
public WeightedTag runWith(EntityManager em)
throws ClientException {
return getVoteTag(em, session, document, tagId);
}
});
}
public WeightedTag getVoteTag(EntityManager em, CoreSession session,
DocumentModel document, String tagId) throws ClientException {
if (null == document) {
throw new ClientException(
"Can't get list of documents from domain null.");
}
String user = getUserName(session);
DocumentModel tag = session.getDocument(new IdRef(tagId));
if (log.isDebugEnabled()) {
log.debug("Going to look for votes of " + tag.getTitle() + " for "
+ document.getTitle());
}
if (!isTagAllowed(tag, user)) {
log.warn("Tag " + tag.getTitle() + " not allowed for " + user);
return new WeightedTag(tag.getId(), tag.getTitle(), 0);
}
TaggingProvider taggingProvider = TaggingProvider.createProvider(em);
Long result = taggingProvider.getVoteTag(document.getId(), tag.getId(),
user);
return new WeightedTag(tag.getId(),
(String) tag.getPropertyValue(TagConstants.TAG_LABEL_FIELD),
result.intValue());
}
public List<Tag> listTagsAppliedOnDocument(final CoreSession session,
final DocumentModel document) throws ClientException {
return getOrCreatePersistenceProvider().run(false,
new RunCallback<List<Tag>>() {
public List<Tag> runWith(EntityManager em)
throws ClientException {
return listTagsAppliedOnDocument(em, session, document);
}
});
}
public List<Tag> listTagsAppliedOnDocument(EntityManager em,
CoreSession session, DocumentModel document) throws ClientException {
if (null == document) {
throw new ClientException("Can't get list of tags from group null.");
}
if (log.isDebugEnabled()) {
log.debug("Going to look for tags applied on "
+ document.getTitle());
}
return TaggingProvider.createProvider(em).listTagsForDocument(
document.getId(), getUserName(session));
}
public List<Tag> listTagsAppliedOnDocumentByUser(final CoreSession session,
final DocumentModel document) throws ClientException {
return getOrCreatePersistenceProvider().run(false,
new RunCallback<List<Tag>>() {
public List<Tag> runWith(EntityManager em)
throws ClientException {
return listTagsAppliedOnDocumentByUser(em, session,
document);
}
});
}
public List<Tag> listTagsAppliedOnDocumentByUser(EntityManager em,
CoreSession session, DocumentModel document) throws ClientException {
if (null == document) {
throw new ClientException("Can't get list of tags from group null.");
}
if (log.isDebugEnabled()) {
log.debug("Going to look only current user tags applied on "
+ document.getTitle());
}
return TaggingProvider.createProvider(em).listTagsForDocumentAndUser(
document.getId(), getUserName(session));
}
public DocumentModelList listTagsInGroup(final CoreSession session,
final DocumentModel tag) throws ClientException {
return getOrCreatePersistenceProvider().run(false,
new RunCallback<DocumentModelList>() {
public DocumentModelList runWith(EntityManager em)
throws ClientException {
return listTagsInGroup(em, session, tag);
}
});
}
public DocumentModelList listTagsInGroup(final DocumentModel tag)
throws ClientException {
return listTagsInGroup(tag.getCoreSession(), tag);
}
public DocumentModelList listTagsInGroup(EntityManager em,
CoreSession session, DocumentModel tag) throws ClientException {
if (null == tag) {
throw new ClientException("Can't get list of tags from group null.");
}
if (log.isDebugEnabled()) {
log.debug("Going to list tags in " + tag.getTitle());
}
String user = getUserName(session);
String query = String.format(
"SELECT * FROM Tag WHERE ecm:path STARTSWITH '%s' AND (tag:private = 0 or dc:creator = '%s') AND ecm:isProxy = %d",
tag.getPathAsString(), user, config.isQueryingForProxy() ? 1
: 0);
UnrestrictedSessionRunQuery runner = new UnrestrictedSessionRunQuery(
session, query);
runner.runUnrestricted();
return runner.result;
}
public void untagDocument(final CoreSession session,
final DocumentModel document, final String tagId)
throws ClientException {
getOrCreatePersistenceProvider().run(true, new RunVoid() {
public void runWith(EntityManager em) throws ClientException {
untagDocument(em, session, document, tagId);
}
});
}
public void untagDocument(EntityManager em, CoreSession session,
DocumentModel document, String tagId) throws ClientException {
if (null == document || tagId == null) {
throw new ClientException("Can't untag document or tag null.");
}
if (log.isDebugEnabled()) {
log.debug("Going to untag " + tagId + " for " + document.getTitle());
}
TaggingProvider.createProvider(em).removeTagging(document.getId(),
tagId, getUserName(session));
}
public void completeUntagDocument(final CoreSession session,
final DocumentModel document, final String tagId)
throws ClientException {
getOrCreatePersistenceProvider().run(true, new RunVoid() {
public void runWith(EntityManager em) throws ClientException {
completeUntagDocument(em, session, document, tagId);
}
});
}
public void completeUntagDocument(EntityManager em, CoreSession session,
DocumentModel document, String tagId) throws ClientException {
if (null == document || tagId == null) {
throw new ClientException("Can't untag document or tag null.");
}
if (log.isDebugEnabled()) {
log.debug("Going to untag " + tagId + " for " + document.getTitle());
}
TaggingProvider.createProvider(em).removeAllTagging(document.getId(),
tagId);
}
public List<String> listDocumentsForTag(final CoreSession session,
final String tagId, final String user) throws ClientException {
return getOrCreatePersistenceProvider().run(true,
new RunCallback<List<String>>() {
public List<String> runWith(EntityManager em)
throws ClientException {
return listDocumentsForTag(em, session, tagId, user);
}
});
}
public List<String> listDocumentsForTag(EntityManager em,
CoreSession session, String tagId, String user)
throws ClientException {
if (null == tagId) {
throw new ClientException(
"Can't get list of documents for tag null.");
}
return TaggingProvider.createProvider(em).getDocumentsForTag(tagId,
user);
}
/**
* Checks if the tag is allowed to be used by the user.
*/
protected static boolean isTagAllowed(DocumentModel tag, String user)
throws ClientException {
if (tag == null) {
throw new ClientException(
"Can't get list of documents from tag null.");
}
Long isPrivate = (Long) tag.getPropertyValue(TagConstants.TAG_IS_PRIVATE_FIELD);
if (isPrivate == null || isPrivate == 0) {
return true;
}
String owner = (String) tag.getPropertyValue("dc:creator");
return user != null && user.equals(owner);
}
/**
* The unrestricted session runner to find / create root tag document.
*
* @author rux
*/
protected static class UnrestrictedSessionCreateRootTag extends
UnrestrictedSessionRunner {
public UnrestrictedSessionCreateRootTag(CoreSession session) {
super(session);
rootTagDocumentId = null;
}
// need to return somehow the result
public String rootTagDocumentId;
@Override
public void run() throws ClientException {
DocumentModel documentRoot = session.getRootDocument();
DocumentModelList rootHiddenChildren = session.getChildren(
documentRoot.getRef(), TagConstants.HIDDEN_FOLDER_TYPE);
if (null != rootHiddenChildren) {
for (DocumentModel hiddenFolder : rootHiddenChildren) {
if (TagConstants.TAGS_DIRECTORY.equals(hiddenFolder.getTitle())) {
rootTagDocumentId = hiddenFolder.getId();
return;
}
}
}
}
}
/**
* The unrestricted runner to find / create a tag document.
*
* @author rux
*/
protected class UnrestrictedSessionCreateTag extends
UnrestrictedSessionRunner {
// need to return somehow the result
public DocumentModel tagDocument;
// and to store the arguments
private final DocumentModel parent;
private final String label;
private final String user;
private final boolean privateFlag;
public UnrestrictedSessionCreateTag(CoreSession session,
DocumentModel parent, String label, boolean privateFlag)
throws ClientException {
super(session);
this.parent = parent;
tagDocument = null;
this.label = label;
user = TagServiceImpl.getUserName(session);
this.privateFlag = privateFlag;
}
@Override
public void run() throws ClientException {
// label can be in fact a composed label: labels separated by /
String[] labels = label.split("/");
DocumentModel relativeParent = parent;
for (String atomicLabel : labels) {
// for each label look for a public or user owned tag. If not,
// create it
String query = String.format(
"SELECT * FROM Tag WHERE ecm:parentId = '%s' AND tag:label = '%s' AND ecm:isProxy = %d",
relativeParent.getId(), atomicLabel,
config.queryProxy ? 1 : 0);
DocumentModelList tags = session.query(query);
DocumentModel foundTag = null;
if (tags != null && tags.size() > 0) {
// it should be only one, but it is possible to have more
// than one tag with the specified label in a group. Need to
// check the flag / user
for (DocumentModel aTag : tags) {
Long isPrivate = (Long) aTag.getPropertyValue(TagConstants.TAG_IS_PRIVATE_FIELD);
if (isPrivate == null || isPrivate == 0) {
// public tag, should be ok
foundTag = aTag;
break;
}
String tagUser = (String) aTag.getPropertyValue("dc:creator");
if (user.equals(tagUser)) {
// it pertains to this user
foundTag = aTag;
break;
}
}
}
if (foundTag != null) {
relativeParent = foundTag;
} else {
// couldn't find the tag, create it
relativeParent = createTagModel(session, relativeParent,
atomicLabel, user, privateFlag);
}
}
// and set ID for retrieval
tagDocument = relativeParent;
((DocumentModelImpl) tagDocument).detach(true);
}
}
/**
* The unrestricted runner for running a query.
*
* @author rux
*/
protected static class UnrestrictedSessionRunQuery extends
UnrestrictedSessionRunner {
// need to have somehow result
public DocumentModelList result;
// need to provide somehow the arguments
private final String query;
public UnrestrictedSessionRunQuery(CoreSession session, String query) {
super(session);
this.query = query;
result = null;
}
@Override
public void run() throws ClientException {
result = session.query(query);
}
}
protected static DocumentModel createTagModel(CoreSession session,
DocumentModel parent, String label, String user, boolean privateFlag)
throws ClientException {
DocumentModel tagDocument = session.createDocumentModel(
parent.getPathAsString(), IdUtils.generateId(label), "Tag");
tagDocument = session.createDocument(tagDocument);
tagDocument.setPropertyValue("dc:title", label);
tagDocument.setPropertyValue("dc:description", "");
tagDocument.setPropertyValue("dc:created", Calendar.getInstance());
tagDocument.setPropertyValue("dc:creator", user);
tagDocument.setPropertyValue(TagConstants.TAG_LABEL_FIELD, label);
tagDocument.setPropertyValue(TagConstants.TAG_IS_PRIVATE_FIELD,
privateFlag ? 1 : 0);
tagDocument = session.saveDocument(tagDocument);
session.save();
return tagDocument;
}
public String getTaggingId(final CoreSession session, final String docId,
final String tagLabel, final String author) throws ClientException {
return getOrCreatePersistenceProvider().run(false,
new RunCallback<String>() {
public String runWith(EntityManager em)
throws ClientException {
return getTaggingId(em, session, docId, tagLabel,
author);
}
});
}
public String getTaggingId(EntityManager em, CoreSession session,
String docId, String tagLabel, String author) {
return TaggingProvider.createProvider(em).getTaggingId(docId, tagLabel,
author);
}
public void updateSchema() {
HibernateConfigurator configurator = Framework.getLocalService(HibernateConfigurator.class);
HibernateConfiguration configuration = configurator.getHibernateConfiguration("nxtags");
TagSchemaUpdater updater = new TagSchemaUpdater(
configuration.hibernateProperties);
updater.update();
}
public boolean isEnabled() {
if (enabled == null) {
checkEnable();
}
return enabled;
}
}
| NXP-4973: fix tagging for administrators
| nuxeo-platform-tag-service/nuxeo-platform-tag-core/src/main/java/org/nuxeo/ecm/platform/tag/TagServiceImpl.java | NXP-4973: fix tagging for administrators | <ide><path>uxeo-platform-tag-service/nuxeo-platform-tag-core/src/main/java/org/nuxeo/ecm/platform/tag/TagServiceImpl.java
<ide> protected static class UnrestrictedSessionCreateRootTag extends
<ide> UnrestrictedSessionRunner {
<ide> public UnrestrictedSessionCreateRootTag(CoreSession session) {
<del> super(session);
<add> super(session.getRepositoryName()); // always open new session
<ide> rootTagDocumentId = null;
<ide> }
<ide>
<ide> public UnrestrictedSessionCreateTag(CoreSession session,
<ide> DocumentModel parent, String label, boolean privateFlag)
<ide> throws ClientException {
<del> super(session);
<add> super(session.getRepositoryName()); // always open new session
<ide> this.parent = parent;
<ide> tagDocument = null;
<ide> this.label = label; |
|
Java | bsd-2-clause | 59e769f048367bcb37f0b5ed6fdd69d0730ca76f | 0 | malensek/elssa,malensek/galileo-net | package io.elssa.net;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
public class ServerMessageRouter extends MessageRouterBase {
private EventLoopGroup bossGroup;
private EventLoopGroup workerGroup;
private ServerBootstrap bootstrap;
private MessagePipeline pipeline;
private Map<Integer, ChannelFuture> ports = new HashMap<>();
public ServerMessageRouter() {
bossGroup = new NioEventLoopGroup();
workerGroup = new NioEventLoopGroup(4);
pipeline = new MessagePipeline(this);
bootstrap = new ServerBootstrap()
.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(pipeline)
.option(ChannelOption.SO_BACKLOG, 128)
.childOption(ChannelOption.SO_KEEPALIVE, true);
}
public ServerMessageRouter(int readBufferSize, int maxWriteQueueSize) {
this();
}
/**
* Begins listening for incoming messages on the specified port. When this
* method returns, the server socket is open and ready to accept
* connections.
*
* @param port The port to listen on
*/
public void listen(int port) {
ChannelFuture cf = bootstrap.bind(port).syncUninterruptibly();
ports.put(port, cf);
}
public void close(int port) {
ChannelFuture cf = ports.get(port);
if (cf == null) {
return;
}
ports.remove(port);
cf.channel().disconnect().syncUninterruptibly();
}
/**
* Closes the server socket channel and stops processing incoming
* messages.
*/
public void shutdown() throws IOException {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
for (ChannelFuture cf : ports.values()) {
cf.channel().close().syncUninterruptibly();
}
}
}
| src/main/java/io/elssa/net/ServerMessageRouter.java | package io.elssa.net;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
public class ServerMessageRouter extends MessageRouterBase {
private static final Logger logger
= LoggerFactory.getLogger(ServerMessageRouter.class);
private EventLoopGroup bossGroup;
private EventLoopGroup workerGroup;
private ServerBootstrap bootstrap;
private MessagePipeline pipeline;
private Map<Integer, ChannelFuture> ports = new HashMap<>();
public ServerMessageRouter() {
bossGroup = new NioEventLoopGroup();
workerGroup = new NioEventLoopGroup(4);
pipeline = new MessagePipeline(this);
bootstrap = new ServerBootstrap()
.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(pipeline)
.option(ChannelOption.SO_BACKLOG, 128)
.childOption(ChannelOption.SO_KEEPALIVE, true);
}
public ServerMessageRouter(int readBufferSize, int maxWriteQueueSize) {
this();
}
public void listen(int port) {
ChannelFuture cf = bootstrap.bind(port).syncUninterruptibly();
ports.put(port, cf);
logger.info("Listening on port {}", port);
}
public void close(int port) {
ChannelFuture cf = ports.get(port);
if (cf == null) {
return;
}
ports.remove(port);
cf.channel().disconnect().syncUninterruptibly();
}
/**
* Closes the server socket channel and stops processing incoming
* messages.
*/
public void shutdown() throws IOException {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
for (ChannelFuture cf : ports.values()) {
cf.channel().close().syncUninterruptibly();
}
}
}
| Remove logger statements and update documentation
Eventually, logging will not be performed at this level;
exceptions and state updates will be used to keep
applications informed.
| src/main/java/io/elssa/net/ServerMessageRouter.java | Remove logger statements and update documentation | <ide><path>rc/main/java/io/elssa/net/ServerMessageRouter.java
<ide> import java.io.IOException;
<ide> import java.util.HashMap;
<ide> import java.util.Map;
<del>
<del>import org.slf4j.Logger;
<del>import org.slf4j.LoggerFactory;
<ide>
<ide> import io.netty.bootstrap.ServerBootstrap;
<ide> import io.netty.channel.ChannelFuture;
<ide> import io.netty.channel.socket.nio.NioServerSocketChannel;
<ide>
<ide> public class ServerMessageRouter extends MessageRouterBase {
<del>
<del> private static final Logger logger
<del> = LoggerFactory.getLogger(ServerMessageRouter.class);
<ide>
<ide> private EventLoopGroup bossGroup;
<ide> private EventLoopGroup workerGroup;
<ide> this();
<ide> }
<ide>
<add> /**
<add> * Begins listening for incoming messages on the specified port. When this
<add> * method returns, the server socket is open and ready to accept
<add> * connections.
<add> *
<add> * @param port The port to listen on
<add> */
<ide> public void listen(int port) {
<ide> ChannelFuture cf = bootstrap.bind(port).syncUninterruptibly();
<ide> ports.put(port, cf);
<del> logger.info("Listening on port {}", port);
<ide> }
<ide>
<ide> public void close(int port) { |
|
Java | apache-2.0 | ec106fc5a9f507ae7d5be6b06b92be33bc7bde54 | 0 | newkek/incubator-tinkerpop,apache/tinkerpop,robertdale/tinkerpop,jorgebay/tinkerpop,BrynCooke/incubator-tinkerpop,jorgebay/tinkerpop,pluradj/incubator-tinkerpop,krlohnes/tinkerpop,krlohnes/tinkerpop,apache/incubator-tinkerpop,apache/tinkerpop,BrynCooke/incubator-tinkerpop,newkek/incubator-tinkerpop,robertdale/tinkerpop,artem-aliev/tinkerpop,artem-aliev/tinkerpop,pluradj/incubator-tinkerpop,apache/tinkerpop,artem-aliev/tinkerpop,robertdale/tinkerpop,robertdale/tinkerpop,apache/tinkerpop,krlohnes/tinkerpop,jorgebay/tinkerpop,BrynCooke/incubator-tinkerpop,apache/incubator-tinkerpop,artem-aliev/tinkerpop,robertdale/tinkerpop,apache/tinkerpop,apache/tinkerpop,apache/incubator-tinkerpop,pluradj/incubator-tinkerpop,artem-aliev/tinkerpop,krlohnes/tinkerpop,samiunn/incubator-tinkerpop,apache/tinkerpop,krlohnes/tinkerpop,samiunn/incubator-tinkerpop,samiunn/incubator-tinkerpop,jorgebay/tinkerpop,newkek/incubator-tinkerpop | /*
* 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.tinkerpop.gremlin.process.traversal.step.map;
import org.apache.tinkerpop.gremlin.LoadGraphWith;
import org.apache.tinkerpop.gremlin.process.AbstractGremlinProcessTest;
import org.apache.tinkerpop.gremlin.process.GremlinProcessRunner;
import org.apache.tinkerpop.gremlin.process.traversal.Traversal;
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.structure.VertexProperty;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import static org.apache.tinkerpop.gremlin.LoadGraphWith.GraphData.MODERN;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* @author Marko A. Rodriguez (http://markorodriguez.com)
*/
@RunWith(GremlinProcessRunner.class)
public abstract class PropertiesTest extends AbstractGremlinProcessTest {
public abstract Traversal<Vertex, Object> get_g_V_hasXageX_propertiesXname_ageX_value();
public abstract Traversal<Vertex, Object> get_g_V_hasXageX_propertiesXage_nameX_value();
public abstract Traversal<Vertex, Object> get_g_V_hasXageX_properties_hasXid_nameIdX_value(final Object nameId);
public abstract Traversal<Vertex, VertexProperty<String>> get_g_V_hasXageX_propertiesXnameX();
@Test
@LoadGraphWith(MODERN)
public void g_V_hasXageX_propertiesXname_ageX_value() {
final Traversal<Vertex, Object> traversal = get_g_V_hasXageX_propertiesXname_ageX_value();
printTraversalForm(traversal);
checkResults(Arrays.asList("marko", 29, "vadas", 27, "josh", 32, "peter", 35), traversal);
}
@Test
@LoadGraphWith(MODERN)
public void g_V_hasXageX_propertiesXage_nameX_value() {
final Traversal<Vertex, Object> traversal = get_g_V_hasXageX_propertiesXage_nameX_value();
printTraversalForm(traversal);
checkResults(Arrays.asList("marko", 29, "vadas", 27, "josh", 32, "peter", 35), traversal);
}
@Test
@LoadGraphWith(MODERN)
public void g_V_hasXageX_properties_hasXid_nameIdX_value() {
final Traversal<Vertex, Object> traversal = get_g_V_hasXageX_properties_hasXid_nameIdX_value(convertToVertexPropertyId("marko", "name").next());
printTraversalForm(traversal);
checkResults(Collections.singletonList("marko"), traversal);
}
@Test
@LoadGraphWith(MODERN)
public void g_V_hasXageX_properties_hasXid_nameIdAsStringX_value() {
final Traversal<Vertex, Object> traversal = get_g_V_hasXageX_properties_hasXid_nameIdX_value(convertToVertexPropertyId("marko", "name").next().toString());
printTraversalForm(traversal);
checkResults(Collections.singletonList("marko"), traversal);
}
@Test
@LoadGraphWith(MODERN)
public void g_V_hasXageX_propertiesXnameX() {
final Traversal<Vertex, VertexProperty<String>> traversal = get_g_V_hasXageX_propertiesXnameX();
printTraversalForm(traversal);
final Set<String> keys = new HashSet<>();
final Set<String> values = new HashSet<>();
final Set<Object> ids = new HashSet<>();
int counter = 0;
while (traversal.hasNext()) {
counter++;
final VertexProperty<String> vertexProperty = traversal.next();
keys.add(vertexProperty.key());
values.add(vertexProperty.value());
ids.add(vertexProperty.id());
assertEquals("name", vertexProperty.key());
assertEquals(convertToVertex(graph, vertexProperty.value()).values("name").next(), vertexProperty.value());
assertEquals(convertToVertex(graph, vertexProperty.value()).properties("name").next().id(), vertexProperty.id());
// assertEquals(convertToVertex(graph, vertexProperty.value()), vertexProperty.element());
// assertEquals(convertToVertexId(graph, vertexProperty.value()), vertexProperty.element().id());
}
assertEquals(4, counter);
assertEquals(1, keys.size());
assertTrue(keys.contains("name"));
assertEquals(4, values.size());
assertTrue(values.contains("marko"));
assertTrue(values.contains("vadas"));
assertTrue(values.contains("josh"));
assertTrue(values.contains("peter"));
assertEquals(4, ids.size());
}
public static class Traversals extends PropertiesTest {
@Override
public Traversal<Vertex, Object> get_g_V_hasXageX_propertiesXname_ageX_value() {
return g.V().has("age").properties("name", "age").value();
}
@Override
public Traversal<Vertex, Object> get_g_V_hasXageX_propertiesXage_nameX_value() {
return g.V().has("age").properties("age", "name").value();
}
@Override
public Traversal<Vertex, Object> get_g_V_hasXageX_properties_hasXid_nameIdX_value(final Object nameId) {
return g.V().has("age").properties().has(T.id, nameId).value();
}
@Override
public Traversal<Vertex, VertexProperty<String>> get_g_V_hasXageX_propertiesXnameX() {
return (Traversal<Vertex, VertexProperty<String>>) g.V().has("age").<String>properties("name");
}
}
}
| gremlin-test/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/PropertiesTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.tinkerpop.gremlin.process.traversal.step.map;
import org.apache.tinkerpop.gremlin.LoadGraphWith;
import org.apache.tinkerpop.gremlin.process.AbstractGremlinProcessTest;
import org.apache.tinkerpop.gremlin.process.GremlinProcessRunner;
import org.apache.tinkerpop.gremlin.process.traversal.Traversal;
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.structure.VertexProperty;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import static org.apache.tinkerpop.gremlin.LoadGraphWith.GraphData.MODERN;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* @author Marko A. Rodriguez (http://markorodriguez.com)
*/
@RunWith(GremlinProcessRunner.class)
public abstract class PropertiesTest extends AbstractGremlinProcessTest {
public abstract Traversal<Vertex, Object> get_g_V_hasXageX_propertiesXname_ageX_value();
public abstract Traversal<Vertex, Object> get_g_V_hasXageX_propertiesXage_nameX_value();
public abstract Traversal<Vertex, Object> get_g_V_hasXageX_properties_hasXid_nameIdX_value(final Object nameId);
public abstract Traversal<Vertex, VertexProperty<String>> get_g_V_hasXageX_propertiesXnameX();
@Test
@LoadGraphWith(MODERN)
public void g_V_hasXageX_propertiesXname_ageX_value() {
final Traversal<Vertex, Object> traversal = get_g_V_hasXageX_propertiesXname_ageX_value();
printTraversalForm(traversal);
checkResults(Arrays.asList("marko", 29, "vadas", 27, "josh", 32, "peter", 35), traversal);
}
@Test
@LoadGraphWith(MODERN)
public void g_V_hasXageX_propertiesXage_nameX_value() {
final Traversal<Vertex, Object> traversal = get_g_V_hasXageX_propertiesXage_nameX_value();
printTraversalForm(traversal);
checkResults(Arrays.asList("marko", 29, "vadas", 27, "josh", 32, "peter", 35), traversal);
}
@Test
@LoadGraphWith(MODERN)
public void g_V_hasXageX_properties_hasXid_nameIdX_value() {
final Traversal<Vertex, Object> traversal = get_g_V_hasXageX_properties_hasXid_nameIdX_value(convertToVertexPropertyId("marko", "name").next());
printTraversalForm(traversal);
checkResults(Collections.singletonList("marko"), traversal);
}
@Test
@LoadGraphWith(MODERN)
public void g_V_hasXageX_properties_hasXid_nameIdAsStringX_value() {
final Traversal<Vertex, Object> traversal = get_g_V_hasXageX_properties_hasXid_nameIdX_value(convertToVertexPropertyId("marko", "name").next().toString());
printTraversalForm(traversal);
checkResults(Collections.singletonList("marko"), traversal);
}
@Test
@LoadGraphWith(MODERN)
public void g_V_hasXageX_propertiesXnameX() {
final Traversal<Vertex, VertexProperty<String>> traversal = get_g_V_hasXageX_propertiesXnameX();
printTraversalForm(traversal);
final Set<String> keys = new HashSet<>();
final Set<String> values = new HashSet<>();
final Set<Object> ids = new HashSet<>();
int counter = 0;
while (traversal.hasNext()) {
counter++;
final VertexProperty<String> vertexProperty = traversal.next();
keys.add(vertexProperty.key());
values.add(vertexProperty.value());
ids.add(vertexProperty.id());
assertEquals("name", vertexProperty.key());
assertEquals(convertToVertex(graph, vertexProperty.value()).values("name").next(), vertexProperty.value());
assertEquals(convertToVertex(graph, vertexProperty.value()).properties("name").next().id(), vertexProperty.id());
assertEquals(convertToVertex(graph, vertexProperty.value()), vertexProperty.element());
assertEquals(convertToVertexId(graph, vertexProperty.value()), vertexProperty.element().id());
}
assertEquals(4, counter);
assertEquals(1, keys.size());
assertTrue(keys.contains("name"));
assertEquals(4, values.size());
assertTrue(values.contains("marko"));
assertTrue(values.contains("vadas"));
assertTrue(values.contains("josh"));
assertTrue(values.contains("peter"));
assertEquals(4, ids.size());
}
public static class Traversals extends PropertiesTest {
@Override
public Traversal<Vertex, Object> get_g_V_hasXageX_propertiesXname_ageX_value() {
return g.V().has("age").properties("name", "age").value();
}
@Override
public Traversal<Vertex, Object> get_g_V_hasXageX_propertiesXage_nameX_value() {
return g.V().has("age").properties("age", "name").value();
}
@Override
public Traversal<Vertex, Object> get_g_V_hasXageX_properties_hasXid_nameIdX_value(final Object nameId) {
return g.V().has("age").properties().has(T.id, nameId).value();
}
@Override
public Traversal<Vertex, VertexProperty<String>> get_g_V_hasXageX_propertiesXnameX() {
return (Traversal<Vertex, VertexProperty<String>>) g.V().has("age").<String>properties("name");
}
}
}
| so strange. I knew this didn't work, but the tests passed locally and now they don't. I think I had some cached classes or something weird -- sorry for the broken tp31/ build. CTR.
| gremlin-test/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/PropertiesTest.java | so strange. I knew this didn't work, but the tests passed locally and now they don't. I think I had some cached classes or something weird -- sorry for the broken tp31/ build. CTR. | <ide><path>remlin-test/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/PropertiesTest.java
<ide> assertEquals("name", vertexProperty.key());
<ide> assertEquals(convertToVertex(graph, vertexProperty.value()).values("name").next(), vertexProperty.value());
<ide> assertEquals(convertToVertex(graph, vertexProperty.value()).properties("name").next().id(), vertexProperty.id());
<del> assertEquals(convertToVertex(graph, vertexProperty.value()), vertexProperty.element());
<del> assertEquals(convertToVertexId(graph, vertexProperty.value()), vertexProperty.element().id());
<add> // assertEquals(convertToVertex(graph, vertexProperty.value()), vertexProperty.element());
<add> // assertEquals(convertToVertexId(graph, vertexProperty.value()), vertexProperty.element().id());
<ide> }
<ide> assertEquals(4, counter);
<ide> assertEquals(1, keys.size()); |
|
Java | apache-2.0 | 68a6deeaef61e030f2767452e67fb63990093bba | 0 | majorseitan/dataverse,bmckinney/dataverse-canonical,ekoi/DANS-DVN-4.6.1,quarian/dataverse,bmckinney/dataverse-canonical,jacksonokuhn/dataverse,leeper/dataverse-1,jacksonokuhn/dataverse,bmckinney/dataverse-canonical,leeper/dataverse-1,jacksonokuhn/dataverse,bmckinney/dataverse-canonical,leeper/dataverse-1,leeper/dataverse-1,JayanthyChengan/dataverse,JayanthyChengan/dataverse,leeper/dataverse-1,quarian/dataverse,JayanthyChengan/dataverse,quarian/dataverse,quarian/dataverse,leeper/dataverse-1,ekoi/DANS-DVN-4.6.1,jacksonokuhn/dataverse,majorseitan/dataverse,jacksonokuhn/dataverse,quarian/dataverse,majorseitan/dataverse,JayanthyChengan/dataverse,leeper/dataverse-1,JayanthyChengan/dataverse,ekoi/DANS-DVN-4.6.1,ekoi/DANS-DVN-4.6.1,quarian/dataverse,majorseitan/dataverse,JayanthyChengan/dataverse,bmckinney/dataverse-canonical,majorseitan/dataverse,ekoi/DANS-DVN-4.6.1,bmckinney/dataverse-canonical,jacksonokuhn/dataverse,leeper/dataverse-1,JayanthyChengan/dataverse,majorseitan/dataverse,JayanthyChengan/dataverse,majorseitan/dataverse,ekoi/DANS-DVN-4.6.1,bmckinney/dataverse-canonical,majorseitan/dataverse,bmckinney/dataverse-canonical,ekoi/DANS-DVN-4.6.1,ekoi/DANS-DVN-4.6.1,quarian/dataverse,quarian/dataverse,jacksonokuhn/dataverse,jacksonokuhn/dataverse | package edu.harvard.iq.dataverse.authorization.groups.impl.explicit;
import edu.harvard.iq.dataverse.DvObject;
import edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser;
import edu.harvard.iq.dataverse.authorization.groups.Group;
import edu.harvard.iq.dataverse.authorization.RoleAssignee;
import edu.harvard.iq.dataverse.authorization.RoleAssigneeDisplayInfo;
import edu.harvard.iq.dataverse.authorization.users.User;
import edu.harvard.iq.dataverse.authorization.groups.GroupException;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import java.util.TreeSet;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Index;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.PostLoad;
import javax.persistence.PrePersist;
import javax.persistence.Table;
import javax.persistence.Transient;
import javax.validation.constraints.Pattern;
import org.hibernate.validator.constraints.NotBlank;
/**
* A group that explicitly lists {@link RoleAssignee}s that belong to it. Implementation-wise,
* there are three cases here: {@link AuthenticatedUser}s, other {@link ExplicitGroup}s, and all the rest.
* AuthenticatedUsers and ExplicitGroups go in tables of their own. The rest are kept via their identifier.
*
* @author michael
*/
@NamedQueries({
@NamedQuery( name="ExplicitGroup.findAll",
query="SELECT eg FROM ExplicitGroup eg"),
@NamedQuery( name="ExplicitGroup.findByOwnerIdAndAlias",
query="SELECT eg FROM ExplicitGroup eg WHERE eg.owner.id=:ownerId AND eg.groupAliasInOwner=:alias"),
@NamedQuery( name="ExplicitGroup.findByAlias",
query="SELECT eg FROM ExplicitGroup eg WHERE eg.groupAlias=:alias"),
@NamedQuery( name="ExplicitGroup.findByOwnerId",
query="SELECT eg FROM ExplicitGroup eg WHERE eg.owner.id=:ownerId"),
@NamedQuery( name="ExplicitGroup.findByOwnerAndAuthUserId",
query="SELECT eg FROM ExplicitGroup eg join eg.containedAuthenticatedUsers au "
+"WHERE eg.owner.id=:ownerId AND au.id=:authUserId"),
@NamedQuery( name="ExplicitGroup.findByOwnerAndSubExGroupId",
query="SELECT eg FROM ExplicitGroup eg join eg.containedExplicitGroups ceg "
+"WHERE eg.owner.id=:ownerId AND ceg.id=:subExGroupId"),
@NamedQuery( name="ExplicitGroup.findByOwnerAndRAIdtf",
query="SELECT eg FROM ExplicitGroup eg join eg.containedRoleAssignees ra "
+"WHERE eg.owner.id=:ownerId AND ra=:raIdtf")
})
@Entity
@Table(indexes = {@Index(columnList="owner_id")
//, @Index(columnList="groupalias") //@unique takes care of this
, @Index(columnList="groupaliasinowner")})
public class ExplicitGroup implements Group, java.io.Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
Long id;
/**
* Authenticated users directly added to the group.
*/
@ManyToMany
private Set<AuthenticatedUser> containedAuthenticatedUsers;
/**
* Explicit groups that belong to {@code this} explicit gorups.
*/
@ManyToMany
@JoinTable(name = "explicitgroup_explicitgroup",
joinColumns = @JoinColumn(name="explicitgroup_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name="containedexplicitgroups_id", referencedColumnName = "id") )
Set<ExplicitGroup> containedExplicitGroups;
/**
* All the role assignees that belong to this group
* and are not {@link authenticatedUser}s or {@ExplicitGroup}s, are stored
* here via their identifiers.
*
* @see RoleAssignee#getIdentifier()
*/
@ElementCollection
private Set<String> containedRoleAssignees;
@Column( length = 1024 )
private String description;
@NotBlank
private String displayName;
/**
* The DvObject under which this group is defined.
*/
@ManyToOne
DvObject owner;
/** Given alias of the group, e.g by the user that created it. Unique in the owner. */
@NotBlank
@Pattern(regexp = "[a-zA-Z0-9\\_\\-]*", message = "Found an illegal character(s). Valid characters are a-Z, 0-9, '_', and '-'.")
private String groupAliasInOwner;
/** Alias of the group. Calculated from the group's name and its owner id. Unique in the table. */
@Column( unique = true )
private String groupAlias;
@Transient
private ExplicitGroupProvider provider;
public ExplicitGroup( ExplicitGroupProvider prv ) {
provider = prv;
containedAuthenticatedUsers = new HashSet<>();
containedExplicitGroups = new HashSet<>();
containedRoleAssignees = new TreeSet<>();
}
/**
* Constructor for JPA.
*/
protected ExplicitGroup() {}
public void add( User u ) {
if ( u instanceof AuthenticatedUser ) {
containedAuthenticatedUsers.add((AuthenticatedUser)u);
} else {
containedRoleAssignees.add( u.getIdentifier() );
}
}
/**
* Adds the {@link RoleAssignee} to {@code this} group.
*
* @param ra the role assignee to be added to this group.
* @throws GroupException if {@code ra} is a group, and is an ancestor of {@code this}.
*/
public void add( RoleAssignee ra ) throws GroupException {
if ( ra.equals(this) ) {
throw new GroupException(this, "A group cannot be added to itself.");
}
if ( ra instanceof User ) {
add( (User)ra );
} else {
// validate no circular deps
Group g = (Group) ra;
if ( g.contains(this) ) {
throw new GroupException(this, "A group cannot be added to one of its childs.");
}
// add
if ( g instanceof ExplicitGroup ) {
containedExplicitGroups.add( (ExplicitGroup)g );
} else {
containedRoleAssignees.add( g.getIdentifier() );
}
}
}
public void remove(RoleAssignee roleAssignee) {
removeByRoleAssgineeIdentifier( roleAssignee.getIdentifier() );
}
/**
* Returns all the role assignee identifiers in this group. <br>
* <b>Note</b> some of the identifiers may be stale (i.e. group deleted but
* identifiers lingered for a while).
*
* @return A list of the role assignee identifiers.
*/
public Set<String> getContainedRoleAssgineeIdentifiers() {
Set<String> retVal = new TreeSet<>();
retVal.addAll( containedRoleAssignees );
for ( ExplicitGroup subg : containedExplicitGroups ) {
retVal.add( subg.getIdentifier() );
}
for ( AuthenticatedUser au : containedAuthenticatedUsers ) {
retVal.add( au.getIdentifier() );
}
return retVal;
}
public void removeByRoleAssgineeIdentifier( String idtf ) {
if ( containedRoleAssignees.contains(idtf) ) {
containedRoleAssignees.remove(idtf);
} else {
for ( AuthenticatedUser au : containedAuthenticatedUsers ) {
if ( au.getIdentifier().equals(idtf) ) {
containedAuthenticatedUsers.remove(au);
return;
}
}
for ( ExplicitGroup eg : containedExplicitGroups ) {
if ( eg.getIdentifier().equals(idtf) ) {
containedExplicitGroups.remove(eg);
return;
}
}
}
}
@Override
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Override
public boolean contains(RoleAssignee ra) {
return containsDirectly(ra) || containsIndirectly(ra);
}
protected boolean containsDirectly( RoleAssignee ra ) {
if ( ra instanceof AuthenticatedUser ) {
AuthenticatedUser au = (AuthenticatedUser) ra;
return containedAuthenticatedUsers.contains(au);
} else if ( ra instanceof ExplicitGroup ) {
ExplicitGroup eg = (ExplicitGroup) ra;
return containedExplicitGroups.contains(eg);
} else {
return containedRoleAssignees.contains( ra.getIdentifier() );
}
}
private boolean containsIndirectly(RoleAssignee ra) {
for ( ExplicitGroup ceg : containedExplicitGroups ) {
if ( ceg.contains(ra) ) {
return true;
}
}
for ( String containedRAIdtf : containedRoleAssignees ) {
RoleAssignee containedRa = provider.findRoleAssignee(containedRAIdtf);
if ( containedRa != null ) {
if ( containedRa instanceof Group ) {
if (((Group)containedRa).contains(ra)) {
return true;
}
}
}
}
return false;
}
/**
* Updates the alias of the group. Call this after setting the owner or the
* groupAliasInOwner fields. JPA-related activities call this automatically.
*/
public void updateAlias() {
groupAlias = ((getOwner()!=null)
? Long.toString(getOwner().getId()) + "-"
: "") + getGroupAliasInOwner();
}
@PrePersist
void prepersist() {
updateAlias();
}
@PostLoad
void postload() {
updateAlias();
}
@Override
public boolean isEditable() {
return true;
}
@Override
public ExplicitGroupProvider getGroupProvider() {
return provider;
}
void setProvider( ExplicitGroupProvider c ) {
provider = c;
}
@Override
public String getIdentifier() {
return Group.IDENTIFIER_PREFIX + provider.getGroupProviderAlias()
+ Group.PATH_SEPARATOR + getAlias();
}
@Override
public RoleAssigneeDisplayInfo getDisplayInfo() {
return new RoleAssigneeDisplayInfo(getDisplayName(), null);
}
public String getGroupAliasInOwner() {
return groupAliasInOwner;
}
public void setGroupAliasInOwner(String groupAliasInOwner) {
this.groupAliasInOwner = groupAliasInOwner;
}
@Override
public String getAlias() {
return groupAlias;
}
@Override
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public DvObject getOwner() {
return owner;
}
public void setOwner(DvObject owner) {
this.owner = owner;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Override
public int hashCode() {
int hash = 7;
hash = 53 * hash + Objects.hashCode(this.id);
hash = 53 * hash + Objects.hashCode(this.groupAliasInOwner);
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if ( ! (obj instanceof ExplicitGroup)) {
return false;
}
final ExplicitGroup other = (ExplicitGroup) obj;
if ( id!=null && other.getId()!=null) {
return Objects.equals(id, other.getId());
} else {
return Objects.equals(this.groupAliasInOwner, other.groupAliasInOwner)
&& Objects.equals(this.owner, other.owner);
}
}
/**
* Low-level call to return the role assignee identifier strings. Note that
* the role assignees themselves might be stale, which is why this call is here -
* to allow the {@link ExplicitGroupServiceBean} to clean up this collection.
* @return the strings of the role assignees in this group.
*/
Set<String> getContainedRoleAssignees() {
return containedRoleAssignees;
}
@Override
public String toString() {
return "[ExplicitGroup " + groupAlias + "]";
}
}
| src/main/java/edu/harvard/iq/dataverse/authorization/groups/impl/explicit/ExplicitGroup.java | package edu.harvard.iq.dataverse.authorization.groups.impl.explicit;
import edu.harvard.iq.dataverse.DvObject;
import edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser;
import edu.harvard.iq.dataverse.authorization.groups.Group;
import edu.harvard.iq.dataverse.authorization.RoleAssignee;
import edu.harvard.iq.dataverse.authorization.RoleAssigneeDisplayInfo;
import edu.harvard.iq.dataverse.authorization.users.User;
import edu.harvard.iq.dataverse.authorization.groups.GroupException;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import java.util.TreeSet;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.PostLoad;
import javax.persistence.PrePersist;
import javax.persistence.Transient;
import javax.validation.constraints.Pattern;
import org.hibernate.validator.constraints.NotBlank;
/**
* A group that explicitly lists {@link RoleAssignee}s that belong to it. Implementation-wise,
* there are three cases here: {@link AuthenticatedUser}s, other {@link ExplicitGroup}s, and all the rest.
* AuthenticatedUsers and ExplicitGroups go in tables of their own. The rest are kept via their identifier.
*
* @author michael
*/
@NamedQueries({
@NamedQuery( name="ExplicitGroup.findAll",
query="SELECT eg FROM ExplicitGroup eg"),
@NamedQuery( name="ExplicitGroup.findByOwnerIdAndAlias",
query="SELECT eg FROM ExplicitGroup eg WHERE eg.owner.id=:ownerId AND eg.groupAliasInOwner=:alias"),
@NamedQuery( name="ExplicitGroup.findByAlias",
query="SELECT eg FROM ExplicitGroup eg WHERE eg.groupAlias=:alias"),
@NamedQuery( name="ExplicitGroup.findByOwnerId",
query="SELECT eg FROM ExplicitGroup eg WHERE eg.owner.id=:ownerId"),
@NamedQuery( name="ExplicitGroup.findByOwnerAndAuthUserId",
query="SELECT eg FROM ExplicitGroup eg join eg.containedAuthenticatedUsers au "
+"WHERE eg.owner.id=:ownerId AND au.id=:authUserId"),
@NamedQuery( name="ExplicitGroup.findByOwnerAndSubExGroupId",
query="SELECT eg FROM ExplicitGroup eg join eg.containedExplicitGroups ceg "
+"WHERE eg.owner.id=:ownerId AND ceg.id=:subExGroupId"),
@NamedQuery( name="ExplicitGroup.findByOwnerAndRAIdtf",
query="SELECT eg FROM ExplicitGroup eg join eg.containedRoleAssignees ra "
+"WHERE eg.owner.id=:ownerId AND ra=:raIdtf")
})
@Entity
public class ExplicitGroup implements Group, java.io.Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
Long id;
/**
* Authenticated users directly added to the group.
*/
@ManyToMany
private Set<AuthenticatedUser> containedAuthenticatedUsers;
/**
* Explicit groups that belong to {@code this} explicit gorups.
*/
@ManyToMany
@JoinTable(name = "explicitgroup_explicitgroup",
joinColumns = @JoinColumn(name="explicitgroup_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name="containedexplicitgroups_id", referencedColumnName = "id") )
Set<ExplicitGroup> containedExplicitGroups;
/**
* All the role assignees that belong to this group
* and are not {@link authenticatedUser}s or {@ExplicitGroup}s, are stored
* here via their identifiers.
*
* @see RoleAssignee#getIdentifier()
*/
@ElementCollection
private Set<String> containedRoleAssignees;
@Column( length = 1024 )
private String description;
@NotBlank
private String displayName;
/**
* The DvObject under which this group is defined.
*/
@ManyToOne
DvObject owner;
/** Given alias of the group, e.g by the user that created it. Unique in the owner. */
@NotBlank
@Pattern(regexp = "[a-zA-Z0-9\\_\\-]*", message = "Found an illegal character(s). Valid characters are a-Z, 0-9, '_', and '-'.")
private String groupAliasInOwner;
/** Alias of the group. Calculated from the group's name and its owner id. Unique in the table. */
@Column( unique = true )
private String groupAlias;
@Transient
private ExplicitGroupProvider provider;
public ExplicitGroup( ExplicitGroupProvider prv ) {
provider = prv;
containedAuthenticatedUsers = new HashSet<>();
containedExplicitGroups = new HashSet<>();
containedRoleAssignees = new TreeSet<>();
}
/**
* Constructor for JPA.
*/
protected ExplicitGroup() {}
public void add( User u ) {
if ( u instanceof AuthenticatedUser ) {
containedAuthenticatedUsers.add((AuthenticatedUser)u);
} else {
containedRoleAssignees.add( u.getIdentifier() );
}
}
/**
* Adds the {@link RoleAssignee} to {@code this} group.
*
* @param ra the role assignee to be added to this group.
* @throws GroupException if {@code ra} is a group, and is an ancestor of {@code this}.
*/
public void add( RoleAssignee ra ) throws GroupException {
if ( ra.equals(this) ) {
throw new GroupException(this, "A group cannot be added to itself.");
}
if ( ra instanceof User ) {
add( (User)ra );
} else {
// validate no circular deps
Group g = (Group) ra;
if ( g.contains(this) ) {
throw new GroupException(this, "A group cannot be added to one of its childs.");
}
// add
if ( g instanceof ExplicitGroup ) {
containedExplicitGroups.add( (ExplicitGroup)g );
} else {
containedRoleAssignees.add( g.getIdentifier() );
}
}
}
public void remove(RoleAssignee roleAssignee) {
removeByRoleAssgineeIdentifier( roleAssignee.getIdentifier() );
}
/**
* Returns all the role assignee identifiers in this group. <br>
* <b>Note</b> some of the identifiers may be stale (i.e. group deleted but
* identifiers lingered for a while).
*
* @return A list of the role assignee identifiers.
*/
public Set<String> getContainedRoleAssgineeIdentifiers() {
Set<String> retVal = new TreeSet<>();
retVal.addAll( containedRoleAssignees );
for ( ExplicitGroup subg : containedExplicitGroups ) {
retVal.add( subg.getIdentifier() );
}
for ( AuthenticatedUser au : containedAuthenticatedUsers ) {
retVal.add( au.getIdentifier() );
}
return retVal;
}
public void removeByRoleAssgineeIdentifier( String idtf ) {
if ( containedRoleAssignees.contains(idtf) ) {
containedRoleAssignees.remove(idtf);
} else {
for ( AuthenticatedUser au : containedAuthenticatedUsers ) {
if ( au.getIdentifier().equals(idtf) ) {
containedAuthenticatedUsers.remove(au);
return;
}
}
for ( ExplicitGroup eg : containedExplicitGroups ) {
if ( eg.getIdentifier().equals(idtf) ) {
containedExplicitGroups.remove(eg);
return;
}
}
}
}
@Override
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Override
public boolean contains(RoleAssignee ra) {
return containsDirectly(ra) || containsIndirectly(ra);
}
protected boolean containsDirectly( RoleAssignee ra ) {
if ( ra instanceof AuthenticatedUser ) {
AuthenticatedUser au = (AuthenticatedUser) ra;
return containedAuthenticatedUsers.contains(au);
} else if ( ra instanceof ExplicitGroup ) {
ExplicitGroup eg = (ExplicitGroup) ra;
return containedExplicitGroups.contains(eg);
} else {
return containedRoleAssignees.contains( ra.getIdentifier() );
}
}
private boolean containsIndirectly(RoleAssignee ra) {
for ( ExplicitGroup ceg : containedExplicitGroups ) {
if ( ceg.contains(ra) ) {
return true;
}
}
for ( String containedRAIdtf : containedRoleAssignees ) {
RoleAssignee containedRa = provider.findRoleAssignee(containedRAIdtf);
if ( containedRa != null ) {
if ( containedRa instanceof Group ) {
if (((Group)containedRa).contains(ra)) {
return true;
}
}
}
}
return false;
}
/**
* Updates the alias of the group. Call this after setting the owner or the
* groupAliasInOwner fields. JPA-related activities call this automatically.
*/
public void updateAlias() {
groupAlias = ((getOwner()!=null)
? Long.toString(getOwner().getId()) + "-"
: "") + getGroupAliasInOwner();
}
@PrePersist
void prepersist() {
updateAlias();
}
@PostLoad
void postload() {
updateAlias();
}
@Override
public boolean isEditable() {
return true;
}
@Override
public ExplicitGroupProvider getGroupProvider() {
return provider;
}
void setProvider( ExplicitGroupProvider c ) {
provider = c;
}
@Override
public String getIdentifier() {
return Group.IDENTIFIER_PREFIX + provider.getGroupProviderAlias()
+ Group.PATH_SEPARATOR + getAlias();
}
@Override
public RoleAssigneeDisplayInfo getDisplayInfo() {
return new RoleAssigneeDisplayInfo(getDisplayName(), null);
}
public String getGroupAliasInOwner() {
return groupAliasInOwner;
}
public void setGroupAliasInOwner(String groupAliasInOwner) {
this.groupAliasInOwner = groupAliasInOwner;
}
@Override
public String getAlias() {
return groupAlias;
}
@Override
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public DvObject getOwner() {
return owner;
}
public void setOwner(DvObject owner) {
this.owner = owner;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Override
public int hashCode() {
int hash = 7;
hash = 53 * hash + Objects.hashCode(this.id);
hash = 53 * hash + Objects.hashCode(this.groupAliasInOwner);
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if ( ! (obj instanceof ExplicitGroup)) {
return false;
}
final ExplicitGroup other = (ExplicitGroup) obj;
if ( id!=null && other.getId()!=null) {
return Objects.equals(id, other.getId());
} else {
return Objects.equals(this.groupAliasInOwner, other.groupAliasInOwner)
&& Objects.equals(this.owner, other.owner);
}
}
/**
* Low-level call to return the role assignee identifier strings. Note that
* the role assignees themselves might be stale, which is why this call is here -
* to allow the {@link ExplicitGroupServiceBean} to clean up this collection.
* @return the strings of the role assignees in this group.
*/
Set<String> getContainedRoleAssignees() {
return containedRoleAssignees;
}
@Override
public String toString() {
return "[ExplicitGroup " + groupAlias + "]";
}
}
| #1880, Add index for ExplicitGroup.java
| src/main/java/edu/harvard/iq/dataverse/authorization/groups/impl/explicit/ExplicitGroup.java | #1880, Add index for ExplicitGroup.java | <ide><path>rc/main/java/edu/harvard/iq/dataverse/authorization/groups/impl/explicit/ExplicitGroup.java
<ide> import javax.persistence.GeneratedValue;
<ide> import javax.persistence.GenerationType;
<ide> import javax.persistence.Id;
<add>import javax.persistence.Index;
<ide> import javax.persistence.JoinColumn;
<ide> import javax.persistence.JoinTable;
<ide> import javax.persistence.ManyToMany;
<ide> import javax.persistence.NamedQuery;
<ide> import javax.persistence.PostLoad;
<ide> import javax.persistence.PrePersist;
<add>import javax.persistence.Table;
<ide> import javax.persistence.Transient;
<ide> import javax.validation.constraints.Pattern;
<ide> import org.hibernate.validator.constraints.NotBlank;
<ide> +"WHERE eg.owner.id=:ownerId AND ra=:raIdtf")
<ide> })
<ide> @Entity
<add>@Table(indexes = {@Index(columnList="owner_id")
<add> //, @Index(columnList="groupalias") //@unique takes care of this
<add> , @Index(columnList="groupaliasinowner")})
<ide> public class ExplicitGroup implements Group, java.io.Serializable {
<ide>
<ide> @Id |
|
Java | epl-1.0 | 78a4d8ca1f45e203d1d3831a8ed0d371ca6f0b58 | 0 | Charling-Huang/birt,rrimmana/birt-1,rrimmana/birt-1,Charling-Huang/birt,sguan-actuate/birt,sguan-actuate/birt,rrimmana/birt-1,sguan-actuate/birt,sguan-actuate/birt,Charling-Huang/birt,Charling-Huang/birt,rrimmana/birt-1,rrimmana/birt-1,Charling-Huang/birt,sguan-actuate/birt | /*******************************************************************************
* Copyright (c) 2004 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.report.engine.data.dte;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.eclipse.birt.core.exception.BirtException;
import org.eclipse.birt.data.engine.api.IBaseExpression;
import org.eclipse.birt.data.engine.api.IBaseQueryDefinition;
import org.eclipse.birt.data.engine.api.IBaseTransform;
import org.eclipse.birt.data.engine.api.IFilterDefinition;
import org.eclipse.birt.data.engine.api.IGroupDefinition;
import org.eclipse.birt.data.engine.api.IInputParameterBinding;
import org.eclipse.birt.data.engine.api.IQueryDefinition;
import org.eclipse.birt.data.engine.api.ISortDefinition;
import org.eclipse.birt.data.engine.api.ISubqueryDefinition;
import org.eclipse.birt.data.engine.api.querydefn.BaseQueryDefinition;
import org.eclipse.birt.data.engine.api.querydefn.ConditionalExpression;
import org.eclipse.birt.data.engine.api.querydefn.FilterDefinition;
import org.eclipse.birt.data.engine.api.querydefn.GroupDefinition;
import org.eclipse.birt.data.engine.api.querydefn.InputParameterBinding;
import org.eclipse.birt.data.engine.api.querydefn.QueryDefinition;
import org.eclipse.birt.data.engine.api.querydefn.ScriptExpression;
import org.eclipse.birt.data.engine.api.querydefn.SortDefinition;
import org.eclipse.birt.data.engine.api.querydefn.SubqueryDefinition;
import org.eclipse.birt.report.engine.adapter.ModelDteApiAdapter;
import org.eclipse.birt.report.engine.api.EngineException;
import org.eclipse.birt.report.engine.content.IStyle;
import org.eclipse.birt.report.engine.executor.ExecutionContext;
import org.eclipse.birt.report.engine.extension.IReportItemQuery;
import org.eclipse.birt.report.engine.extension.internal.ExtensionManager;
import org.eclipse.birt.report.engine.i18n.MessageConstants;
import org.eclipse.birt.report.engine.ir.ActionDesign;
import org.eclipse.birt.report.engine.ir.CellDesign;
import org.eclipse.birt.report.engine.ir.DataItemDesign;
import org.eclipse.birt.report.engine.ir.DefaultReportItemVisitorImpl;
import org.eclipse.birt.report.engine.ir.DrillThroughActionDesign;
import org.eclipse.birt.report.engine.ir.Expression;
import org.eclipse.birt.report.engine.ir.ExtendedItemDesign;
import org.eclipse.birt.report.engine.ir.FreeFormItemDesign;
import org.eclipse.birt.report.engine.ir.GridItemDesign;
import org.eclipse.birt.report.engine.ir.GroupDesign;
import org.eclipse.birt.report.engine.ir.HighlightDesign;
import org.eclipse.birt.report.engine.ir.HighlightRuleDesign;
import org.eclipse.birt.report.engine.ir.ImageItemDesign;
import org.eclipse.birt.report.engine.ir.LabelItemDesign;
import org.eclipse.birt.report.engine.ir.ListBandDesign;
import org.eclipse.birt.report.engine.ir.ListGroupDesign;
import org.eclipse.birt.report.engine.ir.ListItemDesign;
import org.eclipse.birt.report.engine.ir.ListingDesign;
import org.eclipse.birt.report.engine.ir.MapDesign;
import org.eclipse.birt.report.engine.ir.MapRuleDesign;
import org.eclipse.birt.report.engine.ir.MasterPageDesign;
import org.eclipse.birt.report.engine.ir.MultiLineItemDesign;
import org.eclipse.birt.report.engine.ir.Report;
import org.eclipse.birt.report.engine.ir.ReportItemDesign;
import org.eclipse.birt.report.engine.ir.RowDesign;
import org.eclipse.birt.report.engine.ir.SimpleMasterPageDesign;
import org.eclipse.birt.report.engine.ir.TableBandDesign;
import org.eclipse.birt.report.engine.ir.TableGroupDesign;
import org.eclipse.birt.report.engine.ir.TableItemDesign;
import org.eclipse.birt.report.engine.ir.TextItemDesign;
import org.eclipse.birt.report.model.api.DataSetHandle;
import org.eclipse.birt.report.model.api.ExtendedItemHandle;
import org.eclipse.birt.report.model.api.FilterConditionHandle;
import org.eclipse.birt.report.model.api.GroupHandle;
import org.eclipse.birt.report.model.api.ListHandle;
import org.eclipse.birt.report.model.api.ListingHandle;
import org.eclipse.birt.report.model.api.ParamBindingHandle;
import org.eclipse.birt.report.model.api.ReportItemHandle;
import org.eclipse.birt.report.model.api.SlotHandle;
import org.eclipse.birt.report.model.api.SortKeyHandle;
import org.eclipse.birt.report.model.api.TableHandle;
import org.eclipse.birt.report.model.api.elements.DesignChoiceConstants;
/**
* visit the report design and prepare all report queries and sub-queries to
* send to data engine
*
* @version $Revision: 1.49 $ $Date: 2006/02/28 03:53:13 $
*/
public class ReportQueryBuilder
{
protected static Logger logger = Logger.getLogger( ReportQueryBuilder.class
.getName( ) );
public ReportQueryBuilder( )
{
}
/**
* @param report
* the entry point to the report design
* @param context
* the execution context
*/
public void build( Report report, ExecutionContext context )
{
new QueryBuilderVisitor( ).buildQuery( report, context );
}
/**
* The visitor class that actually builds the report query
*/
protected class QueryBuilderVisitor extends DefaultReportItemVisitorImpl
{
/**
* query and it's IDs
*/
protected HashMap queryIDs;
/**
* a collection of all the queries
*/
protected Collection queries;
/**
* the query stack. The top stores the query that is currently prepared.
* Needed because we could have nested queries
*/
protected LinkedList queryStack = new LinkedList( );
/**
* the total number of queries created in this report
*/
protected int queryCount = 0;
/**
* a collection of the expressions on the CURRENT query
*/
protected Collection expressions;
/**
* the expression stack. This is a link list of collections, not a
* link-list of individual expressions.
*/
protected LinkedList expressionStack = new LinkedList( );
/* report item query stack
*
*/
protected LinkedList reportItemQueryStack;
/**
* entry point to the report
*/
protected Report report;
/**
* the execution context
*/
protected ExecutionContext context;
/**
* create report query definitions for this report.
*
* @param report
* entry point to the report
* @param context
* the execution context
*/
public void buildQuery( Report report, ExecutionContext context )
{
this.report = report;
this.context = context;
queries = report.getQueries( );
// first clear the collection in case the caller call this function
// more than once.
queries.clear( );
queryIDs = report.getQueryIDs( );
queryIDs.clear( );
// visit master page
for ( int i = 0; i < report.getPageSetup().getMasterPageCount( ); i++ )
{
MasterPageDesign masterPage = report.getPageSetup().getMasterPage( i );
if ( masterPage != null )
{
SimpleMasterPageDesign pageDesign = (SimpleMasterPageDesign) masterPage;
for ( int j = 0; j < pageDesign.getHeaderCount( ); j++ )
{
pageDesign.getHeader( j ).accept( this, null );
}
for ( int j = 0; j < pageDesign.getFooterCount( ); j++ )
{
pageDesign.getFooter( j ).accept( this, null );
}
}
}
// visit report
for ( int i = 0; i < report.getContentCount( ); i++ )
report.getContent( i ).accept( this, null );
}
/**
* Handles query creation and initialization with report-item related
* expressions
*
* @param item
* report item
*/
private BaseQueryDefinition prepareVisit( ReportItemDesign item )
{
BaseQueryDefinition tempQuery = null;
if ( item instanceof ListingDesign )
tempQuery = createQuery( (ListingDesign) item );
else
tempQuery = createQuery( item );
if ( tempQuery != null )
{
pushQuery( tempQuery );
pushExpressions( tempQuery.getRowExpressions( ) );
}
return tempQuery;
}
/**
* Clean up stack after visiting a report item
*/
private void finishVisit( BaseQueryDefinition query )
{
if ( query != null )
{
popExpressions( );
popQuery( );
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.ir.ReportItemVisitor#visitFreeFormItem(org.eclipse.birt.report.engine.ir.FreeFormItemDesign)
*/
public Object visitFreeFormItem( FreeFormItemDesign container,
Object value )
{
BaseQueryDefinition query = prepareVisit( container );
handleReportItemExpressions( container );
for ( int i = 0; i < container.getItemCount( ); i++ )
container.getItem( i ).accept( this, value );
finishVisit( query );
return value;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.ir.ReportItemVisitor#visitGridItem(org.eclipse.birt.report.engine.ir.GridItemDesign)
*/
public Object visitGridItem( GridItemDesign grid, Object value )
{
BaseQueryDefinition query = prepareVisit( grid );
handleReportItemExpressions( grid );
for ( int i = 0; i < grid.getColumnCount( ); i++ )
{
// ColumnDesign column = grid.getColumn( i );
// handleStyle( column.getStyle( ) );
}
for ( int i = 0; i < grid.getRowCount( ); i++ )
handleRow( grid.getRow( i ), value );
finishVisit( query );
return value;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.ir.IReportItemVisitor#visitImageItem(org.eclipse.birt.report.engine.ir.ImageItemDesign)
*/
public Object visitImageItem( ImageItemDesign image, Object value )
{
BaseQueryDefinition query = prepareVisit( image );
handleReportItemExpressions( image );
handleAction( image.getAction( ) );
if ( image.getImageSource( ) == ImageItemDesign.IMAGE_EXPRESSION )
{
addExpression( image.getImageExpression( ) );
addExpression( image.getImageFormat( ) );
}
else if ( image.getImageSource( ) == ImageItemDesign.IMAGE_URI
|| image.getImageSource( ) == ImageItemDesign.IMAGE_FILE )
{
addExpression( image.getImageUri( ) );
}
finishVisit( query );
return value;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.ir.ReportItemVisitor#visitLabelItem(org.eclipse.birt.report.engine.ir.LabelItemDesign)
*/
public Object visitLabelItem( LabelItemDesign label, Object value )
{
BaseQueryDefinition query = prepareVisit( label );
handleReportItemExpressions( label );
handleAction( label.getAction( ) );
finishVisit( query );
return value;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.ir.IReportItemVisitor#visitExtendedItem(org.eclipse.birt.report.engine.ir.ExtendedItemDesign)
*/
public Object visitExtendedItem( ExtendedItemDesign item, Object value )
{
// create user-defined generation-time helper object
ExtendedItemHandle handle = (ExtendedItemHandle) item.getHandle( );
String tagName = handle.getExtensionName( );
// TODO: check in plugin registry whetherthe needQuery property is
// set to host or item.
// Only do the following for "host"
IReportItemQuery itemQuery = ExtensionManager.getInstance( )
.createQueryItem( tagName );
IBaseQueryDefinition[] queries = null;
IBaseQueryDefinition parentQuery = getParentQuery( );
IBaseTransform parentTrans = getTransform( );
if ( itemQuery != null )
{
try
{
itemQuery.setModelObject( handle );
queries = itemQuery.getReportQueries( parentQuery );
}
catch ( BirtException ex )
{
logger.log( Level.WARNING, ex.getMessage( ), ex );
}
if ( queries != null )
{
item.setQueries( queries );
for ( int i = 0; i < queries.length; i++ )
{
// only a regular query need add to list
if ( queries[i] != null )
{
if ( queries[i] instanceof IQueryDefinition )
{
this.queryIDs.put( queries[i], String
.valueOf( item.getID( ) )
+ "_" + String.valueOf( i ) );
this.queries.add( queries[i] );
// to support parameter binding with data
// related expression in report query
Collection bindings = ( (IQueryDefinition) queries[i] )
.getInputParamBindings( );
if ( bindings.size( ) > 0 )
{
if ( parentTrans != null )
{
Iterator iter = bindings.iterator( );
while ( iter.hasNext( ) )
{
IInputParameterBinding binding = (IInputParameterBinding) iter
.next( );
parentTrans.getRowExpressions( )
.add( binding.getExpr( ) );
}
}
}
}
else if ( queries[i] instanceof ISubqueryDefinition )
{
// TODO: chart engine make a mistake here
if ( parentTrans != null )
{
parentTrans.getSubqueries( ).add(
queries[i] );
}
}
registerQueryAndElement( queries[i], item );
report.getQueryToValueExprMap( ).put( queries[i],
queries[i].getRowExpressions( ) );
}
}
if ( queries.length > 0 )
{
IBaseQueryDefinition query = queries[0];
if ( query != null )
{
item.setQuery( query );
pushQuery( query );
pushExpressions( query.getRowExpressions( ) );
handleReportItemExpressions( item );
// handleActionExpressions(item.getAction());
popExpressions( );
popQuery( );
}
}
}
}
return value;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.ir.ReportItemVisitor#visitListItem(org.eclipse.birt.report.engine.ir.ListItemDesign)
*/
public Object visitListItem( ListItemDesign list, Object value )
{
BaseQueryDefinition query = prepareVisit( list );
if ( query == null )
{
visitListBand( list.getHeader( ), value );
visitListBand( list.getFooter( ), value );
}
else
{
pushReportItemQuery( query );
pushExpressions( query.getBeforeExpressions( ) );
handleReportItemExpressions( list );
visitListBand( list.getHeader( ), value );
popExpressions( );
popReportItemQuery( );
SlotHandle groupsSlot = ( (ListHandle) list.getHandle( ) )
.getGroups( );
pushReportItemQuery( query );
for ( int i = 0; i < list.getGroupCount( ); i++ )
{
handleListGroup( list.getGroup( i ),
(GroupHandle) groupsSlot.get( i ), value );
}
popReportItemQuery( );
if ( list.getDetail( ).getContentCount( ) != 0 )
{
query.setUsesDetails( true );
}
pushReportItemQuery( query );
pushExpressions( query.getRowExpressions( ) );
visitListBand( list.getDetail( ), value );
popExpressions( );
popReportItemQuery( );
pushExpressions( query.getAfterExpressions( ) );
visitListBand( list.getFooter( ), value );
popExpressions( );
}
finishVisit( query );
registerQueryAndElement( query, list );
return value;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.ir.ReportItemVisitor#visitTextItem(org.eclipse.birt.report.engine.ir.TextItemDesign)
*/
public Object visitTextItem( TextItemDesign text, Object value )
{
BaseQueryDefinition query = prepareVisit( text );
handleReportItemExpressions( text );
HashMap exprs = text.getExpressions( );
if ( exprs != null )
{
Iterator iter = exprs.values( ).iterator( );
while ( iter.hasNext( ) )
{
IBaseExpression expr = (IBaseExpression) iter.next( );
addExpression( expr );
}
}
finishVisit( query );
return value;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.ir.ReportItemVisitor#visitTableItem(org.eclipse.birt.report.engine.ir.TableItemDesign)
*/
public Object visitTableItem( TableItemDesign table, Object value )
{
BaseQueryDefinition query = prepareVisit( table );
for ( int i = 0; i < table.getColumnCount( ); i++ )
{
// ColumnDesign column = table.getColumn( i );
// handleStyle( column.getStyle( ) );
}
if ( query == null )
{
handleTableBand( table.getHeader( ), value );
handleTableBand( table.getFooter( ), value );
}
else
{
pushExpressions( query.getBeforeExpressions( ) );
handleReportItemExpressions( table );
handleTableBand( table.getHeader( ), value );
popExpressions( );
SlotHandle groupsSlot = ( (TableHandle) table.getHandle( ) )
.getGroups( );
pushReportItemQuery( query );
for ( int i = 0; i < table.getGroupCount( ); i++ )
{
handleTableGroup( table.getGroup( i ),
(GroupHandle) groupsSlot.get( i ), value );
}
popReportItemQuery( );
if ( table.getDetail( ).getRowCount( ) != 0 )
{
query.setUsesDetails( true );
}
pushReportItemQuery( query );
pushExpressions( query.getRowExpressions( ) );
handleTableBand( table.getDetail( ), value );
popExpressions( );
popReportItemQuery( );
pushExpressions( query.getAfterExpressions( ) );
handleTableBand( table.getFooter( ), value );
popExpressions( );
}
finishVisit( query );
registerQueryAndElement( query, table );
return value;
}
/*
* associate query with Table, List and Chart item design.
*/
private void registerQueryAndElement( IBaseQueryDefinition query,
ReportItemDesign reportItem )
{
assert query!=null && reportItem != null;
HashMap map = report.getReportItemToQueryMap( );
assert map != null;
map.put( query, reportItem );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.ir.ReportItemVisitor#visitMultiLineItem(org.eclipse.birt.report.engine.ir.MultiLineItemDesign)
*/
public Object visitMultiLineItem( MultiLineItemDesign multiLine,
Object value )
{
BaseQueryDefinition query = prepareVisit( multiLine );
handleReportItemExpressions( multiLine );
addExpression( multiLine.getContent( ) );
finishVisit( query );
return value;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.ir.IReportItemVisitor#visitDataItem(org.eclipse.birt.report.engine.ir.DataItemDesign)
*/
public Object visitDataItem( DataItemDesign data, Object value )
{
BaseQueryDefinition query = prepareVisit( data );
handleReportItemExpressions( data );
handleAction( data.getAction( ) );
addExpression( data.getValue( ) );
addtoValueExpressions( data );
finishVisit( query );
return value;
}
private void addtoValueExpressions( DataItemDesign data )
{
if( reportItemQueryStack == null || reportItemQueryStack.isEmpty() == true )
{
return ;
}
if( data.getValue( ) != null )
{
IBaseQueryDefinition query = (IBaseQueryDefinition)reportItemQueryStack
.getLast( );
assert query != null;
HashMap queryMap = report.getQueryToValueExprMap( );
assert queryMap != null;
HashMap exprToNameMap = report.getExprToNameMap( );
assert exprToNameMap != null;
ArrayList valueExprs = (ArrayList)queryMap.get( query );
if( valueExprs == null )
{
valueExprs = new ArrayList( );
}
if( valueExprs.contains( data.getValue( )) == false )
{
valueExprs.add( data.getValue( ));
if ( data.getName( ) != null )
{
exprToNameMap.put( data.getValue( ), data.getName( ) );
}
}
queryMap.put( query, valueExprs );
}
}
/**
* handle expressions common to all report items
*
* @param item
* a report item
*/
protected void handleReportItemExpressions( ReportItemDesign item )
{
if ( item.getVisibility( ) != null )
{
for ( int i = 0; i < item.getVisibility( ).count( ); i++ )
{
addExpression( item.getVisibility( ).getRule( i )
.getExpression( ) );
}
}
addExpression( item.getTOC( ) );
addExpression( item.getBookmark( ) );
addExpression( item.getOnCreate( ) );
// handleStyle( item.getStyle( ) );
handleHighlightExpressions( item.getHighlight( ) );
handleMapExpressions( item.getMap( ) );
handleNamedExpressions ( item.getNamedExpressions( ) );
}
/**
* handle named expression
* @param namedExpressions a map of of named expression
*/
protected void handleNamedExpressions( Map namedExpressions )
{
Collection exprs = namedExpressions.values();
Iterator exprIter = exprs.iterator();
while( exprIter.hasNext( ) )
{
addExpression( (Expression)exprIter.next() );
}
}
/**
* @param band
* the list band
*/
protected void visitListBand( ListBandDesign band, Object value )
{
for ( int i = 0; i < band.getContentCount( ); i++ )
{
band.getContent( i ).accept( this, value );
}
}
/**
* @param group
* a grouping in a list
* @param handle
* handle to a grouping element
*/
protected void handleListGroup( ListGroupDesign group,
GroupHandle handle, Object value )
{
IGroupDefinition groupDefn = handleGroup( group, handle );
pushQuery( groupDefn );
pushExpressions( groupDefn.getBeforeExpressions( ) );
visitListBand( group.getHeader( ), value );
popExpressions( );
pushExpressions( groupDefn.getAfterExpressions( ) );
visitListBand( group.getFooter( ), value );
popExpressions( );
popQuery( );
}
/**
* processes a table/list group
*/
protected IGroupDefinition handleGroup( GroupDesign group,
GroupHandle handle )
{
GroupDefinition groupDefn = new GroupDefinition( group.getName( ) );
groupDefn.setKeyExpression( handle.getKeyExpr( ) );
String interval = handle.getInterval( );
if ( interval != null )
{
groupDefn.setInterval( parseInterval( interval ) );
}
// inter-range
groupDefn.setIntervalRange( handle.getIntervalRange( ) );
// inter-start-value
groupDefn.setIntervalStart( handle.getIntervalBase( ) );
// sort-direction
String direction = handle.getSortDirection( );
if ( direction != null )
{
groupDefn.setSortDirection( parseSortDirection( direction ) );
}
groupDefn.getSorts( ).addAll( createSorts( handle ) );
groupDefn.getFilters( ).addAll( createFilters( handle ) );
getParentQuery( ).getGroups( ).add( groupDefn );
return groupDefn;
}
/**
* processes a band in a table
*/
protected void handleTableBand( TableBandDesign band, Object value )
{
for ( int i = 0; i < band.getRowCount( ); i++ )
handleRow( band.getRow( i ), value );
}
/**
* processes a table group
*/
protected void handleTableGroup( TableGroupDesign group,
GroupHandle handle, Object value )
{
IGroupDefinition groupDefn = handleGroup( group, handle );
pushQuery( groupDefn );
pushExpressions( groupDefn.getBeforeExpressions( ) );
handleTableBand( group.getHeader( ), value );
popExpressions( );
pushExpressions( groupDefn.getAfterExpressions( ) );
handleTableBand( group.getFooter( ), value );
popExpressions( );
popQuery( );
}
/**
* handle style, which may contain highlight/mapping expressions
*
* @param style
* style design
*/
protected void handleStyle( IStyle style )
{
/*
* if ( style != null ) { handleHighlight( style.getHighlight( ) );
* handleMap( style.getMap( ) ); }
*/
}
/**
* handle mapping expressions
*/
protected void handleMapExpressions( MapDesign map )
{
if ( map != null )
{
for ( int i = 0; i < map.getRuleCount( ); i++ )
{
MapRuleDesign rule = map.getRule( i );
if ( rule != null )
addExpression( rule.getConditionExpr( ) );
}
}
}
/**
* handle highlight expressions
*/
protected void handleHighlightExpressions( HighlightDesign highlight )
{
if ( highlight != null )
{
for ( int i = 0; i < highlight.getRuleCount( ); i++ )
{
HighlightRuleDesign rule = highlight.getRule( i );
if ( rule != null )
addExpression( rule.getConditionExpr( ) );
}
}
}
/**
* handles action expressions, i.e, book-mark and hyper-link
* expressions.
*/
protected void handleAction( ActionDesign action )
{
if ( action != null )
{
switch ( action.getActionType( ) )
{
case ActionDesign.ACTION_BOOKMARK :
addExpression( action.getBookmark( ) );
break;
case ActionDesign.ACTION_DRILLTHROUGH :
DrillThroughActionDesign drillThrough = action
.getDrillThrough( );
if ( drillThrough != null )
{
addExpression( drillThrough.getBookmark( ) );
if ( drillThrough.getParameters( ) != null )
{
Iterator ite = drillThrough.getParameters( )
.entrySet( ).iterator( );
while ( ite.hasNext( ) )
{
Map.Entry entry = (Map.Entry) ite.next( );
assert entry.getValue( ) instanceof Expression;
addExpression( (Expression) entry
.getValue( ) );
}
}
}
break;
case ActionDesign.ACTION_HYPERLINK :
addExpression( action.getHyperlink( ) );
break;
default :
assert false;
}
}
}
/**
* visit content of a row
*/
protected void handleRow( RowDesign row, Object value )
{
// handleStyle( row.getStyle( ) );
if ( row.getVisibility( ) != null )
{
for ( int i = 0; i < row.getVisibility( ).count( ); i++ )
addExpression( row.getVisibility( ).getRule( i )
.getExpression( ) );
}
addExpression(row.getTOC());
addExpression( row.getBookmark( ) );
for ( int i = 0; i < row.getCellCount( ); i++ )
{
CellDesign cell = row.getCell( i );
if ( cell != null )
{
handleCell( cell, value );
}
}
}
/**
* handles a cell in a row
*/
protected void handleCell( CellDesign cell, Object value )
{
// handleStyle( cell.getStyle( ) );
for ( int i = 0; i < cell.getContentCount( ); i++ )
cell.getContent( i ).accept( this, value );
}
/**
* A helper function for adding expression collection to stack
*/
protected void pushExpressions( Collection newExpressions )
{
this.expressionStack.addLast( this.expressions );
this.expressions = newExpressions;
}
/**
* A helper function for removing expression collection from stack
*/
protected void popExpressions( )
{
assert !expressionStack.isEmpty( );
this.expressions = (Collection) expressionStack.removeLast( );
}
protected void pushReportItemQuery( IBaseQueryDefinition query )
{
if( this.reportItemQueryStack == null )
{
this.reportItemQueryStack = new LinkedList( );
}
this.reportItemQueryStack.addLast( query );
}
protected void popReportItemQuery( )
{
assert this.reportItemQueryStack.isEmpty( ) == false;
this.reportItemQueryStack.removeLast( );
}
/**
* A helper function for adding a query to query stack
*/
protected void pushQuery( IBaseTransform query )
{
this.queryStack.addLast( query );
}
/**
* A helper function for removing a query from query stack
*/
protected void popQuery( )
{
assert !queryStack.isEmpty( );
queryStack.removeLast( );
}
/**
* add expression to the expression collection on top of the expressions
* stack
*
* @param expr
* expression to be added
*/
protected void addExpression( IBaseExpression expr )
{
// expressions may be null, which means the expression is in the
// topmost element, and has no data set associated with it.
if ( expr != null && expressions != null )
expressions.add( expr );
}
/**
* @return topmost element on query stack
*/
protected IBaseTransform getTransform( )
{
if ( queryStack.isEmpty( ) )
return null;
return (IBaseTransform) queryStack.getLast( );
}
/**
* @return the parent query for the current report item
*/
protected BaseQueryDefinition getParentQuery( )
{
if ( queryStack.isEmpty( ) )
return null;
for ( int i = queryStack.size( ) - 1; i >= 0; i-- )
{
if ( queryStack.get( i ) instanceof BaseQueryDefinition )
return (BaseQueryDefinition) queryStack.get( i );
}
return null;
}
/**
* @return the expression collection
*/
protected Collection getExpressions( )
{
return expressions;
}
/**
* @return a unique query name, based on a simple integer counter
*/
protected String createUniqueQueryName( )
{
queryCount++;
return String.valueOf( queryCount );
}
/**
* create query for non-listing report item
*
* @param item
* report item
* @return a report query
*/
protected BaseQueryDefinition createQuery( ReportItemDesign item )
{
DataSetHandle dsHandle = ( (ReportItemHandle) item.getHandle( ) )
.getDataSet( );
if ( dsHandle == null )
{
// dataset reference error
String dsName = (String) ( (ReportItemHandle) item.getHandle( ) )
.getProperty( ReportItemHandle.DATA_SET_PROP );
if ( dsName != null && dsName.length( ) > 0 )
{
context.addException( item.getHandle( ),
new EngineException(
MessageConstants.UNDEFINED_DATASET_ERROR,
dsName ) );
}
}
if ( dsHandle != null )
{
ReportItemHandle riHandle = (ReportItemHandle) item.getHandle( );
QueryDefinition query = new QueryDefinition( getParentQuery( ) );
query.setDataSetName( dsHandle.getQualifiedName( ) );
ArrayList bindings = createParamBindings( riHandle
.paramBindingsIterator( ) );
if ( bindings.size( ) > 0 )
{
query.getInputParamBindings( ).addAll( bindings );
IBaseTransform trans = getTransform( );
if ( trans != null )
{
for ( int i = 0; i < bindings.size( ); i++ )
{
IInputParameterBinding binding = (IInputParameterBinding) bindings
.get( i );
trans.getRowExpressions( ).add( binding.getExpr( ) );
}
}
}
this.queryIDs.put( query, String.valueOf( item.getID( ) ) );
this.queries.add( query );
item.setQuery( query );
return query;
}
return null;
}
/**
* create query for listing report item
*
* @param listing
* the listing item
* @return a report query definition
*/
protected BaseQueryDefinition createQuery( ListingDesign listing )
{
// creates its own query
BaseQueryDefinition query = createQuery( (ReportItemDesign) listing );
if ( query != null )
{
query.getSorts( ).addAll( createSorts( listing ) );
query.getFilters( ).addAll( createFilters( listing ) );
return query;
}
// creates a subquery, instead
if ( getTransform( ) == null )
{
return null;
}
String name = createUniqueQueryName( );
SubqueryDefinition subQuery = new SubqueryDefinition( name );
listing.setQuery( subQuery );
subQuery.getSorts( ).addAll( createSorts( listing ) );
subQuery.getFilters( ).addAll( createFilters( listing ) );
getTransform( ).getSubqueries( ).add( subQuery );
return subQuery;
}
/**
* get Localized string by the resouce key and <code>Locale</code>
* object in <code>context</code>
*
* @param resourceKey
* the resource key
* @param text
* the default value
* @return the localized string if it is defined in report deign, else
* return the default value
*/
protected String getLocalizedString( String resourceKey, String text )
{
if ( resourceKey == null )
{
return text;
}
String ret = report.getMessage( resourceKey, context.getLocale( ) );
if ( ret == null )
{
logger.log( Level.SEVERE, "get resource error, resource key:" //$NON-NLS-1$
+ resourceKey + " Locale:" //$NON-NLS-1$
+ context.getLocale( ).toString( ) );
return text;
}
return ret;
}
/**
* Walk through the DOM tree from a text item to collect the embedded
* expressions and format expressions
*
* After evaluating, the second child node of the embedded expression
* node holds the value if no error exists.
*
* @param node
* a node in the DOM tree
* @param text
* the text object
*/
/*
* protected void getEmbeddedExpression( Node node, TextItemDesign text ) {
* if ( node.getNodeType( ) == Node.ELEMENT_NODE ) { if (
* node.getNodeName( ).equals( "value-of" ) ) //$NON-NLS-1$ { if (
* !text.hasExpression( node.getFirstChild( ) .getNodeValue( ) ) ) {
* Expression expr = new Expression( node.getFirstChild( )
* .getNodeValue( ) ); this.addExpression( expr ); text.addExpression(
* node.getFirstChild( ) .getNodeValue( ), expr );
*
* return; } } else if ( node.getNodeName( ).equals( "image" ) )
* //$NON-NLS-1$ {
*
* String imageType = ( (Element) ( node ) ) .getAttribute( "type" );
* //$NON-NLS-1$
*
* if ( "expr".equals( imageType ) ) //$NON-NLS-1$ { if (
* !text.hasExpression( node.getFirstChild( ) .getNodeValue( ) ) ) {
* Expression expr = new Expression( node .getFirstChild(
* ).getNodeValue( ) );
*
* this.addExpression( expr ); text.addExpression( node.getFirstChild( )
* .getNodeValue( ), expr ); } } return; } //call recursively for ( Node
* child = node.getFirstChild( ); child != null; child = child
* .getNextSibling( ) ) { getEmbeddedExpression( child, text ); } } }
*/
/**
* create one Filter given a filter condition handle
*
* @param handle
* a filter condition handle
* @return the filter
*/
private IFilterDefinition createFilter( FilterConditionHandle handle )
{
String filterExpr = handle.getExpr( );
if ( filterExpr == null || filterExpr.length( ) == 0 )
return null; // no filter defined
// converts to DtE exprFilter if there is no operator
String filterOpr = handle.getOperator( );
if ( filterOpr == null || filterOpr.length( ) == 0 )
return new FilterDefinition( new ScriptExpression( filterExpr ) );
/*
* has operator defined, try to convert filter condition to
* operator/operand style column filter with 0 to 2 operands
*/
String column = filterExpr;
int dteOpr = ModelDteApiAdapter.toDteFilterOperator( filterOpr );
String operand1 = handle.getValue1( );
String operand2 = handle.getValue2( );
return new FilterDefinition( new ConditionalExpression( column,
dteOpr, operand1, operand2 ) );
}
/**
* create a filter array given a filter condition handle iterator
*
* @param iter
* the iterator
* @return filter array
*/
private ArrayList createFilters( Iterator iter )
{
ArrayList filters = new ArrayList( );
if ( iter != null )
{
while ( iter.hasNext( ) )
{
FilterConditionHandle filterHandle = (FilterConditionHandle) iter
.next( );
IFilterDefinition filter = createFilter( filterHandle );
filters.add( filter );
}
}
return filters;
}
/**
* create filter array given a Listing design element
*
* @param listing
* the ListingDesign
* @return the filter array
*/
public ArrayList createFilters( ListingDesign listing )
{
return createFilters( ( (ListingHandle) listing.getHandle( ) )
.filtersIterator( ) );
}
/**
* create fileter array given a DataSetHandle
*
* @param dataSet
* the DataSetHandle
* @return the filer array
*/
public ArrayList createFilters( DataSetHandle dataSet )
{
return createFilters( dataSet.filtersIterator( ) );
}
/**
* create filter array given a GroupHandle
*
* @param group
* the GroupHandle
* @return filter array
*/
public ArrayList createFilters( GroupHandle group )
{
return createFilters( group.filtersIterator( ) );
}
/**
* create one sort condition
*
* @param handle
* the SortKeyHandle
* @return the sort object
*/
private ISortDefinition createSort( SortKeyHandle handle )
{
SortDefinition sort = new SortDefinition( );
sort.setExpression( handle.getKey( ) );
sort.setSortDirection( handle.getDirection( ).equals(
DesignChoiceConstants.SORT_DIRECTION_ASC ) ? 0 : 1 );
return sort;
}
/**
* create all sort conditions given a sort key handle iterator
*
* @param iter
* the iterator
* @return sort array
*/
private ArrayList createSorts( Iterator iter )
{
ArrayList sorts = new ArrayList( );
if ( iter != null )
{
while ( iter.hasNext( ) )
{
SortKeyHandle handle = (SortKeyHandle) iter.next( );
sorts.add( createSort( handle ) );
}
}
return sorts;
}
/**
* create all sort conditions in a listing element
*
* @param listing
* ListingDesign
* @return the sort array
*/
protected ArrayList createSorts( ListingDesign listing )
{
return createSorts( ( (ListingHandle) listing.getHandle( ) )
.sortsIterator( ) );
}
/**
* create sort array by giving GroupHandle
*
* @param group
* the GroupHandle
* @return the sort array
*/
protected ArrayList createSorts( GroupHandle group )
{
return createSorts( group.sortsIterator( ) );
}
/**
* create input parameter binding
*
* @param handle
* @return
*/
protected IInputParameterBinding createParamBinding(
ParamBindingHandle handle )
{
if ( handle.getExpression( ) == null )
return null; // no expression is bound
ScriptExpression expr = new ScriptExpression( handle
.getExpression( ) );
// model provides binding by name only
return new InputParameterBinding( handle.getParamName( ), expr );
}
/**
* create input parameter bindings
*
* @param iter
* parameter bindings iterator
* @return a list of input parameter bindings
*/
protected ArrayList createParamBindings( Iterator iter )
{
ArrayList list = new ArrayList( );
if ( iter != null )
{
while ( iter.hasNext( ) )
{
ParamBindingHandle modelParamBinding = (ParamBindingHandle) iter
.next( );
IInputParameterBinding binding = createParamBinding( modelParamBinding );
if ( binding != null )
{
list.add( binding );
}
}
}
return list;
}
/**
* converts interval string values to integer values
*/
protected int parseInterval( String interval )
{
if ( DesignChoiceConstants.INTERVAL_YEAR.equals( interval ) )
{
return IGroupDefinition.YEAR_INTERVAL;
}
if ( DesignChoiceConstants.INTERVAL_MONTH.equals( interval ) )
{
return IGroupDefinition.MONTH_INTERVAL;
}
if ( DesignChoiceConstants.INTERVAL_WEEK.equals( interval ) ) //
{
return IGroupDefinition.WEEK_INTERVAL;
}
if ( DesignChoiceConstants.INTERVAL_QUARTER.equals( interval ) )
{
return IGroupDefinition.QUARTER_INTERVAL;
}
if ( DesignChoiceConstants.INTERVAL_DAY.equals( interval ) )
{
return IGroupDefinition.DAY_INTERVAL;
}
if ( DesignChoiceConstants.INTERVAL_HOUR.equals( interval ) )
{
return IGroupDefinition.HOUR_INTERVAL;
}
if ( DesignChoiceConstants.INTERVAL_MINUTE.equals( interval ) )
{
return IGroupDefinition.MINUTE_INTERVAL;
}
if ( DesignChoiceConstants.INTERVAL_PREFIX.equals( interval ) )
{
return IGroupDefinition.STRING_PREFIX_INTERVAL;
}
if ( DesignChoiceConstants.INTERVAL_SECOND.equals( interval ) )
{
return IGroupDefinition.SECOND_INTERVAL;
}
if ( DesignChoiceConstants.INTERVAL_INTERVAL.equals( interval ) )
{
return IGroupDefinition.NUMERIC_INTERVAL;
}
return IGroupDefinition.NO_INTERVAL;
}
/**
* @param direction
* "asc" or "desc" string
* @return integer value defined in <code>ISortDefn</code>
*/
protected int parseSortDirection( String direction )
{
if ( "asc".equals( direction ) ) //$NON-NLS-1$
return ISortDefinition.SORT_ASC;
if ( "desc".equals( direction ) ) //$NON-NLS-1$
return ISortDefinition.SORT_DESC;
assert false;
return 0;
}
}
} | engine/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/data/dte/ReportQueryBuilder.java | /*******************************************************************************
* Copyright (c) 2004 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.report.engine.data.dte;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.eclipse.birt.core.exception.BirtException;
import org.eclipse.birt.data.engine.api.IBaseExpression;
import org.eclipse.birt.data.engine.api.IBaseQueryDefinition;
import org.eclipse.birt.data.engine.api.IBaseTransform;
import org.eclipse.birt.data.engine.api.IFilterDefinition;
import org.eclipse.birt.data.engine.api.IGroupDefinition;
import org.eclipse.birt.data.engine.api.IInputParameterBinding;
import org.eclipse.birt.data.engine.api.IQueryDefinition;
import org.eclipse.birt.data.engine.api.ISortDefinition;
import org.eclipse.birt.data.engine.api.ISubqueryDefinition;
import org.eclipse.birt.data.engine.api.querydefn.BaseQueryDefinition;
import org.eclipse.birt.data.engine.api.querydefn.ConditionalExpression;
import org.eclipse.birt.data.engine.api.querydefn.FilterDefinition;
import org.eclipse.birt.data.engine.api.querydefn.GroupDefinition;
import org.eclipse.birt.data.engine.api.querydefn.InputParameterBinding;
import org.eclipse.birt.data.engine.api.querydefn.QueryDefinition;
import org.eclipse.birt.data.engine.api.querydefn.ScriptExpression;
import org.eclipse.birt.data.engine.api.querydefn.SortDefinition;
import org.eclipse.birt.data.engine.api.querydefn.SubqueryDefinition;
import org.eclipse.birt.report.engine.adapter.ModelDteApiAdapter;
import org.eclipse.birt.report.engine.api.EngineException;
import org.eclipse.birt.report.engine.content.IStyle;
import org.eclipse.birt.report.engine.executor.ExecutionContext;
import org.eclipse.birt.report.engine.extension.IReportItemQuery;
import org.eclipse.birt.report.engine.extension.internal.ExtensionManager;
import org.eclipse.birt.report.engine.i18n.MessageConstants;
import org.eclipse.birt.report.engine.ir.ActionDesign;
import org.eclipse.birt.report.engine.ir.CellDesign;
import org.eclipse.birt.report.engine.ir.DataItemDesign;
import org.eclipse.birt.report.engine.ir.DefaultReportItemVisitorImpl;
import org.eclipse.birt.report.engine.ir.DrillThroughActionDesign;
import org.eclipse.birt.report.engine.ir.Expression;
import org.eclipse.birt.report.engine.ir.ExtendedItemDesign;
import org.eclipse.birt.report.engine.ir.FreeFormItemDesign;
import org.eclipse.birt.report.engine.ir.GridItemDesign;
import org.eclipse.birt.report.engine.ir.GroupDesign;
import org.eclipse.birt.report.engine.ir.HighlightDesign;
import org.eclipse.birt.report.engine.ir.HighlightRuleDesign;
import org.eclipse.birt.report.engine.ir.ImageItemDesign;
import org.eclipse.birt.report.engine.ir.LabelItemDesign;
import org.eclipse.birt.report.engine.ir.ListBandDesign;
import org.eclipse.birt.report.engine.ir.ListGroupDesign;
import org.eclipse.birt.report.engine.ir.ListItemDesign;
import org.eclipse.birt.report.engine.ir.ListingDesign;
import org.eclipse.birt.report.engine.ir.MapDesign;
import org.eclipse.birt.report.engine.ir.MapRuleDesign;
import org.eclipse.birt.report.engine.ir.MultiLineItemDesign;
import org.eclipse.birt.report.engine.ir.Report;
import org.eclipse.birt.report.engine.ir.ReportItemDesign;
import org.eclipse.birt.report.engine.ir.RowDesign;
import org.eclipse.birt.report.engine.ir.TableBandDesign;
import org.eclipse.birt.report.engine.ir.TableGroupDesign;
import org.eclipse.birt.report.engine.ir.TableItemDesign;
import org.eclipse.birt.report.engine.ir.TextItemDesign;
import org.eclipse.birt.report.model.api.DataSetHandle;
import org.eclipse.birt.report.model.api.ExtendedItemHandle;
import org.eclipse.birt.report.model.api.FilterConditionHandle;
import org.eclipse.birt.report.model.api.GroupHandle;
import org.eclipse.birt.report.model.api.ListHandle;
import org.eclipse.birt.report.model.api.ListingHandle;
import org.eclipse.birt.report.model.api.ParamBindingHandle;
import org.eclipse.birt.report.model.api.ReportItemHandle;
import org.eclipse.birt.report.model.api.SlotHandle;
import org.eclipse.birt.report.model.api.SortKeyHandle;
import org.eclipse.birt.report.model.api.TableHandle;
import org.eclipse.birt.report.model.api.elements.DesignChoiceConstants;
/**
* visit the report design and prepare all report queries and sub-queries to
* send to data engine
*
* @version $Revision: 1.48 $ $Date: 2006/01/13 04:56:58 $
*/
public class ReportQueryBuilder
{
protected static Logger logger = Logger.getLogger( ReportQueryBuilder.class
.getName( ) );
public ReportQueryBuilder( )
{
}
/**
* @param report
* the entry point to the report design
* @param context
* the execution context
*/
public void build( Report report, ExecutionContext context )
{
new QueryBuilderVisitor( ).buildQuery( report, context );
}
/**
* The visitor class that actually builds the report query
*/
protected class QueryBuilderVisitor extends DefaultReportItemVisitorImpl
{
/**
* query and it's IDs
*/
protected HashMap queryIDs;
/**
* a collection of all the queries
*/
protected Collection queries;
/**
* the query stack. The top stores the query that is currently prepared.
* Needed because we could have nested queries
*/
protected LinkedList queryStack = new LinkedList( );
/**
* the total number of queries created in this report
*/
protected int queryCount = 0;
/**
* a collection of the expressions on the CURRENT query
*/
protected Collection expressions;
/**
* the expression stack. This is a link list of collections, not a
* link-list of individual expressions.
*/
protected LinkedList expressionStack = new LinkedList( );
/* report item query stack
*
*/
protected LinkedList reportItemQueryStack;
/**
* entry point to the report
*/
protected Report report;
/**
* the execution context
*/
protected ExecutionContext context;
/**
* create report query definitions for this report.
*
* @param report
* entry point to the report
* @param context
* the execution context
*/
public void buildQuery( Report report, ExecutionContext context )
{
this.report = report;
this.context = context;
queries = report.getQueries( );
// first clear the collection in case the caller call this function
// more than once.
queries.clear( );
queryIDs = report.getQueryIDs( );
queryIDs.clear( );
// visit report
for ( int i = 0; i < report.getContentCount( ); i++ )
report.getContent( i ).accept( this, null );
}
/**
* Handles query creation and initialization with report-item related
* expressions
*
* @param item
* report item
*/
private BaseQueryDefinition prepareVisit( ReportItemDesign item )
{
BaseQueryDefinition tempQuery = null;
if ( item instanceof ListingDesign )
tempQuery = createQuery( (ListingDesign) item );
else
tempQuery = createQuery( item );
if ( tempQuery != null )
{
pushQuery( tempQuery );
pushExpressions( tempQuery.getRowExpressions( ) );
}
return tempQuery;
}
/**
* Clean up stack after visiting a report item
*/
private void finishVisit( BaseQueryDefinition query )
{
if ( query != null )
{
popExpressions( );
popQuery( );
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.ir.ReportItemVisitor#visitFreeFormItem(org.eclipse.birt.report.engine.ir.FreeFormItemDesign)
*/
public Object visitFreeFormItem( FreeFormItemDesign container,
Object value )
{
BaseQueryDefinition query = prepareVisit( container );
handleReportItemExpressions( container );
for ( int i = 0; i < container.getItemCount( ); i++ )
container.getItem( i ).accept( this, value );
finishVisit( query );
return value;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.ir.ReportItemVisitor#visitGridItem(org.eclipse.birt.report.engine.ir.GridItemDesign)
*/
public Object visitGridItem( GridItemDesign grid, Object value )
{
BaseQueryDefinition query = prepareVisit( grid );
handleReportItemExpressions( grid );
for ( int i = 0; i < grid.getColumnCount( ); i++ )
{
// ColumnDesign column = grid.getColumn( i );
// handleStyle( column.getStyle( ) );
}
for ( int i = 0; i < grid.getRowCount( ); i++ )
handleRow( grid.getRow( i ), value );
finishVisit( query );
return value;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.ir.IReportItemVisitor#visitImageItem(org.eclipse.birt.report.engine.ir.ImageItemDesign)
*/
public Object visitImageItem( ImageItemDesign image, Object value )
{
BaseQueryDefinition query = prepareVisit( image );
handleReportItemExpressions( image );
handleAction( image.getAction( ) );
if ( image.getImageSource( ) == ImageItemDesign.IMAGE_EXPRESSION )
{
addExpression( image.getImageExpression( ) );
addExpression( image.getImageFormat( ) );
}
else if ( image.getImageSource( ) == ImageItemDesign.IMAGE_URI
|| image.getImageSource( ) == ImageItemDesign.IMAGE_FILE )
{
addExpression( image.getImageUri( ) );
}
finishVisit( query );
return value;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.ir.ReportItemVisitor#visitLabelItem(org.eclipse.birt.report.engine.ir.LabelItemDesign)
*/
public Object visitLabelItem( LabelItemDesign label, Object value )
{
BaseQueryDefinition query = prepareVisit( label );
handleReportItemExpressions( label );
handleAction( label.getAction( ) );
finishVisit( query );
return value;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.ir.IReportItemVisitor#visitExtendedItem(org.eclipse.birt.report.engine.ir.ExtendedItemDesign)
*/
public Object visitExtendedItem( ExtendedItemDesign item, Object value )
{
// create user-defined generation-time helper object
ExtendedItemHandle handle = (ExtendedItemHandle) item.getHandle( );
String tagName = handle.getExtensionName( );
// TODO: check in plugin registry whetherthe needQuery property is
// set to host or item.
// Only do the following for "host"
IReportItemQuery itemQuery = ExtensionManager.getInstance( )
.createQueryItem( tagName );
IBaseQueryDefinition[] queries = null;
IBaseQueryDefinition parentQuery = getParentQuery( );
IBaseTransform parentTrans = getTransform( );
if ( itemQuery != null )
{
try
{
itemQuery.setModelObject( handle );
queries = itemQuery.getReportQueries( parentQuery );
}
catch ( BirtException ex )
{
logger.log( Level.WARNING, ex.getMessage( ), ex );
}
if ( queries != null )
{
item.setQueries( queries );
for ( int i = 0; i < queries.length; i++ )
{
// only a regular query need add to list
if ( queries[i] != null )
{
if ( queries[i] instanceof IQueryDefinition )
{
this.queryIDs.put( queries[i], String
.valueOf( item.getID( ) )
+ "_" + String.valueOf( i ) );
this.queries.add( queries[i] );
// to support parameter binding with data
// related expression in report query
Collection bindings = ( (IQueryDefinition) queries[i] )
.getInputParamBindings( );
if ( bindings.size( ) > 0 )
{
if ( parentTrans != null )
{
Iterator iter = bindings.iterator( );
while ( iter.hasNext( ) )
{
IInputParameterBinding binding = (IInputParameterBinding) iter
.next( );
parentTrans.getRowExpressions( )
.add( binding.getExpr( ) );
}
}
}
}
else if ( queries[i] instanceof ISubqueryDefinition )
{
// TODO: chart engine make a mistake here
if ( parentTrans != null )
{
parentTrans.getSubqueries( ).add(
queries[i] );
}
}
registerQueryAndElement( queries[i], item );
report.getQueryToValueExprMap( ).put( queries[i],
queries[i].getRowExpressions( ) );
}
}
if ( queries.length > 0 )
{
IBaseQueryDefinition query = queries[0];
if ( query != null )
{
item.setQuery( query );
pushQuery( query );
pushExpressions( query.getRowExpressions( ) );
handleReportItemExpressions( item );
// handleActionExpressions(item.getAction());
popExpressions( );
popQuery( );
}
}
}
}
return value;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.ir.ReportItemVisitor#visitListItem(org.eclipse.birt.report.engine.ir.ListItemDesign)
*/
public Object visitListItem( ListItemDesign list, Object value )
{
BaseQueryDefinition query = prepareVisit( list );
if ( query == null )
{
visitListBand( list.getHeader( ), value );
visitListBand( list.getFooter( ), value );
}
else
{
pushReportItemQuery( query );
pushExpressions( query.getBeforeExpressions( ) );
handleReportItemExpressions( list );
visitListBand( list.getHeader( ), value );
popExpressions( );
popReportItemQuery( );
SlotHandle groupsSlot = ( (ListHandle) list.getHandle( ) )
.getGroups( );
pushReportItemQuery( query );
for ( int i = 0; i < list.getGroupCount( ); i++ )
{
handleListGroup( list.getGroup( i ),
(GroupHandle) groupsSlot.get( i ), value );
}
popReportItemQuery( );
if ( list.getDetail( ).getContentCount( ) != 0 )
{
query.setUsesDetails( true );
}
pushReportItemQuery( query );
pushExpressions( query.getRowExpressions( ) );
visitListBand( list.getDetail( ), value );
popExpressions( );
popReportItemQuery( );
pushExpressions( query.getAfterExpressions( ) );
visitListBand( list.getFooter( ), value );
popExpressions( );
}
finishVisit( query );
registerQueryAndElement( query, list );
return value;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.ir.ReportItemVisitor#visitTextItem(org.eclipse.birt.report.engine.ir.TextItemDesign)
*/
public Object visitTextItem( TextItemDesign text, Object value )
{
BaseQueryDefinition query = prepareVisit( text );
handleReportItemExpressions( text );
HashMap exprs = text.getExpressions( );
if ( exprs != null )
{
Iterator iter = exprs.values( ).iterator( );
while ( iter.hasNext( ) )
{
IBaseExpression expr = (IBaseExpression) iter.next( );
addExpression( expr );
}
}
finishVisit( query );
return value;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.ir.ReportItemVisitor#visitTableItem(org.eclipse.birt.report.engine.ir.TableItemDesign)
*/
public Object visitTableItem( TableItemDesign table, Object value )
{
BaseQueryDefinition query = prepareVisit( table );
for ( int i = 0; i < table.getColumnCount( ); i++ )
{
// ColumnDesign column = table.getColumn( i );
// handleStyle( column.getStyle( ) );
}
if ( query == null )
{
handleTableBand( table.getHeader( ), value );
handleTableBand( table.getFooter( ), value );
}
else
{
pushExpressions( query.getBeforeExpressions( ) );
handleReportItemExpressions( table );
handleTableBand( table.getHeader( ), value );
popExpressions( );
SlotHandle groupsSlot = ( (TableHandle) table.getHandle( ) )
.getGroups( );
pushReportItemQuery( query );
for ( int i = 0; i < table.getGroupCount( ); i++ )
{
handleTableGroup( table.getGroup( i ),
(GroupHandle) groupsSlot.get( i ), value );
}
popReportItemQuery( );
if ( table.getDetail( ).getRowCount( ) != 0 )
{
query.setUsesDetails( true );
}
pushReportItemQuery( query );
pushExpressions( query.getRowExpressions( ) );
handleTableBand( table.getDetail( ), value );
popExpressions( );
popReportItemQuery( );
pushExpressions( query.getAfterExpressions( ) );
handleTableBand( table.getFooter( ), value );
popExpressions( );
}
finishVisit( query );
registerQueryAndElement( query, table );
return value;
}
/*
* associate query with Table, List and Chart item design.
*/
private void registerQueryAndElement( IBaseQueryDefinition query,
ReportItemDesign reportItem )
{
assert query!=null && reportItem != null;
HashMap map = report.getReportItemToQueryMap( );
assert map != null;
map.put( query, reportItem );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.ir.ReportItemVisitor#visitMultiLineItem(org.eclipse.birt.report.engine.ir.MultiLineItemDesign)
*/
public Object visitMultiLineItem( MultiLineItemDesign multiLine,
Object value )
{
BaseQueryDefinition query = prepareVisit( multiLine );
handleReportItemExpressions( multiLine );
addExpression( multiLine.getContent( ) );
finishVisit( query );
return value;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.ir.IReportItemVisitor#visitDataItem(org.eclipse.birt.report.engine.ir.DataItemDesign)
*/
public Object visitDataItem( DataItemDesign data, Object value )
{
BaseQueryDefinition query = prepareVisit( data );
handleReportItemExpressions( data );
handleAction( data.getAction( ) );
addExpression( data.getValue( ) );
addtoValueExpressions( data );
finishVisit( query );
return value;
}
private void addtoValueExpressions( DataItemDesign data )
{
if( reportItemQueryStack == null || reportItemQueryStack.isEmpty() == true )
{
return ;
}
if( data.getValue( ) != null )
{
IBaseQueryDefinition query = (IBaseQueryDefinition)reportItemQueryStack
.getLast( );
assert query != null;
HashMap queryMap = report.getQueryToValueExprMap( );
assert queryMap != null;
HashMap exprToNameMap = report.getExprToNameMap( );
assert exprToNameMap != null;
ArrayList valueExprs = (ArrayList)queryMap.get( query );
if( valueExprs == null )
{
valueExprs = new ArrayList( );
}
if( valueExprs.contains( data.getValue( )) == false )
{
valueExprs.add( data.getValue( ));
if ( data.getName( ) != null )
{
exprToNameMap.put( data.getValue( ), data.getName( ) );
}
}
queryMap.put( query, valueExprs );
}
}
/**
* handle expressions common to all report items
*
* @param item
* a report item
*/
protected void handleReportItemExpressions( ReportItemDesign item )
{
if ( item.getVisibility( ) != null )
{
for ( int i = 0; i < item.getVisibility( ).count( ); i++ )
{
addExpression( item.getVisibility( ).getRule( i )
.getExpression( ) );
}
}
addExpression( item.getTOC( ) );
addExpression( item.getBookmark( ) );
addExpression( item.getOnCreate( ) );
// handleStyle( item.getStyle( ) );
handleHighlightExpressions( item.getHighlight( ) );
handleMapExpressions( item.getMap( ) );
handleNamedExpressions ( item.getNamedExpressions( ) );
}
/**
* handle named expression
* @param namedExpressions a map of of named expression
*/
protected void handleNamedExpressions( Map namedExpressions )
{
Collection exprs = namedExpressions.values();
Iterator exprIter = exprs.iterator();
while( exprIter.hasNext( ) )
{
addExpression( (Expression)exprIter.next() );
}
}
/**
* @param band
* the list band
*/
protected void visitListBand( ListBandDesign band, Object value )
{
for ( int i = 0; i < band.getContentCount( ); i++ )
{
band.getContent( i ).accept( this, value );
}
}
/**
* @param group
* a grouping in a list
* @param handle
* handle to a grouping element
*/
protected void handleListGroup( ListGroupDesign group,
GroupHandle handle, Object value )
{
IGroupDefinition groupDefn = handleGroup( group, handle );
pushQuery( groupDefn );
pushExpressions( groupDefn.getBeforeExpressions( ) );
visitListBand( group.getHeader( ), value );
popExpressions( );
pushExpressions( groupDefn.getAfterExpressions( ) );
visitListBand( group.getFooter( ), value );
popExpressions( );
popQuery( );
}
/**
* processes a table/list group
*/
protected IGroupDefinition handleGroup( GroupDesign group,
GroupHandle handle )
{
GroupDefinition groupDefn = new GroupDefinition( group.getName( ) );
groupDefn.setKeyExpression( handle.getKeyExpr( ) );
String interval = handle.getInterval( );
if ( interval != null )
{
groupDefn.setInterval( parseInterval( interval ) );
}
// inter-range
groupDefn.setIntervalRange( handle.getIntervalRange( ) );
// inter-start-value
groupDefn.setIntervalStart( handle.getIntervalBase( ) );
// sort-direction
String direction = handle.getSortDirection( );
if ( direction != null )
{
groupDefn.setSortDirection( parseSortDirection( direction ) );
}
groupDefn.getSorts( ).addAll( createSorts( handle ) );
groupDefn.getFilters( ).addAll( createFilters( handle ) );
getParentQuery( ).getGroups( ).add( groupDefn );
return groupDefn;
}
/**
* processes a band in a table
*/
protected void handleTableBand( TableBandDesign band, Object value )
{
for ( int i = 0; i < band.getRowCount( ); i++ )
handleRow( band.getRow( i ), value );
}
/**
* processes a table group
*/
protected void handleTableGroup( TableGroupDesign group,
GroupHandle handle, Object value )
{
IGroupDefinition groupDefn = handleGroup( group, handle );
pushQuery( groupDefn );
pushExpressions( groupDefn.getBeforeExpressions( ) );
handleTableBand( group.getHeader( ), value );
popExpressions( );
pushExpressions( groupDefn.getAfterExpressions( ) );
handleTableBand( group.getFooter( ), value );
popExpressions( );
popQuery( );
}
/**
* handle style, which may contain highlight/mapping expressions
*
* @param style
* style design
*/
protected void handleStyle( IStyle style )
{
/*
* if ( style != null ) { handleHighlight( style.getHighlight( ) );
* handleMap( style.getMap( ) ); }
*/
}
/**
* handle mapping expressions
*/
protected void handleMapExpressions( MapDesign map )
{
if ( map != null )
{
for ( int i = 0; i < map.getRuleCount( ); i++ )
{
MapRuleDesign rule = map.getRule( i );
if ( rule != null )
addExpression( rule.getConditionExpr( ) );
}
}
}
/**
* handle highlight expressions
*/
protected void handleHighlightExpressions( HighlightDesign highlight )
{
if ( highlight != null )
{
for ( int i = 0; i < highlight.getRuleCount( ); i++ )
{
HighlightRuleDesign rule = highlight.getRule( i );
if ( rule != null )
addExpression( rule.getConditionExpr( ) );
}
}
}
/**
* handles action expressions, i.e, book-mark and hyper-link
* expressions.
*/
protected void handleAction( ActionDesign action )
{
if ( action != null )
{
switch ( action.getActionType( ) )
{
case ActionDesign.ACTION_BOOKMARK :
addExpression( action.getBookmark( ) );
break;
case ActionDesign.ACTION_DRILLTHROUGH :
DrillThroughActionDesign drillThrough = action
.getDrillThrough( );
if ( drillThrough != null )
{
addExpression( drillThrough.getBookmark( ) );
if ( drillThrough.getParameters( ) != null )
{
Iterator ite = drillThrough.getParameters( )
.entrySet( ).iterator( );
while ( ite.hasNext( ) )
{
Map.Entry entry = (Map.Entry) ite.next( );
assert entry.getValue( ) instanceof Expression;
addExpression( (Expression) entry
.getValue( ) );
}
}
}
break;
case ActionDesign.ACTION_HYPERLINK :
addExpression( action.getHyperlink( ) );
break;
default :
assert false;
}
}
}
/**
* visit content of a row
*/
protected void handleRow( RowDesign row, Object value )
{
// handleStyle( row.getStyle( ) );
if ( row.getVisibility( ) != null )
{
for ( int i = 0; i < row.getVisibility( ).count( ); i++ )
addExpression( row.getVisibility( ).getRule( i )
.getExpression( ) );
}
addExpression(row.getTOC());
addExpression( row.getBookmark( ) );
for ( int i = 0; i < row.getCellCount( ); i++ )
{
CellDesign cell = row.getCell( i );
if ( cell != null )
{
handleCell( cell, value );
}
}
}
/**
* handles a cell in a row
*/
protected void handleCell( CellDesign cell, Object value )
{
// handleStyle( cell.getStyle( ) );
for ( int i = 0; i < cell.getContentCount( ); i++ )
cell.getContent( i ).accept( this, value );
}
/**
* A helper function for adding expression collection to stack
*/
protected void pushExpressions( Collection newExpressions )
{
this.expressionStack.addLast( this.expressions );
this.expressions = newExpressions;
}
/**
* A helper function for removing expression collection from stack
*/
protected void popExpressions( )
{
assert !expressionStack.isEmpty( );
this.expressions = (Collection) expressionStack.removeLast( );
}
protected void pushReportItemQuery( IBaseQueryDefinition query )
{
if( this.reportItemQueryStack == null )
{
this.reportItemQueryStack = new LinkedList( );
}
this.reportItemQueryStack.addLast( query );
}
protected void popReportItemQuery( )
{
assert this.reportItemQueryStack.isEmpty( ) == false;
this.reportItemQueryStack.removeLast( );
}
/**
* A helper function for adding a query to query stack
*/
protected void pushQuery( IBaseTransform query )
{
this.queryStack.addLast( query );
}
/**
* A helper function for removing a query from query stack
*/
protected void popQuery( )
{
assert !queryStack.isEmpty( );
queryStack.removeLast( );
}
/**
* add expression to the expression collection on top of the expressions
* stack
*
* @param expr
* expression to be added
*/
protected void addExpression( IBaseExpression expr )
{
// expressions may be null, which means the expression is in the
// topmost element, and has no data set associated with it.
if ( expr != null && expressions != null )
expressions.add( expr );
}
/**
* @return topmost element on query stack
*/
protected IBaseTransform getTransform( )
{
if ( queryStack.isEmpty( ) )
return null;
return (IBaseTransform) queryStack.getLast( );
}
/**
* @return the parent query for the current report item
*/
protected BaseQueryDefinition getParentQuery( )
{
if ( queryStack.isEmpty( ) )
return null;
for ( int i = queryStack.size( ) - 1; i >= 0; i-- )
{
if ( queryStack.get( i ) instanceof BaseQueryDefinition )
return (BaseQueryDefinition) queryStack.get( i );
}
return null;
}
/**
* @return the expression collection
*/
protected Collection getExpressions( )
{
return expressions;
}
/**
* @return a unique query name, based on a simple integer counter
*/
protected String createUniqueQueryName( )
{
queryCount++;
return String.valueOf( queryCount );
}
/**
* create query for non-listing report item
*
* @param item
* report item
* @return a report query
*/
protected BaseQueryDefinition createQuery( ReportItemDesign item )
{
DataSetHandle dsHandle = ( (ReportItemHandle) item.getHandle( ) )
.getDataSet( );
if ( dsHandle == null )
{
// dataset reference error
String dsName = (String) ( (ReportItemHandle) item.getHandle( ) )
.getProperty( ReportItemHandle.DATA_SET_PROP );
if ( dsName != null && dsName.length( ) > 0 )
{
context.addException( item.getHandle( ),
new EngineException(
MessageConstants.UNDEFINED_DATASET_ERROR,
dsName ) );
}
}
if ( dsHandle != null )
{
ReportItemHandle riHandle = (ReportItemHandle) item.getHandle( );
QueryDefinition query = new QueryDefinition( getParentQuery( ) );
query.setDataSetName( dsHandle.getQualifiedName( ) );
ArrayList bindings = createParamBindings( riHandle
.paramBindingsIterator( ) );
if ( bindings.size( ) > 0 )
{
query.getInputParamBindings( ).addAll( bindings );
IBaseTransform trans = getTransform( );
if ( trans != null )
{
for ( int i = 0; i < bindings.size( ); i++ )
{
IInputParameterBinding binding = (IInputParameterBinding) bindings
.get( i );
trans.getRowExpressions( ).add( binding.getExpr( ) );
}
}
}
this.queryIDs.put( query, String.valueOf( item.getID( ) ) );
this.queries.add( query );
item.setQuery( query );
return query;
}
return null;
}
/**
* create query for listing report item
*
* @param listing
* the listing item
* @return a report query definition
*/
protected BaseQueryDefinition createQuery( ListingDesign listing )
{
// creates its own query
BaseQueryDefinition query = createQuery( (ReportItemDesign) listing );
if ( query != null )
{
query.getSorts( ).addAll( createSorts( listing ) );
query.getFilters( ).addAll( createFilters( listing ) );
return query;
}
// creates a subquery, instead
if ( getTransform( ) == null )
{
return null;
}
String name = createUniqueQueryName( );
SubqueryDefinition subQuery = new SubqueryDefinition( name );
listing.setQuery( subQuery );
subQuery.getSorts( ).addAll( createSorts( listing ) );
subQuery.getFilters( ).addAll( createFilters( listing ) );
getTransform( ).getSubqueries( ).add( subQuery );
return subQuery;
}
/**
* get Localized string by the resouce key and <code>Locale</code>
* object in <code>context</code>
*
* @param resourceKey
* the resource key
* @param text
* the default value
* @return the localized string if it is defined in report deign, else
* return the default value
*/
protected String getLocalizedString( String resourceKey, String text )
{
if ( resourceKey == null )
{
return text;
}
String ret = report.getMessage( resourceKey, context.getLocale( ) );
if ( ret == null )
{
logger.log( Level.SEVERE, "get resource error, resource key:" //$NON-NLS-1$
+ resourceKey + " Locale:" //$NON-NLS-1$
+ context.getLocale( ).toString( ) );
return text;
}
return ret;
}
/**
* Walk through the DOM tree from a text item to collect the embedded
* expressions and format expressions
*
* After evaluating, the second child node of the embedded expression
* node holds the value if no error exists.
*
* @param node
* a node in the DOM tree
* @param text
* the text object
*/
/*
* protected void getEmbeddedExpression( Node node, TextItemDesign text ) {
* if ( node.getNodeType( ) == Node.ELEMENT_NODE ) { if (
* node.getNodeName( ).equals( "value-of" ) ) //$NON-NLS-1$ { if (
* !text.hasExpression( node.getFirstChild( ) .getNodeValue( ) ) ) {
* Expression expr = new Expression( node.getFirstChild( )
* .getNodeValue( ) ); this.addExpression( expr ); text.addExpression(
* node.getFirstChild( ) .getNodeValue( ), expr );
*
* return; } } else if ( node.getNodeName( ).equals( "image" ) )
* //$NON-NLS-1$ {
*
* String imageType = ( (Element) ( node ) ) .getAttribute( "type" );
* //$NON-NLS-1$
*
* if ( "expr".equals( imageType ) ) //$NON-NLS-1$ { if (
* !text.hasExpression( node.getFirstChild( ) .getNodeValue( ) ) ) {
* Expression expr = new Expression( node .getFirstChild(
* ).getNodeValue( ) );
*
* this.addExpression( expr ); text.addExpression( node.getFirstChild( )
* .getNodeValue( ), expr ); } } return; } //call recursively for ( Node
* child = node.getFirstChild( ); child != null; child = child
* .getNextSibling( ) ) { getEmbeddedExpression( child, text ); } } }
*/
/**
* create one Filter given a filter condition handle
*
* @param handle
* a filter condition handle
* @return the filter
*/
private IFilterDefinition createFilter( FilterConditionHandle handle )
{
String filterExpr = handle.getExpr( );
if ( filterExpr == null || filterExpr.length( ) == 0 )
return null; // no filter defined
// converts to DtE exprFilter if there is no operator
String filterOpr = handle.getOperator( );
if ( filterOpr == null || filterOpr.length( ) == 0 )
return new FilterDefinition( new ScriptExpression( filterExpr ) );
/*
* has operator defined, try to convert filter condition to
* operator/operand style column filter with 0 to 2 operands
*/
String column = filterExpr;
int dteOpr = ModelDteApiAdapter.toDteFilterOperator( filterOpr );
String operand1 = handle.getValue1( );
String operand2 = handle.getValue2( );
return new FilterDefinition( new ConditionalExpression( column,
dteOpr, operand1, operand2 ) );
}
/**
* create a filter array given a filter condition handle iterator
*
* @param iter
* the iterator
* @return filter array
*/
private ArrayList createFilters( Iterator iter )
{
ArrayList filters = new ArrayList( );
if ( iter != null )
{
while ( iter.hasNext( ) )
{
FilterConditionHandle filterHandle = (FilterConditionHandle) iter
.next( );
IFilterDefinition filter = createFilter( filterHandle );
filters.add( filter );
}
}
return filters;
}
/**
* create filter array given a Listing design element
*
* @param listing
* the ListingDesign
* @return the filter array
*/
public ArrayList createFilters( ListingDesign listing )
{
return createFilters( ( (ListingHandle) listing.getHandle( ) )
.filtersIterator( ) );
}
/**
* create fileter array given a DataSetHandle
*
* @param dataSet
* the DataSetHandle
* @return the filer array
*/
public ArrayList createFilters( DataSetHandle dataSet )
{
return createFilters( dataSet.filtersIterator( ) );
}
/**
* create filter array given a GroupHandle
*
* @param group
* the GroupHandle
* @return filter array
*/
public ArrayList createFilters( GroupHandle group )
{
return createFilters( group.filtersIterator( ) );
}
/**
* create one sort condition
*
* @param handle
* the SortKeyHandle
* @return the sort object
*/
private ISortDefinition createSort( SortKeyHandle handle )
{
SortDefinition sort = new SortDefinition( );
sort.setExpression( handle.getKey( ) );
sort.setSortDirection( handle.getDirection( ).equals(
DesignChoiceConstants.SORT_DIRECTION_ASC ) ? 0 : 1 );
return sort;
}
/**
* create all sort conditions given a sort key handle iterator
*
* @param iter
* the iterator
* @return sort array
*/
private ArrayList createSorts( Iterator iter )
{
ArrayList sorts = new ArrayList( );
if ( iter != null )
{
while ( iter.hasNext( ) )
{
SortKeyHandle handle = (SortKeyHandle) iter.next( );
sorts.add( createSort( handle ) );
}
}
return sorts;
}
/**
* create all sort conditions in a listing element
*
* @param listing
* ListingDesign
* @return the sort array
*/
protected ArrayList createSorts( ListingDesign listing )
{
return createSorts( ( (ListingHandle) listing.getHandle( ) )
.sortsIterator( ) );
}
/**
* create sort array by giving GroupHandle
*
* @param group
* the GroupHandle
* @return the sort array
*/
protected ArrayList createSorts( GroupHandle group )
{
return createSorts( group.sortsIterator( ) );
}
/**
* create input parameter binding
*
* @param handle
* @return
*/
protected IInputParameterBinding createParamBinding(
ParamBindingHandle handle )
{
if ( handle.getExpression( ) == null )
return null; // no expression is bound
ScriptExpression expr = new ScriptExpression( handle
.getExpression( ) );
// model provides binding by name only
return new InputParameterBinding( handle.getParamName( ), expr );
}
/**
* create input parameter bindings
*
* @param iter
* parameter bindings iterator
* @return a list of input parameter bindings
*/
protected ArrayList createParamBindings( Iterator iter )
{
ArrayList list = new ArrayList( );
if ( iter != null )
{
while ( iter.hasNext( ) )
{
ParamBindingHandle modelParamBinding = (ParamBindingHandle) iter
.next( );
IInputParameterBinding binding = createParamBinding( modelParamBinding );
if ( binding != null )
{
list.add( binding );
}
}
}
return list;
}
/**
* converts interval string values to integer values
*/
protected int parseInterval( String interval )
{
if ( DesignChoiceConstants.INTERVAL_YEAR.equals( interval ) )
{
return IGroupDefinition.YEAR_INTERVAL;
}
if ( DesignChoiceConstants.INTERVAL_MONTH.equals( interval ) )
{
return IGroupDefinition.MONTH_INTERVAL;
}
if ( DesignChoiceConstants.INTERVAL_WEEK.equals( interval ) ) //
{
return IGroupDefinition.WEEK_INTERVAL;
}
if ( DesignChoiceConstants.INTERVAL_QUARTER.equals( interval ) )
{
return IGroupDefinition.QUARTER_INTERVAL;
}
if ( DesignChoiceConstants.INTERVAL_DAY.equals( interval ) )
{
return IGroupDefinition.DAY_INTERVAL;
}
if ( DesignChoiceConstants.INTERVAL_HOUR.equals( interval ) )
{
return IGroupDefinition.HOUR_INTERVAL;
}
if ( DesignChoiceConstants.INTERVAL_MINUTE.equals( interval ) )
{
return IGroupDefinition.MINUTE_INTERVAL;
}
if ( DesignChoiceConstants.INTERVAL_PREFIX.equals( interval ) )
{
return IGroupDefinition.STRING_PREFIX_INTERVAL;
}
if ( DesignChoiceConstants.INTERVAL_SECOND.equals( interval ) )
{
return IGroupDefinition.SECOND_INTERVAL;
}
if ( DesignChoiceConstants.INTERVAL_INTERVAL.equals( interval ) )
{
return IGroupDefinition.NUMERIC_INTERVAL;
}
return IGroupDefinition.NO_INTERVAL;
}
/**
* @param direction
* "asc" or "desc" string
* @return integer value defined in <code>ISortDefn</code>
*/
protected int parseSortDirection( String direction )
{
if ( "asc".equals( direction ) ) //$NON-NLS-1$
return ISortDefinition.SORT_ASC;
if ( "desc".equals( direction ) ) //$NON-NLS-1$
return ISortDefinition.SORT_DESC;
assert false;
return 0;
}
}
} | bug122419, Add master page header and footer processes in buildQuery method
| engine/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/data/dte/ReportQueryBuilder.java | bug122419, Add master page header and footer processes in buildQuery method | <ide><path>ngine/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/data/dte/ReportQueryBuilder.java
<ide> import org.eclipse.birt.report.engine.ir.ListingDesign;
<ide> import org.eclipse.birt.report.engine.ir.MapDesign;
<ide> import org.eclipse.birt.report.engine.ir.MapRuleDesign;
<add>import org.eclipse.birt.report.engine.ir.MasterPageDesign;
<ide> import org.eclipse.birt.report.engine.ir.MultiLineItemDesign;
<ide> import org.eclipse.birt.report.engine.ir.Report;
<ide> import org.eclipse.birt.report.engine.ir.ReportItemDesign;
<ide> import org.eclipse.birt.report.engine.ir.RowDesign;
<add>import org.eclipse.birt.report.engine.ir.SimpleMasterPageDesign;
<ide> import org.eclipse.birt.report.engine.ir.TableBandDesign;
<ide> import org.eclipse.birt.report.engine.ir.TableGroupDesign;
<ide> import org.eclipse.birt.report.engine.ir.TableItemDesign;
<ide> * visit the report design and prepare all report queries and sub-queries to
<ide> * send to data engine
<ide> *
<del> * @version $Revision: 1.48 $ $Date: 2006/01/13 04:56:58 $
<add> * @version $Revision: 1.49 $ $Date: 2006/02/28 03:53:13 $
<ide> */
<ide> public class ReportQueryBuilder
<ide> {
<ide>
<ide> queryIDs = report.getQueryIDs( );
<ide> queryIDs.clear( );
<del>
<add>
<add> // visit master page
<add> for ( int i = 0; i < report.getPageSetup().getMasterPageCount( ); i++ )
<add> {
<add> MasterPageDesign masterPage = report.getPageSetup().getMasterPage( i );
<add> if ( masterPage != null )
<add> {
<add> SimpleMasterPageDesign pageDesign = (SimpleMasterPageDesign) masterPage;
<add> for ( int j = 0; j < pageDesign.getHeaderCount( ); j++ )
<add> {
<add> pageDesign.getHeader( j ).accept( this, null );
<add> }
<add> for ( int j = 0; j < pageDesign.getFooterCount( ); j++ )
<add> {
<add> pageDesign.getFooter( j ).accept( this, null );
<add> }
<add> }
<add> }
<add>
<ide> // visit report
<ide> for ( int i = 0; i < report.getContentCount( ); i++ )
<ide> report.getContent( i ).accept( this, null ); |
|
Java | mit | 29512e346229a5adfa1b32b072eda796232dee54 | 0 | testingbot/TestingBot-Jenkins-Plugin,jenkinsci/testingbot-plugin,testingbot/TestingBot-Jenkins-Plugin,jenkinsci/testingbot-plugin | package testingbot;
import hudson.Extension;
import hudson.model.AbstractBuild;
import hudson.model.InvisibleAction;
import hudson.model.ParameterValue;
import hudson.model.ParametersAction;
import hudson.model.TaskListener;
import hudson.model.listeners.RunListener;
import hudson.tasks.junit.CaseResult;
import hudson.tasks.junit.SuiteResult;
import hudson.tasks.junit.TestResult;
import hudson.tasks.test.AbstractTestResultAction;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import testingbot.TestingBotReportFactory;
import testingbot.TestingBotBuildObject;
public class TestingBotBuildSummary extends InvisibleAction {
private AbstractBuild<?,?> build;
public List<TestingBotBuildObject> sessionIds = new ArrayList<TestingBotBuildObject>();
private static Map<Integer,List<String>> sessions = new HashMap<Integer,List<String>>();
public TestingBotBuildSummary(AbstractBuild<?,?> build, List<TestingBotBuildObject> sessionIds) {
this.build = build;
this.sessionIds = sessionIds;
}
public List<TestingBotBuildObject> getSessionIds() {
return this.sessionIds;
}
@Extension
public static final class RunListenerImpl extends RunListener<AbstractBuild<?,?>> {
@Override
public void onCompleted(AbstractBuild<?, ?> r, TaskListener listener) {
TestResult testResult = (TestResult) r.getAction(AbstractTestResultAction.class).getResult();
List<TestingBotBuildObject> ids = new ArrayList<TestingBotBuildObject>();
for (SuiteResult sr : testResult.getSuites()) {
for (CaseResult cr : sr.getCases()) {
List<String> sessionIds = TestingBotReportFactory.findSessionIDs(cr);
TestingBotBuildObject tbo = new TestingBotBuildObject(sessionIds.get(0), cr.getClassName(), cr.getName(), cr.isPassed());
ids.add(tbo);
}
}
Logger.getLogger(TestingBotBuildSummary.class.getName()).log(Level.SEVERE, null, "try to get ids");
r.addAction(new TestingBotBuildSummary(r, ids));
}
}
} | src/main/java/testingbot/TestingBotBuildSummary.java | package testingbot;
import hudson.Extension;
import hudson.model.AbstractBuild;
import hudson.model.InvisibleAction;
import hudson.model.ParameterValue;
import hudson.model.ParametersAction;
import hudson.model.TaskListener;
import hudson.model.listeners.RunListener;
import hudson.tasks.junit.CaseResult;
import hudson.tasks.junit.SuiteResult;
import hudson.tasks.junit.TestResult;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import testingbot.TestingBotReportFactory;
import testingbot.TestingBotBuildObject;
public class TestingBotBuildSummary extends InvisibleAction {
private AbstractBuild<?,?> build;
public List<TestingBotBuildObject> sessionIds = new ArrayList<TestingBotBuildObject>();
private static Map<Integer,List<String>> sessions = new HashMap<Integer,List<String>>();
public TestingBotBuildSummary(AbstractBuild<?,?> build, List<TestingBotBuildObject> sessionIds) {
this.build = build;
this.sessionIds = sessionIds;
}
public List<TestingBotBuildObject> getSessionIds() {
return this.sessionIds;
}
@Extension
public static final class RunListenerImpl extends RunListener<AbstractBuild<?,?>> {
@Override
public void onCompleted(AbstractBuild<?, ?> r, TaskListener listener) {
TestResult testResult = (TestResult) r.getTestResultAction().getResult();
List<TestingBotBuildObject> ids = new ArrayList<TestingBotBuildObject>();
for (SuiteResult sr : testResult.getSuites()) {
for (CaseResult cr : sr.getCases()) {
List<String> sessionIds = TestingBotReportFactory.findSessionIDs(cr);
TestingBotBuildObject tbo = new TestingBotBuildObject(sessionIds.get(0), cr.getClassName(), cr.getName(), cr.isPassed());
ids.add(tbo);
}
}
Logger.getLogger(TestingBotBuildSummary.class.getName()).log(Level.SEVERE, null, "try to get ids");
r.addAction(new TestingBotBuildSummary(r, ids));
}
}
} | remove deprecated getTestResultAction() with getAction(AbstractTestResultAction.class)
| src/main/java/testingbot/TestingBotBuildSummary.java | remove deprecated getTestResultAction() with getAction(AbstractTestResultAction.class) | <ide><path>rc/main/java/testingbot/TestingBotBuildSummary.java
<ide> import hudson.tasks.junit.CaseResult;
<ide> import hudson.tasks.junit.SuiteResult;
<ide> import hudson.tasks.junit.TestResult;
<add>import hudson.tasks.test.AbstractTestResultAction;
<ide> import java.util.ArrayList;
<ide> import java.util.Collections;
<ide> import java.util.HashMap;
<ide>
<ide> @Override
<ide> public void onCompleted(AbstractBuild<?, ?> r, TaskListener listener) {
<del> TestResult testResult = (TestResult) r.getTestResultAction().getResult();
<add> TestResult testResult = (TestResult) r.getAction(AbstractTestResultAction.class).getResult();
<ide> List<TestingBotBuildObject> ids = new ArrayList<TestingBotBuildObject>();
<ide> for (SuiteResult sr : testResult.getSuites()) {
<ide> for (CaseResult cr : sr.getCases()) { |
|
Java | apache-2.0 | a4a5634280cb68081ca7567ade44d33805a6d2c5 | 0 | Team-CMPUT301F13T12/301-Project |
package ualberta.g12.adventurecreator.test;
/* Covers test cases for use cases:
* 2, 5, 16 , 9
*
* http://stackoverflow.com/questions/10845937/how-to-do-junit-testing-in-android
* Referenced Oct 23, 2013 for general format of Test class
*
* Actually modified from:
* http://www.vogella.com/articles/AndroidTesting/article.html#tutorial_unittestactivity
* Referenced Nov. 7, 2013
*
*/
import android.app.Activity;
import android.app.Instrumentation.ActivityMonitor;
import android.test.ActivityInstrumentationTestCase2;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.TextView;
import ualberta.g12.adventurecreator.MainActivity;
import ualberta.g12.adventurecreator.R;
import ualberta.g12.adventurecreator.Story;
import ualberta.g12.adventurecreator.StoryList;
import junit.framework.Assert;
import junit.framework.TestCase;
import java.util.List;
public class MainActivityTestCases extends
ActivityInstrumentationTestCase2<MainActivity> {
private MainActivity activity;
private TextView list_story_title;
private TextView list_story_author;
private ListView main_activity_listview;
private PopupMenu storyListPopupMenu;
private List<Story> stories;
private StoryList sl;
private ListView availableStoryList;
public MainActivityTestCases() {
super(MainActivity.class);
}
@Override
protected void setUp() throws Exception {
super.setUp();
setActivityInitialTouchMode(false);
activity = getActivity();
}
/* Test Cases - all start with "test" */
// Use Case 2, test 1/3
public void testBrowseStoryList() {
// add in multiple stories into the list
for (int i = 0; i < 15; i++) {
Story UserStory = new Story();
sl.addStory(UserStory);
/*
* Button button = (Button) findViewByid(R.id.menu_add_story);
* button.performClick(); Button button2 = (Button)
* findViewByid(R.id.editTextSave); button2.performClick();
*/
}
// starts the activity
activity = this.getActivity();
ListView view = (ListView) activity
.findViewById(ualberta.g12.adventurecreator.R.id.main_activity_listview);
// scroll textview
view.smoothScrollToPosition(100);
// check that user can scroll through the list
// Assert.assertEquals(100,
// Robolectric.shadowOf(view).getSmoothScrolledPosition());
// assertTrue("testBrowseStoryList is not yet implemented", false); //
// Test doesn't work yet
}
// Use Case 2, test 2/3
public void testBrowseNoScrollList() {
// add a single story into the list
Story UserStory = new Story();
sl.addStory(UserStory);
/*
* Button button = (Button) activity.findViewById(R.id.menu_add_story);
* button.performClick(); Button button2 = (Button)
* activity.findViewById(R.id.editTextSave); button2.performClick();
*/
ListView view = (ListView) activity
.findViewById(ualberta.g12.adventurecreator.R.id.main_activity_listview);
// scroll textview
view.smoothScrollToPosition(100);
// check if the list doesn't scroll with a single entry
// Assert.assertEquals(0,
// Robolectric.shadowOf(view).getSmoothScrolledPosition());
// assertTrue("testBrowseNoScrollList is not yet implemented", false);
// // Test does not work yet
}
// Use Case 2, test 3/3
public void testBrowseEmptyStoryList() {
// no notes added
// starts the activity
ListView view = (ListView) activity
.findViewById(ualberta.g12.adventurecreator.R.id.main_activity_listview);
assertNull(sl);
// assertTrue("testBrowseEmptyStoryList is not yet implemented", false);
}
// Use case 5, test 1/3
public void testEditExistingStory() {
activity = this.getActivity();
// Story s = getStoryFromClick();
// editStory(s);
// assert (s != null);
assertTrue("testEditExistingStory is not yet implemented", false);
}
// Use Case 16, test 1/1
// Use Cause 9 , test 1/3
public void testDownloadOtherUserStory() {
Story otherUserStory = new Story();
otherUserStory.setAuthor("OtherUser");
// uploads/publishes story
// addStory(otherUserStory);
// starts the activity (which will automatically find all
// available stories and load them into the availableStoryList)
activity = this.getActivity();
availableStoryList = (ListView) activity
.findViewById(ualberta.g12.adventurecreator.R.id.main_activity_listview);
/*
* storyListPopupMenu = (PopupMenu) activity
* .findViewById(ualberta.g12.adventurecreator
* .MainActivity.R.id.storyListPoupMenuID);
*/
// selects first (and only) story
availableStoryList.setSelection(0);
// causes popupMenu to open for selection
availableStoryList.performLongClick();
// gets download option if available
MenuItem downloadOption = storyListPopupMenu.getMenu().getItem(2);
// asserts user can Download the story
assertTrue(downloadOption.getTitle().equals("Download"));
// check that story is written by another user
// assertFalse(someStory.getAuthor().equals(getCurrentUserName()));
assertTrue("testDownloadOtherUserStory is not yet implemented", false);
}
// Use Case 9 , test 2/3
public void testDowloadStoryNoInternet() {
Story otherUserStory = new Story();
otherUserStory.setAuthor("OtherUser");
// uploads/publishes story
// addStory(otherUserStory);
// starts the activity (which will automatically find all
// available stories and load them into the availableStoryList)
activity = this.getActivity();
availableStoryList = (ListView) activity
.findViewById(ualberta.g12.adventurecreator.R.id.main_activity_listview);
/*
* storyListPopupMenu = (PopupMenu) activity
* .findViewById(activity.R.id.storyListPoupMenuID);
*/
// turn off the internet
// turnOffInternet();
// selects first (and only) story
availableStoryList.setSelection(0);
// causes popupMenu to open for selection
availableStoryList.performLongClick();
// gets download option if available ( not available)
MenuItem downloadOption = storyListPopupMenu.getMenu().getItem(2);
// assertTrue(downloadOption.equals(null));
assertTrue("testDownloadStoryNoInternet is not yet implemented", false);
}
// Use Case 9 , test 3/3
public void testDowloadStoryTurnOffInternet() {
Story otherUserStory = new Story();
otherUserStory.setAuthor("OtherUser");
// uploads/publishes story
// addStory(otherUserStory);
// starts the activity (which will automatically find all
// available stories and load them into the availableStoryList)
activity = this.getActivity();
availableStoryList = (ListView) activity
.findViewById(ualberta.g12.adventurecreator.R.id.main_activity_listview);
/*
* storyListPopupMenu = (PopupMenu) activity
* .findViewById(ualberta.g12.adventurecreator
* .R.id.storyListPoupMenuID);
*/
// selects first (and only) story
availableStoryList.setSelection(0);
// causes popupMenu to open for selection
availableStoryList.performLongClick();
// gets download option if available
MenuItem downloadOption = storyListPopupMenu.getMenu().getItem(2);
// turn off the internet
// turnOffInternet();
// asserts user can Download the story
// assertTrue(downloadOption.getTitle().equals("Download"));
assertTrue("testDownloadStoryTurnOffInternet is not yet implemented", false);
}
}
| test-test/src/ualberta/g12/adventurecreator/test/MainActivityTestCases.java | package ualberta.g12.adventurecreator.test;
/* Covers test cases for use cases:
* 2, 5, 16 , 9
*
* http://stackoverflow.com/questions/10845937/how-to-do-junit-testing-in-android
* Referenced Oct 23, 2013 for general format of Test class
*
* Actually modified from:
* http://www.vogella.com/articles/AndroidTesting/article.html#tutorial_unittestactivity
* Referenced Nov. 7, 2013
*
*/
import android.app.Activity;
import android.app.Instrumentation.ActivityMonitor;
import android.test.ActivityInstrumentationTestCase2;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.TextView;
import ualberta.g12.adventurecreator.MainActivity;
import ualberta.g12.adventurecreator.R;
import ualberta.g12.adventurecreator.Story;
import junit.framework.Assert;
import junit.framework.TestCase;
import java.util.List;
public class MainActivityTestCases extends
ActivityInstrumentationTestCase2<MainActivity> {
private Activity MainActivity;
private TextView list_story_title;
private TextView list_story_author;
private ListView main_activity_listview;
private PopupMenu storyListPopupMenu;
private List<Story> stories;
private StoryList sl;
public MainActivityTestCases() {
super(" ualberta.g12.adventurecreator.MainActivity", MainActivity.class);
}
@Override
protected void setUp() throws Exception {
super.setUp();
setActivityInitialTouchMode(false);
activity = getActivity();
}
/* Test Cases - all start with "test" */
// Use Case 2, test 1/3
public void testBrowseStoryList() {
//add in multiple stories into the list
for (int i = 0; i < 15; i++) {
Story UserStory = new Story();
sl.addStory(UserStory);
/* Button button = (Button) findViewByid(R.id.menu_add_story);
button.performClick();
Button button2 = (Button) findViewByid(R.id.editTextSave);
button2.performClick();*/
}
//starts the activity
activity = this.getActivity();
ListView view = (ListView) activity.findViewById(ualberta.g12.adventurecreator.MainActivity.R.id.main_activity_listview);
//scroll textview
view.smoothScrollToPosition(100);
//check that user can scroll through the list
Assert.assertEquals(100, Robolectric.shadowOf(view).getSmoothScrolledPosition());
// assertTrue("testBrowseStoryList is not yet implemented", false); // Test doesn't work yet
}
// Use Case 2, test 2/3
public void testBrowseNoScrollList() {
// add a single story into the list
Story UserStory = new Story();
sl.addStory(UserStory);
/*
Button button = (Button) activity.findViewById(R.id.menu_add_story);
button.performClick();
Button button2 = (Button) activity.findViewById(R.id.editTextSave);
button2.performClick();*/
ListView view = (ListView) activity
.findViewById(ualberta.g12.adventurecreator.R.id.main_activity_listview);
// scroll textview
view.smoothScrollToPosition(100);
// check if the list doesn't scroll with a single entry
Assert.assertEquals(0, Robolectric.shadowOf(view).getSmoothScrolledPosition());
//assertTrue("testBrowseNoScrollList is not yet implemented", false); // Test does not work yet
}
// Use Case 2, test 3/3
public void testBrowseEmptyStoryList() {
// no notes added
// starts the activity
ListView view = (ListView) activity
.findViewById(ualberta.g12.adventurecreator.R.id.main_activity_listview);
AssertNull(sl);
//assertTrue("testBrowseEmptyStoryList is not yet implemented", false);
}
// Use case 5, test 1/3
public void testEditExistingStory() {
activity = this.getActivity();
//Story s = getStoryFromClick();
//editStory(s);
//assert (s != null);
assertTrue("testEditExistingStory is not yet implemented", false);
}
// Use Case 16, test 1/1
// Use Cause 9 , test 1/3
public void testDownloadOtherUserStory() {
Story otherUserStory = new Story();
otherUserStory.setAuthor("OtherUser");
// uploads/publishes story
//addStory(otherUserStory);
// starts the activity (which will automatically find all
// available stories and load them into the availableStoryList)
activity = this.getActivity();
availableStoryList = (ListView) activity
.findViewById(ualberta.g12.adventurecreator.R.id.main_activity_listview);
/*storyListPopupMenu = (PopupMenu) activity
.findViewById(ualberta.g12.adventurecreator.MainActivity.R.id.storyListPoupMenuID);*/
// selects first (and only) story
availableStoryList.setSelection(0);
// causes popupMenu to open for selection
availableStoryList.performLongClick();
// gets download option if available
MenuItem downloadOption = storyListPopupMenu.getMenu().getItem(2);
// asserts user can Download the story
assertTrue(downloadOption.getTitle().equals("Download"));
// check that story is written by another user
//assertFalse(someStory.getAuthor().equals(getCurrentUserName()));
assertTrue("testDownloadOtherUserStory is not yet implemented", false);
}
// Use Case 9 , test 2/3
public void testDowloadStoryNoInternet() {
Story otherUserStory = new Story();
otherUserStory.setAuthor("OtherUser");
// uploads/publishes story
//addStory(otherUserStory);
// starts the activity (which will automatically find all
// available stories and load them into the availableStoryList)
activity = this.getActivity();
availableStoryList = (ListView) activity
.findViewById(ualberta.g12.adventurecreator.R.id.main_activity_listview);
/*storyListPopupMenu = (PopupMenu) activity
.findViewById(activity.R.id.storyListPoupMenuID);*/
// turn off the internet
//turnOffInternet();
// selects first (and only) story
availableStoryList.setSelection(0);
// causes popupMenu to open for selection
availableStoryList.performLongClick();
// gets download option if available ( not available)
MenuItem downloadOption = storyListPopupMenu.getMenu().getItem(2);
//assertTrue(downloadOption.equals(null));
assertTrue("testDownloadStoryNoInternet is not yet implemented", false);
}
// Use Case 9 , test 3/3
public void testDowloadStoryTurnOffInternet() {
Story otherUserStory = new Story();
otherUserStory.setAuthor("OtherUser");
// uploads/publishes story
//addStory(otherUserStory);
// starts the activity (which will automatically find all
// available stories and load them into the availableStoryList)
activity = this.getActivity();
availableStoryList = (ListView) activity
.findViewById(ualberta.g12.adventurecreator.R.id.main_activity_listview);
/* storyListPopupMenu = (PopupMenu) activity
.findViewById(ualberta.g12.adventurecreator.R.id.storyListPoupMenuID);*/
// selects first (and only) story
availableStoryList.setSelection(0);
// causes popupMenu to open for selection
availableStoryList.performLongClick();
// gets download option if available
MenuItem downloadOption = storyListPopupMenu.getMenu().getItem(2);
// turn off the internet
//turnOffInternet();
// asserts user can Download the story
//assertTrue(downloadOption.getTitle().equals("Download"));
assertTrue("testDownloadStoryTurnOffInternet is not yet implemented", false);
}
}
| Fixed errors
| test-test/src/ualberta/g12/adventurecreator/test/MainActivityTestCases.java | Fixed errors | <ide><path>est-test/src/ualberta/g12/adventurecreator/test/MainActivityTestCases.java
<add>
<ide> package ualberta.g12.adventurecreator.test;
<ide>
<ide> /* Covers test cases for use cases:
<ide> import ualberta.g12.adventurecreator.MainActivity;
<ide> import ualberta.g12.adventurecreator.R;
<ide> import ualberta.g12.adventurecreator.Story;
<add>import ualberta.g12.adventurecreator.StoryList;
<add>
<ide> import junit.framework.Assert;
<ide> import junit.framework.TestCase;
<add>
<ide> import java.util.List;
<ide>
<del>public class MainActivityTestCases extends
<add>public class MainActivityTestCases extends
<ide> ActivityInstrumentationTestCase2<MainActivity> {
<del> private Activity MainActivity;
<add> private MainActivity activity;
<ide> private TextView list_story_title;
<ide> private TextView list_story_author;
<ide> private ListView main_activity_listview;
<ide> private PopupMenu storyListPopupMenu;
<ide> private List<Story> stories;
<ide> private StoryList sl;
<add> private ListView availableStoryList;
<ide>
<ide> public MainActivityTestCases() {
<del> super(" ualberta.g12.adventurecreator.MainActivity", MainActivity.class);
<add> super(MainActivity.class);
<ide> }
<ide>
<ide> @Override
<ide>
<ide> // Use Case 2, test 1/3
<ide> public void testBrowseStoryList() {
<del> //add in multiple stories into the list
<del> for (int i = 0; i < 15; i++) {
<del> Story UserStory = new Story();
<del> sl.addStory(UserStory);
<del> /* Button button = (Button) findViewByid(R.id.menu_add_story);
<del> button.performClick();
<del> Button button2 = (Button) findViewByid(R.id.editTextSave);
<del> button2.performClick();*/
<del> }
<del>
<del> //starts the activity
<del> activity = this.getActivity();
<del> ListView view = (ListView) activity.findViewById(ualberta.g12.adventurecreator.MainActivity.R.id.main_activity_listview);
<del>
<del> //scroll textview
<del> view.smoothScrollToPosition(100);
<del>
<del> //check that user can scroll through the list
<del> Assert.assertEquals(100, Robolectric.shadowOf(view).getSmoothScrolledPosition());
<del> // assertTrue("testBrowseStoryList is not yet implemented", false); // Test doesn't work yet
<add> // add in multiple stories into the list
<add> for (int i = 0; i < 15; i++) {
<add> Story UserStory = new Story();
<add> sl.addStory(UserStory);
<add> /*
<add> * Button button = (Button) findViewByid(R.id.menu_add_story);
<add> * button.performClick(); Button button2 = (Button)
<add> * findViewByid(R.id.editTextSave); button2.performClick();
<add> */
<ide> }
<add>
<add> // starts the activity
<add> activity = this.getActivity();
<add> ListView view = (ListView) activity
<add> .findViewById(ualberta.g12.adventurecreator.R.id.main_activity_listview);
<add>
<add> // scroll textview
<add> view.smoothScrollToPosition(100);
<add>
<add> // check that user can scroll through the list
<add> // Assert.assertEquals(100,
<add> // Robolectric.shadowOf(view).getSmoothScrolledPosition());
<add> // assertTrue("testBrowseStoryList is not yet implemented", false); //
<add> // Test doesn't work yet
<add> }
<ide>
<ide> // Use Case 2, test 2/3
<ide> public void testBrowseNoScrollList() {
<ide> Story UserStory = new Story();
<ide> sl.addStory(UserStory);
<ide> /*
<del> Button button = (Button) activity.findViewById(R.id.menu_add_story);
<del> button.performClick();
<del> Button button2 = (Button) activity.findViewById(R.id.editTextSave);
<del> button2.performClick();*/
<add> * Button button = (Button) activity.findViewById(R.id.menu_add_story);
<add> * button.performClick(); Button button2 = (Button)
<add> * activity.findViewById(R.id.editTextSave); button2.performClick();
<add> */
<ide>
<ide> ListView view = (ListView) activity
<ide> .findViewById(ualberta.g12.adventurecreator.R.id.main_activity_listview);
<ide> view.smoothScrollToPosition(100);
<ide>
<ide> // check if the list doesn't scroll with a single entry
<del> Assert.assertEquals(0, Robolectric.shadowOf(view).getSmoothScrolledPosition());
<del> //assertTrue("testBrowseNoScrollList is not yet implemented", false); // Test does not work yet
<add> // Assert.assertEquals(0,
<add> // Robolectric.shadowOf(view).getSmoothScrolledPosition());
<add> // assertTrue("testBrowseNoScrollList is not yet implemented", false);
<add> // // Test does not work yet
<ide>
<ide> }
<ide>
<ide> ListView view = (ListView) activity
<ide> .findViewById(ualberta.g12.adventurecreator.R.id.main_activity_listview);
<ide>
<del> AssertNull(sl);
<del> //assertTrue("testBrowseEmptyStoryList is not yet implemented", false);
<add> assertNull(sl);
<add> // assertTrue("testBrowseEmptyStoryList is not yet implemented", false);
<ide> }
<ide>
<ide> // Use case 5, test 1/3
<ide> public void testEditExistingStory() {
<ide> activity = this.getActivity();
<del> //Story s = getStoryFromClick();
<del> //editStory(s);
<del> //assert (s != null);
<del>
<add> // Story s = getStoryFromClick();
<add> // editStory(s);
<add> // assert (s != null);
<add>
<ide> assertTrue("testEditExistingStory is not yet implemented", false);
<ide> }
<ide>
<ide> otherUserStory.setAuthor("OtherUser");
<ide>
<ide> // uploads/publishes story
<del> //addStory(otherUserStory);
<add> // addStory(otherUserStory);
<ide>
<ide> // starts the activity (which will automatically find all
<ide> // available stories and load them into the availableStoryList)
<ide> activity = this.getActivity();
<ide> availableStoryList = (ListView) activity
<ide> .findViewById(ualberta.g12.adventurecreator.R.id.main_activity_listview);
<del> /*storyListPopupMenu = (PopupMenu) activity
<del> .findViewById(ualberta.g12.adventurecreator.MainActivity.R.id.storyListPoupMenuID);*/
<add> /*
<add> * storyListPopupMenu = (PopupMenu) activity
<add> * .findViewById(ualberta.g12.adventurecreator
<add> * .MainActivity.R.id.storyListPoupMenuID);
<add> */
<ide>
<ide> // selects first (and only) story
<ide> availableStoryList.setSelection(0);
<ide> assertTrue(downloadOption.getTitle().equals("Download"));
<ide>
<ide> // check that story is written by another user
<del> //assertFalse(someStory.getAuthor().equals(getCurrentUserName()));
<add> // assertFalse(someStory.getAuthor().equals(getCurrentUserName()));
<ide> assertTrue("testDownloadOtherUserStory is not yet implemented", false);
<ide>
<ide> }
<ide> otherUserStory.setAuthor("OtherUser");
<ide>
<ide> // uploads/publishes story
<del> //addStory(otherUserStory);
<add> // addStory(otherUserStory);
<ide>
<ide> // starts the activity (which will automatically find all
<ide> // available stories and load them into the availableStoryList)
<ide> activity = this.getActivity();
<ide> availableStoryList = (ListView) activity
<ide> .findViewById(ualberta.g12.adventurecreator.R.id.main_activity_listview);
<del> /*storyListPopupMenu = (PopupMenu) activity
<del> .findViewById(activity.R.id.storyListPoupMenuID);*/
<add> /*
<add> * storyListPopupMenu = (PopupMenu) activity
<add> * .findViewById(activity.R.id.storyListPoupMenuID);
<add> */
<ide>
<ide> // turn off the internet
<del> //turnOffInternet();
<add> // turnOffInternet();
<ide>
<ide> // selects first (and only) story
<ide> availableStoryList.setSelection(0);
<ide> // gets download option if available ( not available)
<ide> MenuItem downloadOption = storyListPopupMenu.getMenu().getItem(2);
<ide>
<del> //assertTrue(downloadOption.equals(null));
<add> // assertTrue(downloadOption.equals(null));
<ide> assertTrue("testDownloadStoryNoInternet is not yet implemented", false);
<ide>
<ide> }
<ide> otherUserStory.setAuthor("OtherUser");
<ide>
<ide> // uploads/publishes story
<del> //addStory(otherUserStory);
<add> // addStory(otherUserStory);
<ide>
<ide> // starts the activity (which will automatically find all
<ide> // available stories and load them into the availableStoryList)
<ide> activity = this.getActivity();
<ide> availableStoryList = (ListView) activity
<ide> .findViewById(ualberta.g12.adventurecreator.R.id.main_activity_listview);
<del>/* storyListPopupMenu = (PopupMenu) activity
<del> .findViewById(ualberta.g12.adventurecreator.R.id.storyListPoupMenuID);*/
<add> /*
<add> * storyListPopupMenu = (PopupMenu) activity
<add> * .findViewById(ualberta.g12.adventurecreator
<add> * .R.id.storyListPoupMenuID);
<add> */
<ide>
<ide> // selects first (and only) story
<ide> availableStoryList.setSelection(0);
<ide> MenuItem downloadOption = storyListPopupMenu.getMenu().getItem(2);
<ide>
<ide> // turn off the internet
<del> //turnOffInternet();
<add> // turnOffInternet();
<ide>
<ide> // asserts user can Download the story
<del> //assertTrue(downloadOption.getTitle().equals("Download"));
<add> // assertTrue(downloadOption.getTitle().equals("Download"));
<ide> assertTrue("testDownloadStoryTurnOffInternet is not yet implemented", false);
<ide> }
<ide> |
|
Java | apache-2.0 | 040ebf999101fb173a2801ab71b60978f66f43a3 | 0 | janprill/fast-serialization,smorin/fast-serialization,doubleyoung/fast-serialization,slburson/fast-serialization,RuedigerMoeller/fast-serialization,xamde/fast-serialization,FrimaStudio/fast-serialization,smorin/fast-serialization,smorin/fast-serialization,slburson/fast-serialization,RuedigerMoeller/fast-serialization,RuedigerMoeller/fast-serialization,jtsay362/fast-serialization,RuedigerMoeller/fast-serialization,xamde/fast-serialization,doubleyoung/fast-serialization,doubleyoung/fast-serialization,janprill/fast-serialization,janprill/fast-serialization,jtsay362/fast-serialization,jtsay362/fast-serialization,xamde/fast-serialization,slburson/fast-serialization | /*
* Copyright (c) 2012, Ruediger Moeller. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*
*/
package org.nustaq.serialization.util;
import java.util.ArrayList;
import java.util.List;
/**
* Created with IntelliJ IDEA.
* User: ruedi
* Date: 20.11.12
* Time: 19:57
* To change this template use File | Settings | File Templates.
*/
public class FSTIdentity2IdMap {
private static final int RESERVE = 4;
private static final int MAX_DEPTH = 4;
static int[] prim = {
3, 5, 7, 11, 13, 17, 19, 23, 29, 37, 67, 97, 139,
211, 331, 641, 1097, 1531, 2207, 3121, 5059, 7607, 10891,
15901, 19993, 30223, 50077, 74231, 99991, 150001, 300017,
1000033, 1500041, 200033, 3000077, 5000077, 10000019
};
static int adjustSize(int size) {
for (int i = 0; i < prim.length - 1; i++) {
if (size < prim[i]) {
return prim[i] + RESERVE;
}
}
return size + RESERVE;
}
private static final int GROFAC = 2;
private int mask;
public Object[] mKeys;
private int klen;
private int mValues[];
private int mNumberOfElements;
private FSTIdentity2IdMap next;
private List linearScanList; // in case of too depth nesting, this one is filled and linear search is applied
private List<Integer> linearScanVals; // in case of too depth nesting, this one is filled and linear search is applied
public FSTIdentity2IdMap(int initialSize) {
if (initialSize < 2) {
initialSize = 2;
}
initialSize = adjustSize(initialSize * GROFAC);
mKeys = new Object[initialSize];
mValues = new int[initialSize];
mNumberOfElements = 0;
mask = (Integer.highestOneBit(initialSize) << 1) - 1;
klen = initialSize - 4;
}
public int size() {
if ( linearScanList != null )
return linearScanList.size();
return mNumberOfElements + (next != null ? next.size() : 0);
}
final public int putOrGet(Object key, int value) {
int hash = calcHash(key);
return putOrGetHash(key, value, hash, this, 0);
}
final int putOrGetHash(Object key, int value, int hash, FSTIdentity2IdMap parent, int depth ) {
if ( linearScanList != null ) {
for (int i = 0; i < linearScanList.size(); i++) {
Object o = linearScanList.get(i);
if ( o == key ) {
return linearScanVals.get(i);
}
}
linearScanList.add(key);
linearScanVals.add(value);
return Integer.MIN_VALUE;
}
if (mNumberOfElements * GROFAC > mKeys.length) {
if (parent != null) {
if ((parent.mNumberOfElements + mNumberOfElements) * GROFAC > parent.mKeys.length) {
parent.resize(parent.mKeys.length * GROFAC);
return parent.putOrGet(key, value);
} else {
resize(mKeys.length * GROFAC);
}
} else {
resize(mKeys.length * GROFAC);
}
}
Object[] mKeys = this.mKeys;
// int idx = calcIndexFromHash(hash, mKeys);
int idx = calcIndexFromHash(hash, mKeys);
Object mKeyAtIdx = mKeys[idx];
if (mKeyAtIdx == null) // new
{
mNumberOfElements++;
mValues[idx] = value;
mKeys[idx] = key;
return Integer.MIN_VALUE;
} else if (mKeyAtIdx == key) // present
{
return mValues[idx];
} else {
Object mKeyAtIdxPlus1 = mKeys[idx + 1];
if (mKeyAtIdxPlus1 == null) // new
{
mNumberOfElements++;
mValues[idx + 1] = value;
mKeys[idx + 1] = key;
return Integer.MIN_VALUE;
} else if (mKeyAtIdxPlus1 == key) // present
{
return mValues[idx + 1];
} else {
Object mKeysAtIndexPlus2 = mKeys[idx + 2];
if (mKeysAtIndexPlus2 == null) // new
{
mNumberOfElements++;
mValues[idx + 2] = value;
mKeys[idx + 2] = key;
return Integer.MIN_VALUE;
} else if (mKeysAtIndexPlus2 == key) // present
{
return mValues[idx + 2];
} else {
return putOrGetNext(hash, key, value, depth+1);
}
}
}
}
final int putOrGetNext(final int hash, final Object key, final int value, int depth) {
if (next == null) { // new
int newSiz = mKeys.length / 10;
next = new FSTIdentity2IdMap(newSiz);
if ( depth > MAX_DEPTH ) {
next.linearScanVals = new ArrayList<>(3);
next.linearScanList = new ArrayList<>(3);
}
next.putHash(key, value, hash, this, depth);
return Integer.MIN_VALUE;
}
return next.putOrGetHash(key, value, hash, this, depth+1);
}
final public void put(Object key, int value) {
int hash = calcHash(key);
putHash(key, value, hash, this, 0);
}
final void putHash(Object key, int value, int hash, FSTIdentity2IdMap parent, int depth) {
if ( linearScanList != null ) {
for (int i = 0; i < linearScanList.size(); i++) {
Object o = linearScanList.get(i);
if ( o == key ) {
linearScanVals.set(i, value);
return;
}
}
linearScanList.add(key);
linearScanVals.add(value);
return;
}
if (mNumberOfElements * GROFAC > mKeys.length) {
if (parent != null) {
if ((parent.mNumberOfElements + mNumberOfElements) * GROFAC > parent.mKeys.length) {
parent.resize(parent.mKeys.length * GROFAC);
parent.put(key, value);
return;
} else {
resize(mKeys.length * GROFAC);
}
} else {
resize(mKeys.length * GROFAC);
}
}
Object[] mKeys = this.mKeys;
int idx = calcIndexFromHash(hash, mKeys);
if (mKeys[idx] == null) // new
{
mNumberOfElements++;
mValues[idx] = value;
mKeys[idx] = key;
} else if (mKeys[idx] == key) // overwrite
{
// bloom|=hash;
mValues[idx] = value;
} else {
if (mKeys[idx + 1] == null) // new
{
mNumberOfElements++;
mValues[idx + 1] = value;
mKeys[idx + 1] = key;
} else if (mKeys[idx + 1] == key) // overwrite
{
// bloom|=hash;
mValues[idx + 1] = value;
} else {
if (mKeys[idx + 2] == null) // new
{
mNumberOfElements++;
mValues[idx + 2] = value;
mKeys[idx + 2] = key;
} else if (mKeys[idx + 2] == key) // overwrite
{
// bloom|=hash;
mValues[idx + 2] = value;
} else {
putNext(hash, key, value, depth+1);
}
}
}
}
final void putNext(final int hash, final Object key, final int value, int depth) {
if (next == null) {
int newSiz = mKeys.length / 10;
next = new FSTIdentity2IdMap(newSiz);
if ( depth > MAX_DEPTH ) {
next.linearScanVals = new ArrayList<>(3);
next.linearScanList = new ArrayList<>(3);
}
}
next.putHash(key, value, hash, this, depth+1);
}
final public int get(final Object key) {
int hash = calcHash(key);
return getHash(key, hash);
}
final int getHash(final Object key, final int hash) {
if ( linearScanList != null ) {
for (int i = 0; i < linearScanList.size(); i++) {
Object o = linearScanList.get(i);
if ( o == key ) {
return linearScanVals.get(i);
}
}
return Integer.MIN_VALUE;
}
final int idx = calcIndexFromHash(hash, mKeys);
Object mapsKey = mKeys[idx];
if (mapsKey == null) // not found
{
return Integer.MIN_VALUE;
} else if (mapsKey == key) // found
{
return mValues[idx];
} else {
mapsKey = mKeys[idx + 1];
if (mapsKey == null) // not found
{
return Integer.MIN_VALUE;
} else if (mapsKey == key) // found
{
return mValues[idx + 1];
} else {
mapsKey = mKeys[idx + 2];
if (mapsKey == null) // not found
{
return Integer.MIN_VALUE;
} else if (mapsKey == key) // found
{
return mValues[idx + 2];
} else {
if (next == null) {
return Integer.MIN_VALUE;
}
return next.getHash(key, hash);
}
}
}
}
final void resize(int newSize) {
newSize = adjustSize(newSize);
Object[] oldTabKey = mKeys;
int[] oldTabVal = mValues;
mKeys = new Object[newSize];
mValues = new int[newSize];
mNumberOfElements = 0;
mask = (Integer.highestOneBit(newSize) << 1) - 1;
klen = newSize - RESERVE;
for (int n = 0; n < oldTabKey.length; n++) {
if (oldTabKey[n] != null) {
put(oldTabKey[n], oldTabVal[n]);
}
}
if (next != null) {
FSTIdentity2IdMap oldNext = next;
next = null;
oldNext.rePut(this);
}
}
private void rePut(FSTIdentity2IdMap kfstObject2IntMap) {
for (int i = 0; i < mKeys.length; i++) {
Object mKey = mKeys[i];
if (mKey != null) {
kfstObject2IntMap.put(mKey, mValues[i]);
}
}
if (next != null) {
next.rePut(kfstObject2IntMap);
}
}
final int calcIndexFromHash(int hash, Object[] mKeys) {
int res = hash & mask;
while (res >= klen) {
res = res >>> 1;
}
return res;
}
private static int calcHash(Object x) {
int h = System.identityHashCode(x);
// return h>>2;
return ((h << 1) - (h << 8));
}
public void clear() {
if (size() == 0) {
return;
}
if ( linearScanList != null ) {
linearScanList.clear();
linearScanVals.clear();
}
FSTUtil.clear(mKeys);
FSTUtil.clear(mValues);
// Arrays.fill(mKeys,null);
// Arrays.fill(mValues,0);
mNumberOfElements = 0;
if (next != null) {
next.clear();
}
}
public void dump() {
for (int i = 0; i < mKeys.length; i++) {
Object mKey = mKeys[i];
if (mKey != null) {
System.out.println("" + mKey + " => " + mValues[i]);
}
}
if (next != null)
next.dump();
}
}
| src/main/java/org/nustaq/serialization/util/FSTIdentity2IdMap.java | /*
* Copyright (c) 2012, Ruediger Moeller. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*
*/
package org.nustaq.serialization.util;
/**
* Created with IntelliJ IDEA.
* User: ruedi
* Date: 20.11.12
* Time: 19:57
* To change this template use File | Settings | File Templates.
*/
public class FSTIdentity2IdMap {
private static final int RESERVE = 4;
static int[] prim = {
3, 5, 7, 11, 13, 17, 19, 23, 29, 37, 67, 97, 139,
211, 331, 641, 1097, 1531, 2207, 3121, 5059, 7607, 10891,
15901, 19993, 30223, 50077, 74231, 99991, 150001, 300017,
1000033, 1500041, 200033, 3000077, 5000077, 10000019
};
static int adjustSize(int size) {
for (int i = 0; i < prim.length - 1; i++) {
if (size < prim[i]) {
return prim[i] + RESERVE;
}
}
return size + RESERVE;
}
private static final int GROFAC = 2;
private int mask;
public Object[] mKeys;
private int klen;
private int mValues[];
private int mNumberOfElements;
private FSTIdentity2IdMap next;
public FSTIdentity2IdMap(int initialSize) {
if (initialSize < 2) {
initialSize = 2;
}
initialSize = adjustSize(initialSize * GROFAC);
mKeys = new Object[initialSize];
mValues = new int[initialSize];
mNumberOfElements = 0;
mask = (Integer.highestOneBit(initialSize) << 1) - 1;
klen = initialSize - 4;
}
public int size() {
return mNumberOfElements + (next != null ? next.size() : 0);
}
final public int putOrGet(Object key, int value) {
int hash = calcHash(key);
return putOrGetHash(key, value, hash, this);
}
final int putOrGetHash(Object key, int value, int hash, FSTIdentity2IdMap parent) {
if (mNumberOfElements * GROFAC > mKeys.length) {
if (parent != null) {
if ((parent.mNumberOfElements + mNumberOfElements) * GROFAC > parent.mKeys.length) {
parent.resize(parent.mKeys.length * GROFAC);
return parent.putOrGet(key, value);
} else {
resize(mKeys.length * GROFAC);
}
} else {
resize(mKeys.length * GROFAC);
}
}
Object[] mKeys = this.mKeys;
// int idx = calcIndexFromHash(hash, mKeys);
int idx = calcIndexFromHash(hash, mKeys);
Object mKeyAtIdx = mKeys[idx];
if (mKeyAtIdx == null) // new
{
mNumberOfElements++;
mValues[idx] = value;
mKeys[idx] = key;
return Integer.MIN_VALUE;
} else if (mKeyAtIdx == key) // present
{
return mValues[idx];
} else {
Object mKeyAtIdxPlus1 = mKeys[idx + 1];
if (mKeyAtIdxPlus1 == null) // new
{
mNumberOfElements++;
mValues[idx + 1] = value;
mKeys[idx + 1] = key;
return Integer.MIN_VALUE;
} else if (mKeyAtIdxPlus1 == key) // present
{
return mValues[idx + 1];
} else {
Object mKeysAtIndexPlus2 = mKeys[idx + 2];
if (mKeysAtIndexPlus2 == null) // new
{
mNumberOfElements++;
mValues[idx + 2] = value;
mKeys[idx + 2] = key;
return Integer.MIN_VALUE;
} else if (mKeysAtIndexPlus2 == key) // present
{
return mValues[idx + 2];
} else {
return putOrGetNext(hash, key, value);
}
}
}
}
final int putOrGetNext(final int hash, final Object key, final int value) {
if (next == null) { // new
int newSiz = mKeys.length / 10;
next = new FSTIdentity2IdMap(newSiz);
next.putHash(key, value, hash, this);
return Integer.MIN_VALUE;
}
return next.putOrGetHash(key, value, hash, this);
}
final public void put(Object key, int value) {
int hash = calcHash(key);
putHash(key, value, hash, this);
}
final void putHash(Object key, int value, int hash, FSTIdentity2IdMap parent) {
if (mNumberOfElements * GROFAC > mKeys.length) {
if (parent != null) {
if ((parent.mNumberOfElements + mNumberOfElements) * GROFAC > parent.mKeys.length) {
parent.resize(parent.mKeys.length * GROFAC);
parent.put(key, value);
return;
} else {
resize(mKeys.length * GROFAC);
}
} else {
resize(mKeys.length * GROFAC);
}
}
Object[] mKeys = this.mKeys;
int idx = calcIndexFromHash(hash, mKeys);
if (mKeys[idx] == null) // new
{
mNumberOfElements++;
mValues[idx] = value;
mKeys[idx] = key;
} else if (mKeys[idx] == key) // overwrite
{
// bloom|=hash;
mValues[idx] = value;
} else {
if (mKeys[idx + 1] == null) // new
{
mNumberOfElements++;
mValues[idx + 1] = value;
mKeys[idx + 1] = key;
} else if (mKeys[idx + 1] == key) // overwrite
{
// bloom|=hash;
mValues[idx + 1] = value;
} else {
if (mKeys[idx + 2] == null) // new
{
mNumberOfElements++;
mValues[idx + 2] = value;
mKeys[idx + 2] = key;
} else if (mKeys[idx + 2] == key) // overwrite
{
// bloom|=hash;
mValues[idx + 2] = value;
} else {
putNext(hash, key, value);
}
}
}
}
final void putNext(final int hash, final Object key, final int value) {
if (next == null) {
int newSiz = mKeys.length / 10;
next = new FSTIdentity2IdMap(newSiz);
}
next.putHash(key, value, hash, this);
}
final public int get(final Object key) {
int hash = calcHash(key);
return getHash(key, hash);
}
final int getHash(final Object key, final int hash) {
final int idx = calcIndexFromHash(hash, mKeys);
Object mapsKey = mKeys[idx];
if (mapsKey == null) // not found
{
return Integer.MIN_VALUE;
} else if (mapsKey == key) // found
{
return mValues[idx];
} else {
mapsKey = mKeys[idx + 1];
if (mapsKey == null) // not found
{
return Integer.MIN_VALUE;
} else if (mapsKey == key) // found
{
return mValues[idx + 1];
} else {
mapsKey = mKeys[idx + 2];
if (mapsKey == null) // not found
{
return Integer.MIN_VALUE;
} else if (mapsKey == key) // found
{
return mValues[idx + 2];
} else {
if (next == null) {
return Integer.MIN_VALUE;
}
return next.getHash(key, hash);
}
}
}
}
final void resize(int newSize) {
newSize = adjustSize(newSize);
Object[] oldTabKey = mKeys;
int[] oldTabVal = mValues;
mKeys = new Object[newSize];
mValues = new int[newSize];
mNumberOfElements = 0;
mask = (Integer.highestOneBit(newSize) << 1) - 1;
klen = newSize - RESERVE;
for (int n = 0; n < oldTabKey.length; n++) {
if (oldTabKey[n] != null) {
put(oldTabKey[n], oldTabVal[n]);
}
}
if (next != null) {
FSTIdentity2IdMap oldNext = next;
next = null;
oldNext.rePut(this);
}
}
private void rePut(FSTIdentity2IdMap kfstObject2IntMap) {
for (int i = 0; i < mKeys.length; i++) {
Object mKey = mKeys[i];
if (mKey != null) {
kfstObject2IntMap.put(mKey, mValues[i]);
}
}
if (next != null) {
next.rePut(kfstObject2IntMap);
}
}
final int calcIndexFromHash(int hash, Object[] mKeys) {
int res = hash & mask;
while (res >= klen) {
res = res >>> 1;
}
return res;
}
private static int calcHash(Object x) {
int h = System.identityHashCode(x);
// return h>>2;
return ((h << 1) - (h << 8));
}
public void clear() {
if (size() == 0) {
return;
}
FSTUtil.clear(mKeys);
FSTUtil.clear(mValues);
// Arrays.fill(mKeys,null);
// Arrays.fill(mValues,0);
mNumberOfElements = 0;
if (next != null) {
next.clear();
}
}
public static void main(String arg[]) {
String strings[] = new String[5000];
for (int i = 0; i < strings.length; i++) {
strings[i] = "" + Math.random();
}
FSTIdentity2IdMap map = new FSTIdentity2IdMap(97);
// warm
for (int j = 0; j < 50000; j++) {
testNewPut(strings, map);
map.clear();
}
long tim = System.currentTimeMillis();
for (int j = 0; j < 50000; j++) {
testNewPut(strings, map);
map.clear();
}
testNewPut(strings, map);
testGet(strings, map);
map.clear();
testPut(strings, map);
testGet(strings, map);
testWrongGet(map);
long now = System.currentTimeMillis();
System.out.println("time new " + (now - tim));
tim = System.currentTimeMillis();
for (int j = 0; j < 50000; j++) {
// testExistPut(strings, map);
testPut(strings, map);
}
now = System.currentTimeMillis();
System.out.println("time exist put " + (now - tim));
tim = System.currentTimeMillis();
for (int j = 0; j < 50000; j++) {
testGet(strings, map);
}
now = System.currentTimeMillis();
System.out.println("time exist " + (now - tim));
}
private static void testExistPut(String[] strings, FSTIdentity2IdMap map) {
for (int i = 0; i < strings.length; i++) {
String string = strings[i];
int fieldId = map.putOrGet(string, i);
// if ( fieldId != i ) {
// throw new RuntimeException("möp 1 "+i+" "+fieldId);
// }
}
}
private static void testPut(String[] strings, FSTIdentity2IdMap map) {
for (int i = 0; i < strings.length; i++) {
String string = strings[i];
map.put(string, i);
}
}
private static void testGet(String[] strings, FSTIdentity2IdMap map) {
for (int i = 0; i < strings.length; i++) {
String string = strings[i];
int fieldId = map.get(string);
if (fieldId != i) {
throw new RuntimeException("möp 2 " + i + " " + fieldId);
}
}
}
private static void testWrongGet(FSTIdentity2IdMap map) {
for (int i = 0; i < 1000; i++) {
int fieldId = map.get("pok" + i);
if (fieldId != Integer.MIN_VALUE) {
throw new RuntimeException("möp 3 " + i + " " + fieldId);
}
}
}
private static void testNewPut(String[] strings, FSTIdentity2IdMap map) {
for (int i = 0; i < strings.length; i++) {
String string = strings[i];
if (map.putOrGet(string, i) > 0) {
throw new RuntimeException("möp");
}
}
}
public void dump() {
for (int i = 0; i < mKeys.length; i++) {
Object mKey = mKeys[i];
if (mKey != null) {
System.out.println("" + mKey + " => " + mValues[i]);
}
}
if (next != null)
next.dump();
}
} | Update FSTIdentity2IdMap.java | src/main/java/org/nustaq/serialization/util/FSTIdentity2IdMap.java | Update FSTIdentity2IdMap.java | <ide><path>rc/main/java/org/nustaq/serialization/util/FSTIdentity2IdMap.java
<ide>
<ide> package org.nustaq.serialization.util;
<ide>
<add>import java.util.ArrayList;
<add>import java.util.List;
<add>
<ide> /**
<ide> * Created with IntelliJ IDEA.
<ide> * User: ruedi
<ide> */
<ide> public class FSTIdentity2IdMap {
<ide> private static final int RESERVE = 4;
<add> private static final int MAX_DEPTH = 4;
<ide> static int[] prim = {
<ide> 3, 5, 7, 11, 13, 17, 19, 23, 29, 37, 67, 97, 139,
<ide> 211, 331, 641, 1097, 1531, 2207, 3121, 5059, 7607, 10891,
<ide> private int mValues[];
<ide> private int mNumberOfElements;
<ide> private FSTIdentity2IdMap next;
<add> private List linearScanList; // in case of too depth nesting, this one is filled and linear search is applied
<add> private List<Integer> linearScanVals; // in case of too depth nesting, this one is filled and linear search is applied
<ide>
<ide> public FSTIdentity2IdMap(int initialSize) {
<ide> if (initialSize < 2) {
<ide> }
<ide>
<ide> public int size() {
<add> if ( linearScanList != null )
<add> return linearScanList.size();
<ide> return mNumberOfElements + (next != null ? next.size() : 0);
<ide> }
<ide>
<ide> final public int putOrGet(Object key, int value) {
<ide> int hash = calcHash(key);
<del> return putOrGetHash(key, value, hash, this);
<del> }
<del>
<del> final int putOrGetHash(Object key, int value, int hash, FSTIdentity2IdMap parent) {
<add> return putOrGetHash(key, value, hash, this, 0);
<add> }
<add>
<add> final int putOrGetHash(Object key, int value, int hash, FSTIdentity2IdMap parent, int depth ) {
<add> if ( linearScanList != null ) {
<add> for (int i = 0; i < linearScanList.size(); i++) {
<add> Object o = linearScanList.get(i);
<add> if ( o == key ) {
<add> return linearScanVals.get(i);
<add> }
<add> }
<add> linearScanList.add(key);
<add> linearScanVals.add(value);
<add> return Integer.MIN_VALUE;
<add> }
<ide> if (mNumberOfElements * GROFAC > mKeys.length) {
<ide> if (parent != null) {
<ide> if ((parent.mNumberOfElements + mNumberOfElements) * GROFAC > parent.mKeys.length) {
<ide> {
<ide> return mValues[idx + 2];
<ide> } else {
<del> return putOrGetNext(hash, key, value);
<del> }
<del> }
<del> }
<del> }
<del>
<del> final int putOrGetNext(final int hash, final Object key, final int value) {
<add> return putOrGetNext(hash, key, value, depth+1);
<add> }
<add> }
<add> }
<add> }
<add>
<add> final int putOrGetNext(final int hash, final Object key, final int value, int depth) {
<ide> if (next == null) { // new
<ide> int newSiz = mKeys.length / 10;
<ide> next = new FSTIdentity2IdMap(newSiz);
<del> next.putHash(key, value, hash, this);
<del> return Integer.MIN_VALUE;
<del> }
<del> return next.putOrGetHash(key, value, hash, this);
<add> if ( depth > MAX_DEPTH ) {
<add> next.linearScanVals = new ArrayList<>(3);
<add> next.linearScanList = new ArrayList<>(3);
<add> }
<add> next.putHash(key, value, hash, this, depth);
<add> return Integer.MIN_VALUE;
<add> }
<add> return next.putOrGetHash(key, value, hash, this, depth+1);
<ide> }
<ide>
<ide> final public void put(Object key, int value) {
<ide> int hash = calcHash(key);
<del> putHash(key, value, hash, this);
<del> }
<del>
<del> final void putHash(Object key, int value, int hash, FSTIdentity2IdMap parent) {
<add> putHash(key, value, hash, this, 0);
<add> }
<add>
<add> final void putHash(Object key, int value, int hash, FSTIdentity2IdMap parent, int depth) {
<add> if ( linearScanList != null ) {
<add> for (int i = 0; i < linearScanList.size(); i++) {
<add> Object o = linearScanList.get(i);
<add> if ( o == key ) {
<add> linearScanVals.set(i, value);
<add> return;
<add> }
<add> }
<add> linearScanList.add(key);
<add> linearScanVals.add(value);
<add> return;
<add> }
<ide> if (mNumberOfElements * GROFAC > mKeys.length) {
<ide> if (parent != null) {
<ide> if ((parent.mNumberOfElements + mNumberOfElements) * GROFAC > parent.mKeys.length) {
<ide> // bloom|=hash;
<ide> mValues[idx + 2] = value;
<ide> } else {
<del> putNext(hash, key, value);
<del> }
<del> }
<del> }
<del> }
<del>
<del> final void putNext(final int hash, final Object key, final int value) {
<add> putNext(hash, key, value, depth+1);
<add> }
<add> }
<add> }
<add> }
<add>
<add> final void putNext(final int hash, final Object key, final int value, int depth) {
<ide> if (next == null) {
<ide> int newSiz = mKeys.length / 10;
<ide> next = new FSTIdentity2IdMap(newSiz);
<del> }
<del> next.putHash(key, value, hash, this);
<add> if ( depth > MAX_DEPTH ) {
<add> next.linearScanVals = new ArrayList<>(3);
<add> next.linearScanList = new ArrayList<>(3);
<add> }
<add> }
<add> next.putHash(key, value, hash, this, depth+1);
<ide> }
<ide>
<ide> final public int get(final Object key) {
<ide> }
<ide>
<ide> final int getHash(final Object key, final int hash) {
<add> if ( linearScanList != null ) {
<add> for (int i = 0; i < linearScanList.size(); i++) {
<add> Object o = linearScanList.get(i);
<add> if ( o == key ) {
<add> return linearScanVals.get(i);
<add> }
<add> }
<add> return Integer.MIN_VALUE;
<add> }
<add>
<ide> final int idx = calcIndexFromHash(hash, mKeys);
<ide>
<ide> Object mapsKey = mKeys[idx];
<ide> public void clear() {
<ide> if (size() == 0) {
<ide> return;
<add> }
<add> if ( linearScanList != null ) {
<add> linearScanList.clear();
<add> linearScanVals.clear();
<ide> }
<ide> FSTUtil.clear(mKeys);
<ide> FSTUtil.clear(mValues);
<ide> }
<ide> }
<ide>
<del> public static void main(String arg[]) {
<del> String strings[] = new String[5000];
<del> for (int i = 0; i < strings.length; i++) {
<del> strings[i] = "" + Math.random();
<del> }
<del>
<del>
<del> FSTIdentity2IdMap map = new FSTIdentity2IdMap(97);
<del>
<del> // warm
<del> for (int j = 0; j < 50000; j++) {
<del> testNewPut(strings, map);
<del> map.clear();
<del> }
<del>
<del> long tim = System.currentTimeMillis();
<del> for (int j = 0; j < 50000; j++) {
<del> testNewPut(strings, map);
<del> map.clear();
<del> }
<del>
<del> testNewPut(strings, map);
<del> testGet(strings, map);
<del> map.clear();
<del> testPut(strings, map);
<del> testGet(strings, map);
<del> testWrongGet(map);
<del> long now = System.currentTimeMillis();
<del> System.out.println("time new " + (now - tim));
<del>
<del> tim = System.currentTimeMillis();
<del> for (int j = 0; j < 50000; j++) {
<del>// testExistPut(strings, map);
<del> testPut(strings, map);
<del> }
<del> now = System.currentTimeMillis();
<del> System.out.println("time exist put " + (now - tim));
<del>
<del> tim = System.currentTimeMillis();
<del> for (int j = 0; j < 50000; j++) {
<del> testGet(strings, map);
<del> }
<del> now = System.currentTimeMillis();
<del> System.out.println("time exist " + (now - tim));
<del>
<del>
<del> }
<del>
<del> private static void testExistPut(String[] strings, FSTIdentity2IdMap map) {
<del> for (int i = 0; i < strings.length; i++) {
<del> String string = strings[i];
<del> int fieldId = map.putOrGet(string, i);
<del>// if ( fieldId != i ) {
<del>// throw new RuntimeException("möp 1 "+i+" "+fieldId);
<del>// }
<del> }
<del> }
<del>
<del> private static void testPut(String[] strings, FSTIdentity2IdMap map) {
<del> for (int i = 0; i < strings.length; i++) {
<del> String string = strings[i];
<del> map.put(string, i);
<del> }
<del> }
<del>
<del> private static void testGet(String[] strings, FSTIdentity2IdMap map) {
<del> for (int i = 0; i < strings.length; i++) {
<del> String string = strings[i];
<del> int fieldId = map.get(string);
<del> if (fieldId != i) {
<del> throw new RuntimeException("möp 2 " + i + " " + fieldId);
<del> }
<del> }
<del> }
<del>
<del> private static void testWrongGet(FSTIdentity2IdMap map) {
<del> for (int i = 0; i < 1000; i++) {
<del> int fieldId = map.get("pok" + i);
<del> if (fieldId != Integer.MIN_VALUE) {
<del> throw new RuntimeException("möp 3 " + i + " " + fieldId);
<del> }
<del> }
<del> }
<del>
<del> private static void testNewPut(String[] strings, FSTIdentity2IdMap map) {
<del> for (int i = 0; i < strings.length; i++) {
<del> String string = strings[i];
<del> if (map.putOrGet(string, i) > 0) {
<del> throw new RuntimeException("möp");
<del> }
<del> }
<del> }
<del>
<ide> public void dump() {
<ide> for (int i = 0; i < mKeys.length; i++) {
<ide> Object mKey = mKeys[i]; |
|
Java | apache-2.0 | e5c4890106d1908fc0f1c54c2115b0b2dca8a239 | 0 | ellitron/ramcloud-gremlin,ellitron/ramcloud-gremlin,jdellithorpe/torc-gremlin,jdellithorpe/torc-gremlin | /*
* Copyright 2015 Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// TODO: Change license to match RAMCloud
package org.ellitron.tinkerpop.gremlin.torc.structure;
import org.apache.tinkerpop.gremlin.process.computer.GraphComputer;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Transaction;
import org.apache.tinkerpop.gremlin.structure.VertexProperty;
import org.apache.tinkerpop.gremlin.structure.util.ElementHelper;
import org.apache.tinkerpop.gremlin.structure.util.StringFactory;
import edu.stanford.ramcloud.*;
import edu.stanford.ramcloud.transactions.*;
import edu.stanford.ramcloud.ClientException.*;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.HashMap;
import org.apache.commons.configuration.Configuration;
import org.apache.log4j.Logger;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.tinkerpop.gremlin.structure.Direction;
import org.apache.tinkerpop.gremlin.structure.Element;
import org.apache.tinkerpop.gremlin.structure.Property;
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.util.AbstractTransaction;
import org.ellitron.tinkerpop.gremlin.torc.structure.util.TorcHelper;
/**
* TODO: Write documentation - Bidirectional edges
*
*
* @author Jonathan Ellithorpe <[email protected]>
*
* TODO: Make TorcGraph thread safe. Currently every TorcGraph method that
* performs reads or writes to the database uses a ThreadLocal
* RAMCloudTransaction to isolate transactions from different threads. Each
* ThreadLocal RAMCloudTransaction object, however, is constructed with a
* reference to the same RAMCloud client object, which itself is not thread
* safe. Therefore, TorcGraph, although using separate RAMCloudTransaction
* objects for each thread, it not actually thread safe. To fix this problem,
* each ThreadLocal RAMCloudTransaction object needs to be constructed with its
* own RAMCloud client object.
*
* TODO: Implement way of handling objects that are larger than 1MB.
*/
@Graph.OptIn(Graph.OptIn.SUITE_STRUCTURE_STANDARD)
public final class TorcGraph implements Graph {
private static final Logger logger = Logger.getLogger(TorcGraph.class);
// Configuration keys.
public static final String CONFIG_GRAPH_NAME = "gremlin.torc.graphName";
public static final String CONFIG_COORD_LOCATOR = "gremlin.torc.coordinatorLocator";
public static final String CONFIG_NUM_MASTER_SERVERS = "gremlin.torc.numMasterServers";
public static final String CONFIG_LOG_LEVEL = "gremlin.torc.logLevel";
// Constants.
private static final String ID_TABLE_NAME = "idTable";
private static final String VERTEX_TABLE_NAME = "vertexTable";
private static final String EDGE_TABLE_NAME = "edgeTable";
private static final int MAX_TX_RETRY_COUNT = 100;
private static final int NUM_ID_COUNTERS = 16;
// Normal private members.
private final Configuration configuration;
private final String coordinatorLocator;
private final int totalMasterServers;
private final ConcurrentHashMap<Thread, RAMCloud> threadLocalClientMap = new ConcurrentHashMap<>();
private long idTableId, vertexTableId, edgeTableId;
private final String graphName;
private final TorcGraphTransaction torcGraphTx = new TorcGraphTransaction();
boolean initialized = false;
private TorcGraph(final Configuration configuration) {
this.configuration = configuration;
graphName = configuration.getString(CONFIG_GRAPH_NAME);
coordinatorLocator = configuration.getString(CONFIG_COORD_LOCATOR);
totalMasterServers = configuration.getInt(CONFIG_NUM_MASTER_SERVERS);
logger.debug(String.format("Constructing TorcGraph (%s,%s,%d)", graphName, coordinatorLocator, totalMasterServers));
}
public boolean isInitialized() {
return initialized;
}
/**
* This method ensures three things are true before it returns to the
* caller:
*
* 1) This thread has an initialized thread-local RAMCloud client (its own
* connection to RAMCloud)
*
* 2) RAMCloud tables have been created for this graph
*
* 3) RAMCloud table IDs have been fetched.
*
*
* This method is intended to be used as a way of deferring costly
* initialization until absolutely needed. This method should be called at
* the top of any public method of TorcGraph that performs operations
* against RAMCloud.
*/
private void initialize() {
if (!threadLocalClientMap.containsKey(Thread.currentThread())) {
threadLocalClientMap.put(Thread.currentThread(), new RAMCloud(coordinatorLocator));
logger.debug(String.format("initialize(): Thread %d made connection to RAMCloud cluster.", Thread.currentThread().getId()));
if (!initialized) {
RAMCloud client = threadLocalClientMap.get(Thread.currentThread());
idTableId = client.createTable(graphName + "_" + ID_TABLE_NAME, totalMasterServers);
vertexTableId = client.createTable(graphName + "_" + VERTEX_TABLE_NAME, totalMasterServers);
edgeTableId = client.createTable(graphName + "_" + EDGE_TABLE_NAME, totalMasterServers);
initialized = true;
logger.debug(String.format("initialize(): Fetched table Ids (%s=%d,%s=%d,%s=%d)", graphName + "_" + ID_TABLE_NAME, idTableId, graphName + "_" + VERTEX_TABLE_NAME, vertexTableId, graphName + "_" + EDGE_TABLE_NAME, edgeTableId));
}
}
}
public static TorcGraph open(final Configuration configuration) {
return new TorcGraph(configuration);
}
@Override
public Vertex addVertex(final Object... keyValues) {
long startTimeNs = 0;
if (logger.isDebugEnabled()) {
startTimeNs = System.nanoTime();
}
initialize();
torcGraphTx.readWrite();
RAMCloudTransaction rctx = torcGraphTx.getThreadLocalRAMCloudTx();
ElementHelper.legalPropertyKeyValueArray(keyValues);
// Only values of type String supported, currently.
for (int i = 0; i < keyValues.length; i = i + 2) {
if (!(keyValues[i] instanceof T) && !(keyValues[i + 1] instanceof String)) {
throw Property.Exceptions.dataTypeOfPropertyValueNotSupported(keyValues[i + 1]);
}
}
Object idValue = ElementHelper.getIdValue(keyValues).orElse(null);
final String label = ElementHelper.getLabelValue(keyValues).orElse(Vertex.DEFAULT_LABEL);
UInt128 vertexId;
if (idValue != null) {
vertexId = UInt128.decode(idValue);
// Check if a vertex with this ID already exists.
try {
rctx.read(vertexTableId, TorcHelper.getVertexLabelKey(vertexId));
throw Graph.Exceptions.vertexWithIdAlreadyExists(vertexId.toString());
} catch (ObjectDoesntExistException e) {
// Good!
}
} else {
long id_counter = (long) (Math.random() * NUM_ID_COUNTERS);
RAMCloud client = threadLocalClientMap.get(Thread.currentThread());
long id = client.incrementInt64(idTableId, Long.toString(id_counter).getBytes(), 1, null);
vertexId = new UInt128((1L << 63) + id_counter, id);
}
// Create property map.
Map<String, String> properties = new HashMap<>();
for (int i = 0; i < keyValues.length; i = i + 2) {
if (keyValues[i] instanceof String) {
properties.put((String) keyValues[i], (String) keyValues[i + 1]);
}
}
rctx.write(vertexTableId, TorcHelper.getVertexLabelKey(vertexId), label.getBytes());
rctx.write(vertexTableId, TorcHelper.getVertexPropertiesKey(vertexId), TorcHelper.serializeProperties(properties).array());
if (logger.isDebugEnabled()) {
long endTimeNs = System.nanoTime();
int propLength = TorcHelper.serializeProperties(properties).array().length;
logger.debug(String.format("addVertex(id=%s,label=%s,propLen=%d), took %dus", vertexId.toString(), label, propLength, (endTimeNs - startTimeNs) / 1000l));
}
return new TorcVertex(this, vertexId, label);
}
@Override
public <C extends GraphComputer> C compute(final Class<C> type) throws IllegalArgumentException {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public GraphComputer compute() throws IllegalArgumentException {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public Iterator<Vertex> vertices(final Object... vertexIds) {
long startTimeNs = 0;
if (logger.isDebugEnabled()) {
startTimeNs = System.nanoTime();
}
initialize();
torcGraphTx.readWrite();
RAMCloudTransaction rctx = torcGraphTx.getThreadLocalRAMCloudTx();
ElementHelper.validateMixedElementIds(TorcVertex.class, vertexIds);
List<Vertex> list = new ArrayList<>();
if (vertexIds.length > 0) {
if (vertexIds[0] instanceof TorcVertex) {
Arrays.asList(vertexIds).forEach((id) -> {
list.add((Vertex) id);
});
} else {
for (int i = 0; i < vertexIds.length; ++i) {
UInt128 vertexId = UInt128.decode(vertexIds[i]);
RAMCloudObject obj;
try {
obj = rctx.read(vertexTableId, TorcHelper.getVertexLabelKey(vertexId));
} catch (ObjectDoesntExistException e) {
throw Graph.Exceptions.elementNotFound(TorcVertex.class, vertexIds[i]);
}
list.add(new TorcVertex(this, vertexId, obj.getValue()));
}
}
} else {
long max_id[] = new long[NUM_ID_COUNTERS];
for (int i = 0; i < NUM_ID_COUNTERS; ++i) {
try {
ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES);
buffer.order(ByteOrder.LITTLE_ENDIAN);
buffer.put(rctx.read(idTableId, Long.toString(i)).getValueBytes());
buffer.flip();
max_id[i] = buffer.getLong();
} catch (ObjectDoesntExistException e) {
max_id[i] = 0;
}
}
for (int i = 0; i < NUM_ID_COUNTERS; ++i) {
for (long j = 1; j <= max_id[i]; ++j) {
UInt128 vertexId = new UInt128((1L << 63) + i, j);
try {
RAMCloudObject obj = rctx.read(vertexTableId, TorcHelper.getVertexLabelKey(vertexId));
list.add(new TorcVertex(this, vertexId, obj.getValue()));
} catch (ObjectDoesntExistException e) {
// Continue...
}
}
}
}
if (logger.isDebugEnabled()) {
long endTimeNs = System.nanoTime();
logger.debug(String.format("vertices(n=%d), took %dus", vertexIds.length, (endTimeNs - startTimeNs) / 1000l));
}
return list.iterator();
}
@Override
public Iterator<Edge> edges(final Object... edgeIds) {
long startTimeNs = 0;
if (logger.isDebugEnabled()) {
startTimeNs = System.nanoTime();
}
initialize();
torcGraphTx.readWrite();
RAMCloudTransaction rctx = torcGraphTx.getThreadLocalRAMCloudTx();
ElementHelper.validateMixedElementIds(TorcEdge.class, edgeIds);
List<Edge> list = new ArrayList<>();
if (edgeIds.length > 0) {
if (edgeIds[0] instanceof TorcEdge) {
list = Arrays.asList((Edge[]) edgeIds);
} else if (edgeIds[0] instanceof TorcEdge.Id) {
for (int i = 0; i < edgeIds.length; ++i) {
list.add(((TorcEdge.Id) edgeIds[i]).getEdge());
}
} else {
throw Graph.Exceptions.elementNotFound(TorcEdge.class, edgeIds[0]);
}
} else {
long max_id[] = new long[NUM_ID_COUNTERS];
for (int i = 0; i < NUM_ID_COUNTERS; ++i) {
try {
ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES);
buffer.order(ByteOrder.LITTLE_ENDIAN);
buffer.put(rctx.read(idTableId, Integer.toString(i)).getValueBytes());
buffer.flip();
max_id[i] = buffer.getLong();
} catch (ObjectDoesntExistException e) {
max_id[i] = 0;
}
}
for (int i = 0; i < NUM_ID_COUNTERS; ++i) {
for (long j = 1; j <= max_id[i]; ++j) {
UInt128 baseVertexId = new UInt128((1L << 63) + i, j);
try {
RAMCloudObject obj = rctx.read(vertexTableId, TorcHelper.getVertexEdgeLabelListKey(baseVertexId));
List<String> edgeLabels = TorcHelper.deserializeEdgeLabelList(obj);
for (String label : edgeLabels) {
try {
obj = rctx.read(vertexTableId, TorcHelper.getVertexEdgeListKey(baseVertexId, label, TorcEdgeDirection.DIRECTED_OUT));
List<UInt128> neighborVertexIds = TorcHelper.parseNeighborIdsFromEdgeList(obj);
for (UInt128 neighborVertexId : neighborVertexIds) {
list.add(new TorcEdge(this, baseVertexId, neighborVertexId, TorcEdge.Type.DIRECTED, label));
}
} catch (ObjectDoesntExistException e) {
/*
* The DIRECTED_OUT edge list for this label
* doesn't exist. Continue...
*/
}
/**
* TODO: Decide whether or not to include the new
* bi-directional edges in this list. Not sure
* whether or not including these RAMCloudGraph
* specific bi-directional edges is considered a
* violation of the API.
*/
try {
obj = rctx.read(vertexTableId, TorcHelper.getVertexEdgeListKey(baseVertexId, label, TorcEdgeDirection.UNDIRECTED));
List<UInt128> neighborVertexIds = TorcHelper.parseNeighborIdsFromEdgeList(obj);
for (UInt128 neighborVertexId : neighborVertexIds) {
/*
* Prevent double counting of undirected
* edges. Only count the edge at the vertex
* with the min ID.
*/
if (baseVertexId.compareTo(neighborVertexId) < 0) {
list.add(new TorcEdge(this, baseVertexId, neighborVertexId, TorcEdge.Type.UNDIRECTED, label));
}
}
} catch (ObjectDoesntExistException e) {
/*
* The UNDIRECTED edge list for this label
* doesn't exist. Continue...
*/
}
}
} catch (ObjectDoesntExistException e) {
/*
* The edge label list object for this vertex doesn't
* exist
*/
}
}
}
}
if (logger.isDebugEnabled()) {
long endTimeNs = System.nanoTime();
logger.debug(String.format("edges(n=%d), took %dus", edgeIds.length, (endTimeNs - startTimeNs) / 1000l));
}
return list.iterator();
}
@Override
public Transaction tx() {
initialize();
return torcGraphTx;
}
@Override
public Variables variables() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public Configuration configuration() {
return configuration;
}
/**
* Closes the thread-local transaction (if it is open), and closes the
* thread-local connection to RAMCloud (if one has been made). This may
* affect the state of the graph in RAMCloud depending on the close behavior
* set for the transaction (e.g. in the case that there is an open
* transaction which is set to automatically commit when closed).
*
* Important: Every thread that performs any operation on this graph
* instance has the responsibility of calling this close method before
* exiting. Otherwise it is possible that state that has been created via
* the RAMCloud JNI library will not be cleaned up properly (for instance,
* although {@link RAMCloud} and {@link RAMCloudTransaction} objects have
* implemented finalize() methods to clean up their mirrored C++ objects, it
* is still possible that the garbage collector will clean up the RAMCloud
* object before the RAMCloudTransaction object that uses it. This *may*
* lead to unexpected behavior).
*/
@Override
public void close() {
long startTimeNs = 0;
if (logger.isDebugEnabled()) {
startTimeNs = System.nanoTime();
}
if (threadLocalClientMap.containsKey(Thread.currentThread())) {
torcGraphTx.close();
RAMCloud client = threadLocalClientMap.get(Thread.currentThread());
client.disconnect();
threadLocalClientMap.remove(Thread.currentThread());
}
if (logger.isDebugEnabled()) {
long endTimeNs = System.nanoTime();
logger.debug(String.format("close(), took %dus", (endTimeNs - startTimeNs) / 1000l));
}
}
/**
* This method closes all open transactions on all threads (using rollback),
* and closes all open client connections to RAMCloud on all threads. Since
* this method uses rollback as the close mechanism for open transactions,
* and RAMCloud transactions keep no server-side state until commit, it is
* safe to execute this method even after the graph has been deleted with
* {@link #deleteAll()}. Its intended use is primarily for unit tests to
* ensure the freeing of all client-side state remaining across JNI (i.e.
* C++ RAMCloud client objects, C++ RAMCloud Transaction objects) before
* finishing the current test and moving on to the next.
*/
public void closeAllThreads() {
long startTimeNs = 0;
if (logger.isDebugEnabled()) {
startTimeNs = System.nanoTime();
}
torcGraphTx.doRollbackAllThreads();
threadLocalClientMap.forEach((thread, client) -> {
try {
client.disconnect();
} catch (Exception e) {
logger.error("closeAllThreads(): could not close transaction of thread " + thread.getId());
}
logger.debug(String.format("closeAllThreads(): closed client connection of %d", thread.getId()));
});
threadLocalClientMap.clear();
if (logger.isDebugEnabled()) {
long endTimeNs = System.nanoTime();
logger.debug(String.format("closeAllThreads(), took %dus", (endTimeNs - startTimeNs) / 1000l));
}
}
/**
* Deletes all graph data for the graph represented by this TorcGraph
* instance in RAMCloud.
*
* This method's intended use is for the reset phase of unit tests (see also
* {@link #closeAllThreads()}). To delete all RAMCloud state representing
* this graph as well as clear up all client-side state, one would execute
* the following in sequence:
*
* graph.deleteGraph();
*
* graph.closeAllThreads();
*/
public void deleteGraph() {
long startTimeNs = 0;
if (logger.isDebugEnabled()) {
startTimeNs = System.nanoTime();
}
initialize();
RAMCloud client = threadLocalClientMap.get(Thread.currentThread());
client.dropTable(graphName + "_" + ID_TABLE_NAME);
client.dropTable(graphName + "_" + VERTEX_TABLE_NAME);
client.dropTable(graphName + "_" + EDGE_TABLE_NAME);
if (logger.isDebugEnabled()) {
long endTimeNs = System.nanoTime();
logger.debug(String.format("deleteGraph(), took %dus", (endTimeNs - startTimeNs) / 1000l));
}
}
@Override
public String toString() {
return StringFactory.graphString(this, "coordLoc:" + this.coordinatorLocator + " graphName:" + this.graphName);
}
@Override
public Features features() {
return new TorcGraphFeatures();
}
/**
* Methods called by TorcVertex.
*/
void removeVertex(final TorcVertex vertex) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
Edge addEdge(final TorcVertex vertex1, final TorcVertex vertex2, final String label, final TorcEdge.Type type, final Object[] keyValues) {
long startTimeNs = 0;
if (logger.isDebugEnabled()) {
startTimeNs = System.nanoTime();
}
torcGraphTx.readWrite();
RAMCloudTransaction rctx = torcGraphTx.getThreadLocalRAMCloudTx();
// Validate that these key/value pairs are all strings
if (keyValues.length % 2 != 0) {
throw Element.Exceptions.providedKeyValuesMustBeAMultipleOfTwo();
}
for (int i = 0; i < keyValues.length; i = i + 2) {
if (keyValues[i] instanceof T) {
if (keyValues[i].equals(T.id)) {
throw Edge.Exceptions.userSuppliedIdsNotSupported();
} else {
throw new UnsupportedOperationException("Not supported yet.");
}
}
if (!(keyValues[i] instanceof String)) {
throw Element.Exceptions.providedKeyValuesMustHaveALegalKeyOnEvenIndices();
}
if (!(keyValues[i + 1] instanceof String)) {
throw Property.Exceptions.dataTypeOfPropertyValueNotSupported(keyValues[i + 1]);
}
}
// Create property map.
Map<String, String> properties = new HashMap<>();
for (int i = 0; i < keyValues.length; i = i + 2) {
properties.put((String) keyValues[i], (String) keyValues[i + 1]);
}
ByteBuffer serializedProperties = TorcHelper.serializeProperties(properties);
int serializedEdgeLength = Long.BYTES * 2 + Short.BYTES + serializedProperties.array().length;
// TODO: Figure out a way to work this logic into a function so it's not
// repeated twice as it is below.
// Update vertex1's edge list
byte[] edgeListKey;
if (type == TorcEdge.Type.UNDIRECTED) {
edgeListKey = TorcHelper.getVertexEdgeListKey(vertex1.id(), label, TorcEdgeDirection.UNDIRECTED);
} else {
edgeListKey = TorcHelper.getVertexEdgeListKey(vertex1.id(), label, TorcEdgeDirection.DIRECTED_OUT);
}
try {
RAMCloudObject edgeListRCObj = rctx.read(vertexTableId, edgeListKey);
ByteBuffer newEdgeList = ByteBuffer.allocate(serializedEdgeLength + edgeListRCObj.getValueBytes().length);
newEdgeList.put(vertex2.id().toByteArray());
newEdgeList.putShort((short) serializedProperties.array().length);
newEdgeList.put(serializedProperties.array());
newEdgeList.put(edgeListRCObj.getValueBytes());
rctx.write(vertexTableId, edgeListKey, newEdgeList.array());
} catch (ObjectDoesntExistException e) {
ByteBuffer newEdgeList = ByteBuffer.allocate(serializedEdgeLength);
newEdgeList.put(vertex2.id().toByteArray());
newEdgeList.putShort((short) serializedProperties.array().length);
newEdgeList.put(serializedProperties.array());
rctx.write(vertexTableId, edgeListKey, newEdgeList.array());
byte[] edgeLabelListKey = TorcHelper.getVertexEdgeLabelListKey(vertex1.id());
try {
RAMCloudObject edgeLabelListRCObj = rctx.read(vertexTableId, edgeLabelListKey);
List<String> edgeLabelList = TorcHelper.deserializeEdgeLabelList(edgeLabelListRCObj);
if (!edgeLabelList.contains(label)) {
edgeLabelList.add(label);
rctx.write(vertexTableId, edgeLabelListKey, TorcHelper.serializeEdgeLabelList(edgeLabelList).array());
}
} catch (ObjectDoesntExistException e2) {
List<String> edgeLabelList = new ArrayList<>();
edgeLabelList.add(label);
rctx.write(vertexTableId, edgeLabelListKey, TorcHelper.serializeEdgeLabelList(edgeLabelList).array());
}
}
// Update vertex2's edge list
if (type == TorcEdge.Type.UNDIRECTED) {
edgeListKey = TorcHelper.getVertexEdgeListKey(vertex2.id(), label, TorcEdgeDirection.UNDIRECTED);
} else {
edgeListKey = TorcHelper.getVertexEdgeListKey(vertex2.id(), label, TorcEdgeDirection.DIRECTED_IN);
}
try {
RAMCloudObject edgeListRCObj = rctx.read(vertexTableId, edgeListKey);
ByteBuffer newEdgeList = ByteBuffer.allocate(serializedEdgeLength + edgeListRCObj.getValueBytes().length);
newEdgeList.put(vertex1.id().toByteArray());
newEdgeList.putShort((short) serializedProperties.array().length);
newEdgeList.put(serializedProperties.array());
newEdgeList.put(edgeListRCObj.getValueBytes());
rctx.write(vertexTableId, edgeListKey, newEdgeList.array());
} catch (ObjectDoesntExistException e) {
ByteBuffer newEdgeList = ByteBuffer.allocate(serializedEdgeLength);
newEdgeList.put(vertex1.id().toByteArray());
newEdgeList.putShort((short) serializedProperties.array().length);
newEdgeList.put(serializedProperties.array());
rctx.write(vertexTableId, edgeListKey, newEdgeList.array());
byte[] edgeLabelListKey = TorcHelper.getVertexEdgeLabelListKey(vertex2.id());
try {
RAMCloudObject edgeLabelListRCObj = rctx.read(vertexTableId, edgeLabelListKey);
List<String> edgeLabelList = TorcHelper.deserializeEdgeLabelList(edgeLabelListRCObj);
if (!edgeLabelList.contains(label)) {
edgeLabelList.add(label);
rctx.write(vertexTableId, edgeLabelListKey, TorcHelper.serializeEdgeLabelList(edgeLabelList).array());
}
} catch (ObjectDoesntExistException e2) {
List<String> edgeLabelList = new ArrayList<>();
edgeLabelList.add(label);
rctx.write(vertexTableId, edgeLabelListKey, TorcHelper.serializeEdgeLabelList(edgeLabelList).array());
}
}
if (logger.isDebugEnabled()) {
long endTimeNs = System.nanoTime();
int propLength = TorcHelper.serializeProperties(properties).array().length;
logger.debug(String.format("addEdge(from=%s,to=%s,label=%s,propLen=%d), took %dus", vertex1.id().toString(), vertex2.id().toString(), label, propLength, (endTimeNs - startTimeNs) / 1000l));
}
return new TorcEdge(this, vertex1.id(), vertex2.id(), type, label);
}
Iterator<Edge> vertexEdges(final TorcVertex vertex, final EnumSet<TorcEdgeDirection> edgeDirections, final String[] edgeLabels) {
long startTimeNs = 0;
if (logger.isDebugEnabled()) {
startTimeNs = System.nanoTime();
}
torcGraphTx.readWrite();
RAMCloudTransaction rctx = torcGraphTx.getThreadLocalRAMCloudTx();
List<Edge> edges = new ArrayList<>();
List<String> labels = Arrays.asList(edgeLabels);
if (labels.isEmpty()) {
try {
RAMCloudObject vertEdgeLabelListRCObj = rctx.read(vertexTableId, TorcHelper.getVertexEdgeLabelListKey(vertex.id()));
labels = TorcHelper.deserializeEdgeLabelList(vertEdgeLabelListRCObj);
} catch (ObjectDoesntExistException e) {
}
}
for (String label : labels) {
for (TorcEdgeDirection dir : edgeDirections) {
try {
byte[] edgeListKey = TorcHelper.getVertexEdgeListKey(vertex.id(), label, dir);
RAMCloudObject edgeListRCObj = rctx.read(vertexTableId, edgeListKey);
List<UInt128> neighborVertexIds = TorcHelper.parseNeighborIdsFromEdgeList(edgeListRCObj);
for (UInt128 neighborVertexId : neighborVertexIds) {
switch (dir) {
case DIRECTED_OUT:
edges.add(new TorcEdge(this, vertex.id(), neighborVertexId, TorcEdge.Type.DIRECTED, label));
break;
case DIRECTED_IN:
edges.add(new TorcEdge(this, neighborVertexId, vertex.id(), TorcEdge.Type.DIRECTED, label));
break;
case UNDIRECTED:
edges.add(new TorcEdge(this, vertex.id(), neighborVertexId, TorcEdge.Type.UNDIRECTED, label));
break;
}
}
} catch (ObjectDoesntExistException e) {
/*
* The list of edges for this direction and label does not
* exist. Continue...
*/
}
}
}
if (logger.isDebugEnabled()) {
long endTimeNs = System.nanoTime();
logger.debug(String.format("vertexEdges(vertex=%s,directions=%s,labels=%s), took %dus", vertex.id().toString(), edgeDirections.toString(), labels.toString(), (endTimeNs - startTimeNs) / 1000l));
}
return edges.iterator();
}
Iterator<Vertex> vertexNeighbors(final TorcVertex vertex, final EnumSet<TorcEdgeDirection> edgeDirections, final String[] edgeLabels) {
long startTimeNs = 0;
if (logger.isDebugEnabled()) {
startTimeNs = System.nanoTime();
}
torcGraphTx.readWrite();
RAMCloudTransaction rctx = torcGraphTx.getThreadLocalRAMCloudTx();
List<Vertex> vertices = new ArrayList<>();
List<String> labels = Arrays.asList(edgeLabels);
if (labels.isEmpty()) {
try {
RAMCloudObject vertEdgeLabelListRCObj = rctx.read(vertexTableId, TorcHelper.getVertexEdgeLabelListKey(vertex.id()));
labels = TorcHelper.deserializeEdgeLabelList(vertEdgeLabelListRCObj);
} catch (ObjectDoesntExistException e) {
}
}
for (String label : labels) {
for (TorcEdgeDirection dir : edgeDirections) {
try {
byte[] edgeListKey = TorcHelper.getVertexEdgeListKey(vertex.id(), label, dir);
RAMCloudObject edgeListRCObj = rctx.read(vertexTableId, edgeListKey);
List<UInt128> neighborIds = TorcHelper.parseNeighborIdsFromEdgeList(edgeListRCObj);
for (UInt128 neighborId : neighborIds) {
RAMCloudObject neighborLabelRCObj = rctx.read(vertexTableId, TorcHelper.getVertexLabelKey(neighborId));
vertices.add(new TorcVertex(this, neighborId, neighborLabelRCObj.getValue()));
}
} catch (ObjectDoesntExistException e) {
/*
* The list of edges for this direction and label does not
* exist. Continue...
*/
}
}
}
if (logger.isDebugEnabled()) {
long endTimeNs = System.nanoTime();
logger.debug(String.format("vertexNeighbors(vertex=%s,directions=%s,labels=%s), took %dus", vertex.id().toString(), edgeDirections.toString(), labels.toString(), (endTimeNs - startTimeNs) / 1000l));
}
return vertices.iterator();
}
<V> Iterator<VertexProperty<V>> getVertexProperties(final TorcVertex vertex, final String[] propertyKeys) {
long startTimeNs = 0;
if (logger.isDebugEnabled()) {
startTimeNs = System.nanoTime();
}
torcGraphTx.readWrite();
RAMCloudTransaction rctx = torcGraphTx.getThreadLocalRAMCloudTx();
RAMCloudObject obj = rctx.read(vertexTableId, TorcHelper.getVertexPropertiesKey(vertex.id()));
Map<String, String> properties = TorcHelper.deserializeProperties(obj);
List<VertexProperty<V>> propList = new ArrayList<>();
if (propertyKeys.length > 0) {
for (String key : propertyKeys) {
if (properties.containsKey(key)) {
propList.add(new TorcVertexProperty(vertex, key, properties.get(key)));
} else {
throw Property.Exceptions.propertyDoesNotExist(vertex, key);
}
}
} else {
for (Map.Entry<String, String> property : properties.entrySet()) {
// TODO: Here I am implicitly assuming that V is of type String,
// since property.getValue() returns a string, making the new
// elemennt to propList TorcVertexProperty<String>
propList.add(new TorcVertexProperty(vertex, property.getKey(), property.getValue()));
}
}
if (logger.isDebugEnabled()) {
long endTimeNs = System.nanoTime();
logger.debug(String.format("getVertexProperties(vertex=%s,propKeys=%s), took %dus", vertex.id().toString(), Arrays.asList(propertyKeys).toString(), (endTimeNs - startTimeNs) / 1000l));
}
return propList.iterator();
}
<V> VertexProperty<V> setVertexProperty(final TorcVertex vertex, final VertexProperty.Cardinality cardinality, final String key, final V value, final Object[] keyValues) {
long startTimeNs = 0;
if (logger.isDebugEnabled()) {
startTimeNs = System.nanoTime();
}
torcGraphTx.readWrite();
RAMCloudTransaction rctx = torcGraphTx.getThreadLocalRAMCloudTx();
if (keyValues != null) {
throw VertexProperty.Exceptions.metaPropertiesNotSupported();
}
if (!(value instanceof String)) {
throw Property.Exceptions.dataTypeOfPropertyValueNotSupported(value);
}
RAMCloudObject obj = rctx.read(vertexTableId, TorcHelper.getVertexPropertiesKey(vertex.id()));
Map<String, String> properties = TorcHelper.deserializeProperties(obj);
if (properties.containsKey(key)) {
if (cardinality == VertexProperty.Cardinality.single) {
properties.put(key, (String) value);
} else if (cardinality == VertexProperty.Cardinality.list) {
throw VertexProperty.Exceptions.multiPropertiesNotSupported();
} else if (cardinality == VertexProperty.Cardinality.set) {
throw VertexProperty.Exceptions.multiPropertiesNotSupported();
} else {
throw new UnsupportedOperationException("Do not recognize Cardinality of this type: " + cardinality.toString());
}
} else {
properties.put(key, (String) value);
}
rctx.write(vertexTableId, TorcHelper.getVertexPropertiesKey(vertex.id()), TorcHelper.serializeProperties(properties).array());
if (logger.isDebugEnabled()) {
long endTimeNs = System.nanoTime();
logger.debug(String.format("setVertexProperty(vertex=%s,card=%s,key=%s,value=%s), took %dus", vertex.id().toString(), cardinality.toString(), key, value, (endTimeNs - startTimeNs) / 1000l));
}
return new TorcVertexProperty(vertex, key, value);
}
/**
* Methods called by TorcEdge.
*/
void removeEdge(final TorcEdge edge) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
Iterator<Vertex> edgeVertices(final TorcEdge edge, final Direction direction) {
long startTimeNs = 0;
if (logger.isDebugEnabled()) {
startTimeNs = System.nanoTime();
}
if (edge.getType() == TorcEdge.Type.UNDIRECTED
&& direction != Direction.BOTH) {
throw new RuntimeException(String.format("Tried get source/destination vertex of an undirected edge: [edge:%s, direction:%s]", edge.toString(), direction.toString()));
}
torcGraphTx.readWrite();
RAMCloudTransaction rctx = torcGraphTx.getThreadLocalRAMCloudTx();
List<Vertex> list = new ArrayList<>();
if (direction.equals(Direction.OUT) || direction.equals(Direction.BOTH)) {
RAMCloudObject obj = rctx.read(vertexTableId, TorcHelper.getVertexLabelKey(edge.getV1Id()));
list.add(new TorcVertex(this, edge.getV1Id(), obj.getValue()));
}
if (direction.equals(Direction.IN) || direction.equals(Direction.BOTH)) {
RAMCloudObject obj = rctx.read(vertexTableId, TorcHelper.getVertexLabelKey(edge.getV2Id()));
list.add(new TorcVertex(this, edge.getV2Id(), obj.getValue()));
}
if (logger.isDebugEnabled()) {
long endTimeNs = System.nanoTime();
// TODO: Update this when we have TorcEdgeId class to stringify
logger.debug(String.format("edgeVertices(edgeIdGoesHere,dir=%s), took %dus", direction.toString(), (endTimeNs - startTimeNs) / 1000l));
}
return list.iterator();
}
<V> Iterator<Property<V>> getEdgeProperties(final TorcEdge edge, final String[] propertyKeys) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
<V> Property<V> setEdgeProperty(final TorcEdge edge, final String key, final V value) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public boolean equals(Object that) {
if (!(that instanceof TorcGraph)) {
return false;
}
TorcGraph thatGraph = (TorcGraph) that;
return this.coordinatorLocator.equals(thatGraph.coordinatorLocator)
&& this.graphName.equals(thatGraph.graphName);
}
@Override
public int hashCode() {
int hash = 7;
hash = 29 * hash + Objects.hashCode(this.coordinatorLocator);
hash = 29 * hash + Objects.hashCode(this.graphName);
return hash;
}
// TODO: Move this into its own file.
public static class Exceptions {
public static IllegalArgumentException userSuppliedIdNotValid(String message) {
throw new IllegalArgumentException("Invalid vertex ID: " + message);
}
}
class TorcGraphTransaction extends AbstractTransaction {
private final ConcurrentHashMap<Thread, RAMCloudTransaction> threadLocalRCTXMap = new ConcurrentHashMap<>();
public TorcGraphTransaction() {
super(TorcGraph.this);
}
/**
* This method returns the underlying RAMCloudTransaction object for
* this thread that contains all of the transaction state.
*
* @return RAMCloudTransaction for current thread.
*/
protected RAMCloudTransaction getThreadLocalRAMCloudTx() {
return threadLocalRCTXMap.get(Thread.currentThread());
}
/**
* This method rolls back the transactions of all threads that have not
* closed their transactions themselves. It is meant to be used as a
* final cleanup method to free all transaction state before exiting, in
* the case that threads had executed without performing final cleanup
* themselves before exiting. This currently happens in TinkerPop unit
* tests (3.1.0-incubating). See
* {@link org.apache.tinkerpop.gremlin.structure.TransactionTest#shouldExecuteCompetingThreadsOnMultipleDbInstances}.
* This method is *not* meant to be called while other threads and still
* executing.
*/
private void doRollbackAllThreads() {
threadLocalRCTXMap.forEach((thread, rctx) -> {
try {
rctx.close();
} catch (Exception e) {
logger.error("TorcGraphTransaction.doRollbackAllThreads(): could not close transaction of thread " + thread.getId());
}
logger.debug(String.format("TorcGraphTransaction.doRollbackAllThreads(): rolling back oustanding transaction of thread %d", thread.getId()));
});
threadLocalRCTXMap.clear();
}
@Override
public void doOpen() {
Thread us = Thread.currentThread();
if (threadLocalRCTXMap.get(us) == null) {
RAMCloud client = threadLocalClientMap.get(us);
threadLocalRCTXMap.put(us, new RAMCloudTransaction(client));
} else {
throw Transaction.Exceptions.transactionAlreadyOpen();
}
logger.debug(String.format("TorcGraphTransaction.doOpen(thread=%d)", us.getId()));
}
@Override
public void doCommit() throws AbstractTransaction.TransactionException {
long startTimeNs = 0;
if (logger.isDebugEnabled()) {
startTimeNs = System.nanoTime();
}
RAMCloudTransaction rctx = threadLocalRCTXMap.get(Thread.currentThread());
try {
if (!rctx.commitAndSync()) {
throw new AbstractTransaction.TransactionException("RAMCloud commitAndSync failed.");
}
} catch (ClientException ex) {
throw new AbstractTransaction.TransactionException(ex);
} finally {
rctx.close();
threadLocalRCTXMap.remove(Thread.currentThread());
}
if (logger.isDebugEnabled()) {
long endTimeNs = System.nanoTime();
logger.debug(String.format("TorcGraphTransaction.doCommit(thread=%d), took %dus", Thread.currentThread().getId(), (endTimeNs - startTimeNs) / 1000l));
}
}
@Override
public void doRollback() throws AbstractTransaction.TransactionException {
long startTimeNs = 0;
if (logger.isDebugEnabled()) {
startTimeNs = System.nanoTime();
}
RAMCloudTransaction rctx = threadLocalRCTXMap.get(Thread.currentThread());
try {
rctx.close();
} catch (Exception e) {
throw new AbstractTransaction.TransactionException(e);
} finally {
threadLocalRCTXMap.remove(Thread.currentThread());
}
if (logger.isDebugEnabled()) {
long endTimeNs = System.nanoTime();
logger.debug(String.format("TorcGraphTransaction.doRollback(thread=%d), took %dus", Thread.currentThread().getId(), (endTimeNs - startTimeNs) / 1000l));
}
}
@Override
public boolean isOpen() {
boolean isOpen = (threadLocalRCTXMap.get(Thread.currentThread()) != null);
logger.debug(String.format("TorcGraphTransaction.isOpen(thread=%d): returning %s", Thread.currentThread().getId(), isOpen));
return isOpen;
}
}
// TODO: Move this to its own file.
public class TorcGraphFeatures implements Features {
private TorcGraphFeatures() {
}
@Override
public Features.GraphFeatures graph() {
return new TorcGraphGraphFeatures();
}
@Override
public Features.VertexFeatures vertex() {
return new TorcGraphVertexFeatures();
}
@Override
public Features.EdgeFeatures edge() {
return new TorcGraphEdgeFeatures();
}
@Override
public String toString() {
return StringFactory.featureString(this);
}
}
public class TorcGraphGraphFeatures implements Features.GraphFeatures {
private TorcGraphGraphFeatures() {
}
@Override
public boolean supportsComputer() {
return false;
}
@Override
public boolean supportsPersistence() {
return true;
}
@Override
public boolean supportsConcurrentAccess() {
return false;
}
@Override
public boolean supportsTransactions() {
return true;
}
@Override
public boolean supportsThreadedTransactions() {
return false;
}
@Override
public Features.VariableFeatures variables() {
return new TorcGraphVariableFeatures() {
};
}
}
public class TorcGraphVertexFeatures implements Features.VertexFeatures {
private TorcGraphVertexFeatures() {
}
@Override
public VertexProperty.Cardinality getCardinality(final String key) {
return VertexProperty.Cardinality.single;
}
@Override
public boolean supportsAddVertices() {
return true;
}
@Override
public boolean supportsRemoveVertices() {
return false;
}
@Override
public boolean supportsMultiProperties() {
return false;
}
@Override
public boolean supportsMetaProperties() {
return false;
}
@Override
public Features.VertexPropertyFeatures properties() {
return new TorcGraphVertexPropertyFeatures();
}
@Override
public boolean supportsAddProperty() {
return true;
}
@Override
public boolean supportsRemoveProperty() {
return true;
}
@Override
public boolean supportsUserSuppliedIds() {
return false;
}
@Override
public boolean supportsNumericIds() {
return false;
}
@Override
public boolean supportsStringIds() {
return false;
}
@Override
public boolean supportsUuidIds() {
return false;
}
@Override
public boolean supportsCustomIds() {
return false;
}
@Override
public boolean supportsAnyIds() {
return false;
}
}
public class TorcGraphEdgeFeatures implements Features.EdgeFeatures {
private TorcGraphEdgeFeatures() {
}
@Override
public boolean supportsAddEdges() {
return true;
}
@Override
public boolean supportsRemoveEdges() {
return false;
}
@Override
public Features.EdgePropertyFeatures properties() {
return new TorcGraphEdgePropertyFeatures() {
};
}
@Override
public boolean supportsAddProperty() {
return false;
}
@Override
public boolean supportsRemoveProperty() {
return false;
}
@Override
public boolean supportsUserSuppliedIds() {
return false;
}
@Override
public boolean supportsNumericIds() {
return false;
}
@Override
public boolean supportsStringIds() {
return false;
}
@Override
public boolean supportsUuidIds() {
return false;
}
@Override
public boolean supportsCustomIds() {
return false;
}
@Override
public boolean supportsAnyIds() {
return false;
}
}
public class TorcGraphVertexPropertyFeatures implements Features.VertexPropertyFeatures {
private TorcGraphVertexPropertyFeatures() {
}
@Override
public boolean supportsAddProperty() {
return false;
}
@Override
public boolean supportsRemoveProperty() {
return false;
}
@Override
public boolean supportsUserSuppliedIds() {
return false;
}
@Override
public boolean supportsNumericIds() {
return false;
}
@Override
public boolean supportsStringIds() {
return false;
}
@Override
public boolean supportsUuidIds() {
return false;
}
@Override
public boolean supportsCustomIds() {
return false;
}
@Override
public boolean supportsAnyIds() {
return false;
}
@Override
public boolean supportsBooleanValues() {
return false;
}
@Override
public boolean supportsByteValues() {
return false;
}
@Override
public boolean supportsDoubleValues() {
return false;
}
@Override
public boolean supportsFloatValues() {
return false;
}
@Override
public boolean supportsIntegerValues() {
return false;
}
@Override
public boolean supportsLongValues() {
return false;
}
@Override
public boolean supportsMapValues() {
return false;
}
@Override
public boolean supportsMixedListValues() {
return false;
}
@Override
public boolean supportsBooleanArrayValues() {
return false;
}
@Override
public boolean supportsByteArrayValues() {
return false;
}
@Override
public boolean supportsDoubleArrayValues() {
return false;
}
@Override
public boolean supportsFloatArrayValues() {
return false;
}
@Override
public boolean supportsIntegerArrayValues() {
return false;
}
@Override
public boolean supportsStringArrayValues() {
return false;
}
@Override
public boolean supportsLongArrayValues() {
return false;
}
@Override
public boolean supportsSerializableValues() {
return false;
}
@Override
public boolean supportsStringValues() {
return true;
}
@Override
public boolean supportsUniformListValues() {
return false;
}
}
public class TorcGraphEdgePropertyFeatures implements Features.EdgePropertyFeatures {
private TorcGraphEdgePropertyFeatures() {
}
@Override
public boolean supportsBooleanValues() {
return false;
}
@Override
public boolean supportsByteValues() {
return false;
}
@Override
public boolean supportsDoubleValues() {
return false;
}
@Override
public boolean supportsFloatValues() {
return false;
}
@Override
public boolean supportsIntegerValues() {
return false;
}
@Override
public boolean supportsLongValues() {
return false;
}
@Override
public boolean supportsMapValues() {
return false;
}
@Override
public boolean supportsMixedListValues() {
return false;
}
@Override
public boolean supportsBooleanArrayValues() {
return false;
}
@Override
public boolean supportsByteArrayValues() {
return false;
}
@Override
public boolean supportsDoubleArrayValues() {
return false;
}
@Override
public boolean supportsFloatArrayValues() {
return false;
}
@Override
public boolean supportsIntegerArrayValues() {
return false;
}
@Override
public boolean supportsStringArrayValues() {
return false;
}
@Override
public boolean supportsLongArrayValues() {
return false;
}
@Override
public boolean supportsSerializableValues() {
return false;
}
@Override
public boolean supportsStringValues() {
return true;
}
@Override
public boolean supportsUniformListValues() {
return false;
}
}
public class TorcGraphVariableFeatures implements Features.VariableFeatures {
private TorcGraphVariableFeatures() {
}
@Override
public boolean supportsBooleanValues() {
return false;
}
@Override
public boolean supportsByteValues() {
return false;
}
@Override
public boolean supportsDoubleValues() {
return false;
}
@Override
public boolean supportsFloatValues() {
return false;
}
@Override
public boolean supportsIntegerValues() {
return false;
}
@Override
public boolean supportsLongValues() {
return false;
}
@Override
public boolean supportsMapValues() {
return false;
}
@Override
public boolean supportsMixedListValues() {
return false;
}
@Override
public boolean supportsBooleanArrayValues() {
return false;
}
@Override
public boolean supportsByteArrayValues() {
return false;
}
@Override
public boolean supportsDoubleArrayValues() {
return false;
}
@Override
public boolean supportsFloatArrayValues() {
return false;
}
@Override
public boolean supportsIntegerArrayValues() {
return false;
}
@Override
public boolean supportsStringArrayValues() {
return false;
}
@Override
public boolean supportsLongArrayValues() {
return false;
}
@Override
public boolean supportsSerializableValues() {
return false;
}
@Override
public boolean supportsStringValues() {
return false;
}
@Override
public boolean supportsUniformListValues() {
return false;
}
}
}
| src/main/java/org/ellitron/tinkerpop/gremlin/torc/structure/TorcGraph.java | /*
* Copyright 2015 Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// TODO: Change license to match RAMCloud
package org.ellitron.tinkerpop.gremlin.torc.structure;
import org.apache.tinkerpop.gremlin.process.computer.GraphComputer;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Transaction;
import org.apache.tinkerpop.gremlin.structure.VertexProperty;
import org.apache.tinkerpop.gremlin.structure.util.ElementHelper;
import org.apache.tinkerpop.gremlin.structure.util.StringFactory;
import edu.stanford.ramcloud.*;
import edu.stanford.ramcloud.transactions.*;
import edu.stanford.ramcloud.ClientException.*;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.HashMap;
import org.apache.commons.configuration.Configuration;
import org.apache.log4j.Logger;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.tinkerpop.gremlin.structure.Direction;
import org.apache.tinkerpop.gremlin.structure.Element;
import org.apache.tinkerpop.gremlin.structure.Property;
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.util.AbstractTransaction;
import org.ellitron.tinkerpop.gremlin.torc.structure.util.TorcHelper;
/**
* TODO: Write documentation - Bidirectional edges
*
*
* @author Jonathan Ellithorpe <[email protected]>
*
* TODO: Make TorcGraph thread safe. Currently every TorcGraph method that
* performs reads or writes to the database uses a ThreadLocal
* RAMCloudTransaction to isolate transactions from different threads. Each
* ThreadLocal RAMCloudTransaction object, however, is constructed with a
* reference to the same RAMCloud client object, which itself is not thread
* safe. Therefore, TorcGraph, although using separate RAMCloudTransaction
* objects for each thread, it not actually thread safe. To fix this problem,
* each ThreadLocal RAMCloudTransaction object needs to be constructed with its
* own RAMCloud client object.
*
* TODO: Implement way of handling objects that are larger than 1MB.
*/
@Graph.OptIn(Graph.OptIn.SUITE_STRUCTURE_STANDARD)
public final class TorcGraph implements Graph {
private static final Logger logger = Logger.getLogger(TorcGraph.class);
// Configuration keys.
public static final String CONFIG_GRAPH_NAME = "gremlin.torc.graphName";
public static final String CONFIG_COORD_LOCATOR = "gremlin.torc.coordinatorLocator";
public static final String CONFIG_NUM_MASTER_SERVERS = "gremlin.torc.numMasterServers";
public static final String CONFIG_LOG_LEVEL = "gremlin.torc.logLevel";
// Constants.
private static final String ID_TABLE_NAME = "idTable";
private static final String VERTEX_TABLE_NAME = "vertexTable";
private static final String EDGE_TABLE_NAME = "edgeTable";
private static final int MAX_TX_RETRY_COUNT = 100;
private static final int NUM_ID_COUNTERS = 16;
// Normal private members.
private final Configuration configuration;
private final String coordinatorLocator;
private final int totalMasterServers;
private final ConcurrentHashMap<Thread, RAMCloud> threadLocalClientMap = new ConcurrentHashMap<>();
private long idTableId, vertexTableId, edgeTableId;
private final String graphName;
private final TorcGraphTransaction torcGraphTx = new TorcGraphTransaction();
boolean initialized = false;
private TorcGraph(final Configuration configuration) {
this.configuration = configuration;
graphName = configuration.getString(CONFIG_GRAPH_NAME);
coordinatorLocator = configuration.getString(CONFIG_COORD_LOCATOR);
totalMasterServers = configuration.getInt(CONFIG_NUM_MASTER_SERVERS);
logger.debug(String.format("Constructing TorcGraph (%s,%s,%d)", graphName, coordinatorLocator, totalMasterServers));
}
public boolean isInitialized() {
return initialized;
}
/**
* This method ensures three things are true before it returns to the
* caller:
*
* 1) This thread has an initialized thread-local RAMCloud client (its own
* connection to RAMCloud)
*
* 2) RAMCloud tables have been created for this graph
*
* 3) RAMCloud table IDs have been fetched.
*
*
* This method is intended to be used as a way of deferring costly
* initialization until absolutely needed. This method should be called at
* the top of any public method of TorcGraph that performs operations
* against RAMCloud.
*/
private void initialize() {
if (!threadLocalClientMap.containsKey(Thread.currentThread())) {
threadLocalClientMap.put(Thread.currentThread(), new RAMCloud(coordinatorLocator));
logger.debug(String.format("initialize(): Thread %d made connection to RAMCloud cluster.", Thread.currentThread().getId()));
if (!initialized) {
RAMCloud client = threadLocalClientMap.get(Thread.currentThread());
idTableId = client.createTable(graphName + "_" + ID_TABLE_NAME, totalMasterServers);
vertexTableId = client.createTable(graphName + "_" + VERTEX_TABLE_NAME, totalMasterServers);
edgeTableId = client.createTable(graphName + "_" + EDGE_TABLE_NAME, totalMasterServers);
initialized = true;
logger.debug(String.format("initialize(): Fetched table Ids (%s=%d,%s=%d,%s=%d)", graphName + "_" + ID_TABLE_NAME, idTableId, graphName + "_" + VERTEX_TABLE_NAME, vertexTableId, graphName + "_" + EDGE_TABLE_NAME, edgeTableId));
}
}
}
public static TorcGraph open(final Configuration configuration) {
return new TorcGraph(configuration);
}
@Override
public Vertex addVertex(final Object... keyValues) {
long startTimeNs = 0;
if (logger.isDebugEnabled()) {
startTimeNs = System.nanoTime();
}
initialize();
torcGraphTx.readWrite();
RAMCloudTransaction rctx = torcGraphTx.getThreadLocalRAMCloudTx();
ElementHelper.legalPropertyKeyValueArray(keyValues);
// Only values of type String supported, currently.
for (int i = 0; i < keyValues.length; i = i + 2) {
if (!(keyValues[i] instanceof T) && !(keyValues[i + 1] instanceof String)) {
throw Property.Exceptions.dataTypeOfPropertyValueNotSupported(keyValues[i + 1]);
}
}
Object idValue = ElementHelper.getIdValue(keyValues).orElse(null);
final String label = ElementHelper.getLabelValue(keyValues).orElse(Vertex.DEFAULT_LABEL);
UInt128 vertexId;
if (idValue != null) {
vertexId = UInt128.decode(idValue);
// Check if a vertex with this ID already exists.
try {
rctx.read(vertexTableId, TorcHelper.getVertexLabelKey(vertexId));
throw Graph.Exceptions.vertexWithIdAlreadyExists(vertexId.toString());
} catch (ObjectDoesntExistException e) {
// Good!
}
} else {
long id_counter = (long) (Math.random() * NUM_ID_COUNTERS);
RAMCloud client = threadLocalClientMap.get(Thread.currentThread());
long id = client.incrementInt64(idTableId, Long.toString(id_counter).getBytes(), 1, null);
vertexId = new UInt128((1L << 63) + id_counter, id);
}
// Create property map.
Map<String, String> properties = new HashMap<>();
for (int i = 0; i < keyValues.length; i = i + 2) {
if (keyValues[i] instanceof String) {
properties.put((String) keyValues[i], (String) keyValues[i + 1]);
}
}
rctx.write(vertexTableId, TorcHelper.getVertexLabelKey(vertexId), label.getBytes());
rctx.write(vertexTableId, TorcHelper.getVertexPropertiesKey(vertexId), TorcHelper.serializeProperties(properties).array());
if (logger.isDebugEnabled()) {
long endTimeNs = System.nanoTime();
int propLength = TorcHelper.serializeProperties(properties).array().length;
logger.debug(String.format("addVertex(id=%s,label=%s,propLen=%d), took %dus", vertexId.toString(), label, propLength, (endTimeNs - startTimeNs) / 1000l));
}
return new TorcVertex(this, vertexId, label);
}
@Override
public <C extends GraphComputer> C compute(final Class<C> type) throws IllegalArgumentException {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public GraphComputer compute() throws IllegalArgumentException {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public Iterator<Vertex> vertices(final Object... vertexIds) {
long startTimeNs = 0;
if (logger.isDebugEnabled()) {
startTimeNs = System.nanoTime();
}
initialize();
torcGraphTx.readWrite();
RAMCloudTransaction rctx = torcGraphTx.getThreadLocalRAMCloudTx();
ElementHelper.validateMixedElementIds(TorcVertex.class, vertexIds);
List<Vertex> list = new ArrayList<>();
if (vertexIds.length > 0) {
if (vertexIds[0] instanceof TorcVertex) {
Arrays.asList(vertexIds).forEach((id) -> {
list.add((Vertex) id);
});
} else {
for (int i = 0; i < vertexIds.length; ++i) {
UInt128 vertexId = UInt128.decode(vertexIds[i]);
RAMCloudObject obj;
try {
obj = rctx.read(vertexTableId, TorcHelper.getVertexLabelKey(vertexId));
} catch (ObjectDoesntExistException e) {
throw Graph.Exceptions.elementNotFound(TorcVertex.class, vertexIds[i]);
}
list.add(new TorcVertex(this, vertexId, obj.getValue()));
}
}
} else {
long max_id[] = new long[NUM_ID_COUNTERS];
for (int i = 0; i < NUM_ID_COUNTERS; ++i) {
try {
ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES);
buffer.order(ByteOrder.LITTLE_ENDIAN);
buffer.put(rctx.read(idTableId, Long.toString(i)).getValueBytes());
buffer.flip();
max_id[i] = buffer.getLong();
} catch (ObjectDoesntExistException e) {
max_id[i] = 0;
}
}
for (int i = 0; i < NUM_ID_COUNTERS; ++i) {
for (long j = 1; j <= max_id[i]; ++j) {
UInt128 vertexId = new UInt128((1L << 63) + i, j);
try {
RAMCloudObject obj = rctx.read(vertexTableId, TorcHelper.getVertexLabelKey(vertexId));
list.add(new TorcVertex(this, vertexId, obj.getValue()));
} catch (ObjectDoesntExistException e) {
// Continue...
}
}
}
}
if (logger.isDebugEnabled()) {
long endTimeNs = System.nanoTime();
logger.debug(String.format("vertices(n=%d), took %dus", vertexIds.length, (endTimeNs - startTimeNs) / 1000l));
}
return list.iterator();
}
@Override
public Iterator<Edge> edges(final Object... edgeIds) {
long startTimeNs = 0;
if (logger.isDebugEnabled()) {
startTimeNs = System.nanoTime();
}
initialize();
torcGraphTx.readWrite();
RAMCloudTransaction rctx = torcGraphTx.getThreadLocalRAMCloudTx();
ElementHelper.validateMixedElementIds(TorcEdge.class, edgeIds);
List<Edge> list = new ArrayList<>();
if (edgeIds.length > 0) {
if (edgeIds[0] instanceof TorcEdge) {
list = Arrays.asList((Edge[]) edgeIds);
} else if (edgeIds[0] instanceof TorcEdge.Id) {
for (int i = 0; i < edgeIds.length; ++i) {
list.add(((TorcEdge.Id) edgeIds[i]).getEdge());
}
} else {
throw Graph.Exceptions.elementNotFound(TorcEdge.class, edgeIds[0]);
}
} else {
long max_id[] = new long[NUM_ID_COUNTERS];
for (int i = 0; i < NUM_ID_COUNTERS; ++i) {
try {
ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES);
buffer.order(ByteOrder.LITTLE_ENDIAN);
buffer.put(rctx.read(idTableId, Integer.toString(i)).getValueBytes());
buffer.flip();
max_id[i] = buffer.getLong();
} catch (ObjectDoesntExistException e) {
max_id[i] = 0;
}
}
for (int i = 0; i < NUM_ID_COUNTERS; ++i) {
for (long j = 1; j <= max_id[i]; ++j) {
UInt128 baseVertexId = new UInt128((1L << 63) + i, j);
try {
RAMCloudObject obj = rctx.read(vertexTableId, TorcHelper.getVertexEdgeLabelListKey(baseVertexId));
List<String> edgeLabels = TorcHelper.deserializeEdgeLabelList(obj);
for (String label : edgeLabels) {
try {
obj = rctx.read(vertexTableId, TorcHelper.getVertexEdgeListKey(baseVertexId, label, TorcEdgeDirection.DIRECTED_OUT));
List<UInt128> neighborVertexIds = TorcHelper.parseNeighborIdsFromEdgeList(obj);
for (UInt128 neighborVertexId : neighborVertexIds) {
list.add(new TorcEdge(this, baseVertexId, neighborVertexId, TorcEdge.Type.DIRECTED, label));
}
} catch (ObjectDoesntExistException e) {
/*
* The DIRECTED_OUT edge list for this label
* doesn't exist. Continue...
*/
}
/**
* TODO: Decide whether or not to include the new
* bi-directional edges in this list. Not sure
* whether or not including these RAMCloudGraph
* specific bi-directional edges is considered a
* violation of the API.
*/
try {
obj = rctx.read(vertexTableId, TorcHelper.getVertexEdgeListKey(baseVertexId, label, TorcEdgeDirection.UNDIRECTED));
List<UInt128> neighborVertexIds = TorcHelper.parseNeighborIdsFromEdgeList(obj);
for (UInt128 neighborVertexId : neighborVertexIds) {
/*
* Prevent double counting of undirected
* edges. Only count the edge at the vertex
* with the min ID.
*/
if (baseVertexId.compareTo(neighborVertexId) < 0) {
list.add(new TorcEdge(this, baseVertexId, neighborVertexId, TorcEdge.Type.UNDIRECTED, label));
}
}
} catch (ObjectDoesntExistException e) {
/*
* The UNDIRECTED edge list for this label
* doesn't exist. Continue...
*/
}
}
} catch (ObjectDoesntExistException e) {
/*
* The edge label list object for this vertex doesn't
* exist
*/
}
}
}
}
if (logger.isDebugEnabled()) {
long endTimeNs = System.nanoTime();
logger.debug(String.format("edges(n=%d), took %dus", edgeIds.length, (endTimeNs - startTimeNs) / 1000l));
}
return list.iterator();
}
@Override
public Transaction tx() {
initialize();
return torcGraphTx;
}
@Override
public Variables variables() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public Configuration configuration() {
return configuration;
}
/**
* Closes the thread-local transaction (if it is open), and closes the
* thread-local connection to RAMCloud (if one has been made). This may
* affect the state of the graph in RAMCloud depending on the close behavior
* set for the transaction (e.g. in the case that there is an open
* transaction which is set to automatically commit when closed).
*
* Important: Every thread that performs any operation on this graph
* instance has the responsibility of calling this close method before
* exiting. Otherwise it is possible that state that has been created via
* the RAMCloud JNI library will not be cleaned up properly (for instance,
* although {@link RAMCloud} and {@link RAMCloudTransaction} objects have
* implemented finalize() methods to clean up their mirrored C++ objects, it
* is still possible that the garbage collector will clean up the RAMCloud
* object before the RAMCloudTransaction object that uses it. This *may*
* lead to unexpected behavior).
*/
@Override
public void close() {
long startTimeNs = 0;
if (logger.isDebugEnabled()) {
startTimeNs = System.nanoTime();
}
if (threadLocalClientMap.containsKey(Thread.currentThread())) {
torcGraphTx.close();
RAMCloud client = threadLocalClientMap.get(Thread.currentThread());
client.disconnect();
threadLocalClientMap.remove(Thread.currentThread());
}
if (logger.isDebugEnabled()) {
long endTimeNs = System.nanoTime();
logger.debug(String.format("close(), took %dus", (endTimeNs - startTimeNs) / 1000l));
}
}
/**
* This method closes all open transactions on all threads (using rollback),
* and closes all open client connections to RAMCloud on all threads. Since
* this method uses rollback as the close mechanism for open transactions,
* and RAMCloud transactions keep no server-side state until commit, it is
* safe to execute this method even after the graph has been deleted with
* {@link #deleteAll()}. Its intended use is primarily for unit tests to
* ensure the freeing of all client-side state remaining across JNI (i.e.
* C++ RAMCloud client objects, C++ RAMCloud Transaction objects) before
* finishing the current test and moving on to the next.
*/
public void closeAllThreads() {
long startTimeNs = 0;
if (logger.isDebugEnabled()) {
startTimeNs = System.nanoTime();
}
torcGraphTx.doRollbackAllThreads();
threadLocalClientMap.forEach((thread, client) -> {
try {
client.disconnect();
} catch (Exception e) {
logger.error("closeAllThreads(): could not close transaction of thread " + thread.getId());
}
logger.debug(String.format("closeAllThreads(): closed client connection of %d", thread.getId()));
});
threadLocalClientMap.clear();
if (logger.isDebugEnabled()) {
long endTimeNs = System.nanoTime();
logger.debug(String.format("closeAllThreads(), took %dus", (endTimeNs - startTimeNs) / 1000l));
}
}
/**
* Deletes all graph data for the graph represented by this TorcGraph
* instance in RAMCloud.
*
* This method's intended use is for the reset phase of unit tests (see also
* {@link #closeAllThreads()}). To delete all RAMCloud state representing
* this graph as well as clear up all client-side state, one would execute
* the following in sequence:
*
* graph.deleteGraph();
*
* graph.closeAllThreads();
*/
public void deleteGraph() {
long startTimeNs = 0;
if (logger.isDebugEnabled()) {
startTimeNs = System.nanoTime();
}
initialize();
RAMCloud client = threadLocalClientMap.get(Thread.currentThread());
client.dropTable(graphName + "_" + ID_TABLE_NAME);
client.dropTable(graphName + "_" + VERTEX_TABLE_NAME);
client.dropTable(graphName + "_" + EDGE_TABLE_NAME);
if (logger.isDebugEnabled()) {
long endTimeNs = System.nanoTime();
logger.debug(String.format("deleteGraph(), took %dus", (endTimeNs - startTimeNs) / 1000l));
}
}
@Override
public String toString() {
return StringFactory.graphString(this, "coordLoc:" + this.coordinatorLocator + " graphName:" + this.graphName);
}
@Override
public Features features() {
return new TorcGraphFeatures();
}
/**
* Methods called by TorcVertex.
*/
void removeVertex(final TorcVertex vertex) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
Edge addEdge(final TorcVertex vertex1, final TorcVertex vertex2, final String label, final TorcEdge.Type type, final Object[] keyValues) {
long startTimeNs = 0;
if (logger.isDebugEnabled()) {
startTimeNs = System.nanoTime();
}
torcGraphTx.readWrite();
RAMCloudTransaction rctx = torcGraphTx.getThreadLocalRAMCloudTx();
// Validate that these key/value pairs are all strings
if (keyValues.length % 2 != 0) {
throw Element.Exceptions.providedKeyValuesMustBeAMultipleOfTwo();
}
for (int i = 0; i < keyValues.length; i = i + 2) {
if (keyValues[i] instanceof T) {
if (keyValues[i].equals(T.id)) {
throw Edge.Exceptions.userSuppliedIdsNotSupported();
} else {
throw new UnsupportedOperationException("Not supported yet.");
}
}
if (!(keyValues[i] instanceof String)) {
throw Element.Exceptions.providedKeyValuesMustHaveALegalKeyOnEvenIndices();
}
if (!(keyValues[i + 1] instanceof String)) {
throw Property.Exceptions.dataTypeOfPropertyValueNotSupported(keyValues[i + 1]);
}
}
// Create property map.
Map<String, String> properties = new HashMap<>();
for (int i = 0; i < keyValues.length; i = i + 2) {
properties.put((String) keyValues[i], (String) keyValues[i + 1]);
}
ByteBuffer serializedProperties = TorcHelper.serializeProperties(properties);
int serializedEdgeLength = Long.BYTES * 2 + Short.BYTES + serializedProperties.array().length;
// TODO: Figure out a way to work this logic into a function so it's not
// repeated twice as it is below.
// Update vertex1's edge list
byte[] edgeListKey;
if (type == TorcEdge.Type.UNDIRECTED) {
edgeListKey = TorcHelper.getVertexEdgeListKey(vertex1.id(), label, TorcEdgeDirection.UNDIRECTED);
} else {
edgeListKey = TorcHelper.getVertexEdgeListKey(vertex1.id(), label, TorcEdgeDirection.DIRECTED_OUT);
}
try {
RAMCloudObject edgeListRCObj = rctx.read(vertexTableId, edgeListKey);
ByteBuffer newEdgeList = ByteBuffer.allocate(serializedEdgeLength + edgeListRCObj.getValueBytes().length);
newEdgeList.put(vertex2.id().toByteArray());
newEdgeList.putShort((short) serializedProperties.array().length);
newEdgeList.put(serializedProperties.array());
newEdgeList.put(edgeListRCObj.getValueBytes());
rctx.write(vertexTableId, edgeListKey, newEdgeList.array());
} catch (ObjectDoesntExistException e) {
ByteBuffer newEdgeList = ByteBuffer.allocate(serializedEdgeLength);
newEdgeList.put(vertex2.id().toByteArray());
newEdgeList.putShort((short) serializedProperties.array().length);
newEdgeList.put(serializedProperties.array());
rctx.write(vertexTableId, edgeListKey, newEdgeList.array());
byte[] edgeLabelListKey = TorcHelper.getVertexEdgeLabelListKey(vertex1.id());
try {
RAMCloudObject edgeLabelListRCObj = rctx.read(vertexTableId, edgeLabelListKey);
List<String> edgeLabelList = TorcHelper.deserializeEdgeLabelList(edgeLabelListRCObj);
if (!edgeLabelList.contains(label)) {
edgeLabelList.add(label);
rctx.write(vertexTableId, edgeLabelListKey, TorcHelper.serializeEdgeLabelList(edgeLabelList).array());
}
} catch (ObjectDoesntExistException e2) {
List<String> edgeLabelList = new ArrayList<>();
edgeLabelList.add(label);
rctx.write(vertexTableId, edgeLabelListKey, TorcHelper.serializeEdgeLabelList(edgeLabelList).array());
}
}
// Update vertex2's edge list
if (type == TorcEdge.Type.UNDIRECTED) {
edgeListKey = TorcHelper.getVertexEdgeListKey(vertex2.id(), label, TorcEdgeDirection.UNDIRECTED);
} else {
edgeListKey = TorcHelper.getVertexEdgeListKey(vertex2.id(), label, TorcEdgeDirection.DIRECTED_IN);
}
try {
RAMCloudObject edgeListRCObj = rctx.read(vertexTableId, edgeListKey);
ByteBuffer newEdgeList = ByteBuffer.allocate(serializedEdgeLength + edgeListRCObj.getValueBytes().length);
newEdgeList.put(vertex1.id().toByteArray());
newEdgeList.putShort((short) serializedProperties.array().length);
newEdgeList.put(serializedProperties.array());
newEdgeList.put(edgeListRCObj.getValueBytes());
rctx.write(vertexTableId, edgeListKey, newEdgeList.array());
} catch (ObjectDoesntExistException e) {
ByteBuffer newEdgeList = ByteBuffer.allocate(serializedEdgeLength);
newEdgeList.put(vertex1.id().toByteArray());
newEdgeList.putShort((short) serializedProperties.array().length);
newEdgeList.put(serializedProperties.array());
rctx.write(vertexTableId, edgeListKey, newEdgeList.array());
byte[] edgeLabelListKey = TorcHelper.getVertexEdgeLabelListKey(vertex2.id());
try {
RAMCloudObject edgeLabelListRCObj = rctx.read(vertexTableId, edgeLabelListKey);
List<String> edgeLabelList = TorcHelper.deserializeEdgeLabelList(edgeLabelListRCObj);
if (!edgeLabelList.contains(label)) {
edgeLabelList.add(label);
rctx.write(vertexTableId, edgeLabelListKey, TorcHelper.serializeEdgeLabelList(edgeLabelList).array());
}
} catch (ObjectDoesntExistException e2) {
List<String> edgeLabelList = new ArrayList<>();
edgeLabelList.add(label);
rctx.write(vertexTableId, edgeLabelListKey, TorcHelper.serializeEdgeLabelList(edgeLabelList).array());
}
}
if (logger.isDebugEnabled()) {
long endTimeNs = System.nanoTime();
int propLength = TorcHelper.serializeProperties(properties).array().length;
logger.debug(String.format("addEdge(from=%s,to=%s,label=%s,propLen=%d), took %dus", vertex1.id().toString(), vertex2.id().toString(), label, propLength, (endTimeNs - startTimeNs) / 1000l));
}
return new TorcEdge(this, vertex1.id(), vertex2.id(), type, label);
}
Iterator<Edge> vertexEdges(final TorcVertex vertex, final EnumSet<TorcEdgeDirection> edgeDirections, final String[] edgeLabels) {
long startTimeNs = 0;
if (logger.isDebugEnabled()) {
startTimeNs = System.nanoTime();
}
torcGraphTx.readWrite();
RAMCloudTransaction rctx = torcGraphTx.getThreadLocalRAMCloudTx();
List<Edge> edges = new ArrayList<>();
List<String> labels = Arrays.asList(edgeLabels);
if (labels.isEmpty()) {
try {
RAMCloudObject vertEdgeLabelListRCObj = rctx.read(vertexTableId, TorcHelper.getVertexEdgeLabelListKey(vertex.id()));
labels = TorcHelper.deserializeEdgeLabelList(vertEdgeLabelListRCObj);
} catch (ObjectDoesntExistException e) {
}
}
for (String label : labels) {
for (TorcEdgeDirection dir : edgeDirections) {
try {
byte[] edgeListKey = TorcHelper.getVertexEdgeListKey(vertex.id(), label, dir);
RAMCloudObject edgeListRCObj = rctx.read(vertexTableId, edgeListKey);
List<UInt128> neighborVertexIds = TorcHelper.parseNeighborIdsFromEdgeList(edgeListRCObj);
for (UInt128 neighborVertexId : neighborVertexIds) {
switch (dir) {
case DIRECTED_OUT:
edges.add(new TorcEdge(this, vertex.id(), neighborVertexId, TorcEdge.Type.DIRECTED, label));
break;
case DIRECTED_IN:
edges.add(new TorcEdge(this, neighborVertexId, vertex.id(), TorcEdge.Type.DIRECTED, label));
break;
case UNDIRECTED:
edges.add(new TorcEdge(this, vertex.id(), neighborVertexId, TorcEdge.Type.UNDIRECTED, label));
break;
}
}
} catch (ObjectDoesntExistException e) {
/*
* The list of edges for this direction and label does not
* exist. Continue...
*/
}
}
}
if (logger.isDebugEnabled()) {
long endTimeNs = System.nanoTime();
logger.debug(String.format("vertexEdges(vertex=%s,directions=%s,labels=%s), took %dus", vertex.id().toString(), edgeDirections.toString(), labels.toString(), (endTimeNs - startTimeNs) / 1000l));
}
return edges.iterator();
}
Iterator<Vertex> vertexNeighbors(final TorcVertex vertex, final EnumSet<TorcEdgeDirection> edgeDirections, final String[] edgeLabels) {
long startTimeNs = 0;
if (logger.isDebugEnabled()) {
startTimeNs = System.nanoTime();
}
torcGraphTx.readWrite();
RAMCloudTransaction rctx = torcGraphTx.getThreadLocalRAMCloudTx();
List<Vertex> vertices = new ArrayList<>();
List<String> labels = Arrays.asList(edgeLabels);
if (labels.isEmpty()) {
try {
RAMCloudObject vertEdgeLabelListRCObj = rctx.read(vertexTableId, TorcHelper.getVertexEdgeLabelListKey(vertex.id()));
labels = TorcHelper.deserializeEdgeLabelList(vertEdgeLabelListRCObj);
} catch (ObjectDoesntExistException e) {
}
}
for (String label : labels) {
for (TorcEdgeDirection dir : edgeDirections) {
try {
byte[] edgeListKey = TorcHelper.getVertexEdgeListKey(vertex.id(), label, dir);
RAMCloudObject edgeListRCObj = rctx.read(vertexTableId, edgeListKey);
List<UInt128> neighborIds = TorcHelper.parseNeighborIdsFromEdgeList(edgeListRCObj);
for (UInt128 neighborId : neighborIds) {
RAMCloudObject neighborLabelRCObj = rctx.read(vertexTableId, TorcHelper.getVertexLabelKey(neighborId));
vertices.add(new TorcVertex(this, neighborId, neighborLabelRCObj.getValue()));
}
} catch (ObjectDoesntExistException e) {
/*
* The list of edges for this direction and label does not
* exist. Continue...
*/
}
}
}
if (logger.isDebugEnabled()) {
long endTimeNs = System.nanoTime();
logger.debug(String.format("vertexNeighbors(vertex=%s,directions=%s,labels=%s), took %dus", vertex.id().toString(), edgeDirections.toString(), labels.toString(), (endTimeNs - startTimeNs) / 1000l));
}
return vertices.iterator();
}
<V> Iterator<VertexProperty<V>> getVertexProperties(final TorcVertex vertex, final String[] propertyKeys) {
long startTimeNs = 0;
if (logger.isDebugEnabled()) {
startTimeNs = System.nanoTime();
}
torcGraphTx.readWrite();
RAMCloudTransaction rctx = torcGraphTx.getThreadLocalRAMCloudTx();
RAMCloudObject obj = rctx.read(vertexTableId, TorcHelper.getVertexPropertiesKey(vertex.id()));
Map<String, String> properties = TorcHelper.deserializeProperties(obj);
List<VertexProperty<V>> propList = new ArrayList<>();
if (propertyKeys.length > 0) {
for (String key : propertyKeys) {
if (properties.containsKey(key)) {
propList.add(new TorcVertexProperty(vertex, key, properties.get(key)));
} else {
throw Property.Exceptions.propertyDoesNotExist(vertex, key);
}
}
} else {
for (Map.Entry<String, String> property : properties.entrySet()) {
// TODO: Here I am implicitly assuming that V is of type String,
// since property.getValue() returns a string, making the new
// elemennt to propList TorcVertexProperty<String>
propList.add(new TorcVertexProperty(vertex, property.getKey(), property.getValue()));
}
}
if (logger.isDebugEnabled()) {
long endTimeNs = System.nanoTime();
logger.debug(String.format("getVertexProperties(vertex=%s,propKeys=%s), took %dus", vertex.id().toString(), Arrays.asList(propertyKeys).toString(), (endTimeNs - startTimeNs) / 1000l));
}
return propList.iterator();
}
<V> VertexProperty<V> setVertexProperty(final TorcVertex vertex, final VertexProperty.Cardinality cardinality, final String key, final V value, final Object[] keyValues) {
long startTimeNs = 0;
if (logger.isDebugEnabled()) {
startTimeNs = System.nanoTime();
}
torcGraphTx.readWrite();
RAMCloudTransaction rctx = torcGraphTx.getThreadLocalRAMCloudTx();
if (keyValues != null) {
throw VertexProperty.Exceptions.metaPropertiesNotSupported();
}
if (!(value instanceof String)) {
throw Property.Exceptions.dataTypeOfPropertyValueNotSupported(value);
}
RAMCloudObject obj = rctx.read(vertexTableId, TorcHelper.getVertexPropertiesKey(vertex.id()));
Map<String, String> properties = TorcHelper.deserializeProperties(obj);
if (properties.containsKey(key)) {
if (cardinality == VertexProperty.Cardinality.single) {
properties.put(key, (String) value);
} else if (cardinality == VertexProperty.Cardinality.list) {
throw VertexProperty.Exceptions.multiPropertiesNotSupported();
} else if (cardinality == VertexProperty.Cardinality.set) {
throw VertexProperty.Exceptions.multiPropertiesNotSupported();
} else {
throw new UnsupportedOperationException("Do not recognize Cardinality of this type: " + cardinality.toString());
}
} else {
properties.put(key, (String) value);
}
rctx.write(vertexTableId, TorcHelper.getVertexPropertiesKey(vertex.id()), TorcHelper.serializeProperties(properties).array());
if (logger.isDebugEnabled()) {
long endTimeNs = System.nanoTime();
logger.debug(String.format("setVertexProperty(vertex=%s,card=%s,key=%s,value=%s), took %dus", vertex.id().toString(), cardinality.toString(), key, value, (endTimeNs - startTimeNs) / 1000l));
}
return new TorcVertexProperty(vertex, key, value);
}
/**
* Methods called by TorcEdge.
*/
void removeEdge(final TorcEdge edge) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
Iterator<Vertex> edgeVertices(final TorcEdge edge, final Direction direction) {
long startTimeNs = 0;
if (logger.isDebugEnabled()) {
startTimeNs = System.nanoTime();
}
if (edge.getType() == TorcEdge.Type.UNDIRECTED
&& direction != Direction.BOTH) {
throw new RuntimeException(String.format("Tried get source/destination vertex of an undirected edge: [edge:%s, direction:%s]", edge.toString(), direction.toString()));
}
torcGraphTx.readWrite();
RAMCloudTransaction rctx = torcGraphTx.getThreadLocalRAMCloudTx();
List<Vertex> list = new ArrayList<>();
if (direction.equals(Direction.OUT) || direction.equals(Direction.BOTH)) {
RAMCloudObject obj = rctx.read(vertexTableId, TorcHelper.getVertexLabelKey(edge.getV1Id()));
list.add(new TorcVertex(this, edge.getV1Id(), obj.getValue()));
}
if (direction.equals(Direction.IN) || direction.equals(Direction.BOTH)) {
RAMCloudObject obj = rctx.read(vertexTableId, TorcHelper.getVertexLabelKey(edge.getV2Id()));
list.add(new TorcVertex(this, edge.getV2Id(), obj.getValue()));
}
if (logger.isDebugEnabled()) {
long endTimeNs = System.nanoTime();
// TODO: Update this when we have TorcEdgeId class to stringify
logger.debug(String.format("edgeVertices(edgeIdGoesHere,dir=%s), took %dus", direction.toString(), (endTimeNs - startTimeNs) / 1000l));
}
return list.iterator();
}
<V> Iterator<Property<V>> getEdgeProperties(final TorcEdge edge, final String[] propertyKeys) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
<V> Property<V> setEdgeProperty(final TorcEdge edge, final String key, final V value) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public boolean equals(Object that) {
if (!(that instanceof TorcGraph)) {
return false;
}
TorcGraph thatGraph = (TorcGraph) that;
return this.coordinatorLocator.equals(thatGraph.coordinatorLocator)
&& this.graphName.equals(thatGraph.graphName);
}
@Override
public int hashCode() {
int hash = 7;
hash = 29 * hash + Objects.hashCode(this.coordinatorLocator);
hash = 29 * hash + Objects.hashCode(this.graphName);
return hash;
}
// TODO: Move this into its own file.
public static class Exceptions {
public static IllegalArgumentException userSuppliedIdNotValid(String message) {
throw new IllegalArgumentException("Invalid vertex ID: " + message);
}
}
class TorcGraphTransaction extends AbstractTransaction {
private final ConcurrentHashMap<Thread, RAMCloudTransaction> threadLocalRCTXMap = new ConcurrentHashMap<>();
public TorcGraphTransaction() {
super(TorcGraph.this);
}
/**
* This method returns the underlying RAMCloudTransaction object for
* this thread that contains all of the transaction state.
*
* @return RAMCloudTransaction for current thread.
*/
protected RAMCloudTransaction getThreadLocalRAMCloudTx() {
return threadLocalRCTXMap.get(Thread.currentThread());
}
/**
* This method rolls back the transactions of all threads that have not
* closed their transactions themselves. It is meant to be used as a
* final cleanup method to free all transaction state before exiting, in
* the case that threads had executed without performing final cleanup
* themselves before exiting. This currently happens in TinkerPop unit
* tests (3.1.0-incubating). See
* {@link org.apache.tinkerpop.gremlin.structure.TransactionTest#shouldExecuteCompetingThreadsOnMultipleDbInstances}.
* This method is *not* meant to be called while other threads and still
* executing.
*/
private void doRollbackAllThreads() {
threadLocalRCTXMap.forEach((thread, rctx) -> {
try {
rctx.close();
} catch (Exception e) {
logger.error("TorcGraphTransaction.doRollbackAllThreads(): could not close transaction of thread " + thread.getId());
}
logger.debug(String.format("TorcGraphTransaction.doRollbackAllThreads(): %d", thread.getId()));
});
threadLocalRCTXMap.clear();
}
@Override
public void doOpen() {
Thread us = Thread.currentThread();
if (threadLocalRCTXMap.get(us) == null) {
RAMCloud client = threadLocalClientMap.get(us);
threadLocalRCTXMap.put(us, new RAMCloudTransaction(client));
} else {
throw Transaction.Exceptions.transactionAlreadyOpen();
}
logger.debug(String.format("TorcGraphTransaction.doOpen(thread=%d)", us.getId()));
}
@Override
public void doCommit() throws AbstractTransaction.TransactionException {
long startTimeNs = 0;
if (logger.isDebugEnabled()) {
startTimeNs = System.nanoTime();
}
RAMCloudTransaction rctx = threadLocalRCTXMap.get(Thread.currentThread());
try {
if (!rctx.commitAndSync()) {
throw new AbstractTransaction.TransactionException("RAMCloud commitAndSync failed.");
}
} catch (ClientException ex) {
throw new AbstractTransaction.TransactionException(ex);
} finally {
rctx.close();
threadLocalRCTXMap.remove(Thread.currentThread());
}
if (logger.isDebugEnabled()) {
long endTimeNs = System.nanoTime();
logger.debug(String.format("TorcGraphTransaction.doCommit(thread=%d), took %dus", Thread.currentThread().getId(), (endTimeNs - startTimeNs) / 1000l));
}
}
@Override
public void doRollback() throws AbstractTransaction.TransactionException {
long startTimeNs = 0;
if (logger.isDebugEnabled()) {
startTimeNs = System.nanoTime();
}
RAMCloudTransaction rctx = threadLocalRCTXMap.get(Thread.currentThread());
try {
rctx.close();
} catch (Exception e) {
throw new AbstractTransaction.TransactionException(e);
} finally {
threadLocalRCTXMap.remove(Thread.currentThread());
}
if (logger.isDebugEnabled()) {
long endTimeNs = System.nanoTime();
logger.debug(String.format("TorcGraphTransaction.doRollback(thread=%d), took %dus", Thread.currentThread().getId(), (endTimeNs - startTimeNs) / 1000l));
}
}
@Override
public boolean isOpen() {
boolean isOpen = (threadLocalRCTXMap.get(Thread.currentThread()) != null);
logger.debug(String.format("TorcGraphTransaction.isOpen(thread=%d): returning %s", Thread.currentThread().getId(), isOpen));
return isOpen;
}
}
// TODO: Move this to its own file.
public class TorcGraphFeatures implements Features {
private TorcGraphFeatures() {
}
@Override
public Features.GraphFeatures graph() {
return new TorcGraphGraphFeatures();
}
@Override
public Features.VertexFeatures vertex() {
return new TorcGraphVertexFeatures();
}
@Override
public Features.EdgeFeatures edge() {
return new TorcGraphEdgeFeatures();
}
@Override
public String toString() {
return StringFactory.featureString(this);
}
}
public class TorcGraphGraphFeatures implements Features.GraphFeatures {
private TorcGraphGraphFeatures() {
}
@Override
public boolean supportsComputer() {
return false;
}
@Override
public boolean supportsPersistence() {
return true;
}
@Override
public boolean supportsConcurrentAccess() {
return false;
}
@Override
public boolean supportsTransactions() {
return true;
}
@Override
public boolean supportsThreadedTransactions() {
return false;
}
@Override
public Features.VariableFeatures variables() {
return new TorcGraphVariableFeatures() {
};
}
}
public class TorcGraphVertexFeatures implements Features.VertexFeatures {
private TorcGraphVertexFeatures() {
}
@Override
public VertexProperty.Cardinality getCardinality(final String key) {
return VertexProperty.Cardinality.single;
}
@Override
public boolean supportsAddVertices() {
return true;
}
@Override
public boolean supportsRemoveVertices() {
return false;
}
@Override
public boolean supportsMultiProperties() {
return false;
}
@Override
public boolean supportsMetaProperties() {
return false;
}
@Override
public Features.VertexPropertyFeatures properties() {
return new TorcGraphVertexPropertyFeatures();
}
@Override
public boolean supportsAddProperty() {
return true;
}
@Override
public boolean supportsRemoveProperty() {
return true;
}
@Override
public boolean supportsUserSuppliedIds() {
return false;
}
@Override
public boolean supportsNumericIds() {
return false;
}
@Override
public boolean supportsStringIds() {
return false;
}
@Override
public boolean supportsUuidIds() {
return false;
}
@Override
public boolean supportsCustomIds() {
return false;
}
@Override
public boolean supportsAnyIds() {
return false;
}
}
public class TorcGraphEdgeFeatures implements Features.EdgeFeatures {
private TorcGraphEdgeFeatures() {
}
@Override
public boolean supportsAddEdges() {
return true;
}
@Override
public boolean supportsRemoveEdges() {
return false;
}
@Override
public Features.EdgePropertyFeatures properties() {
return new TorcGraphEdgePropertyFeatures() {
};
}
@Override
public boolean supportsAddProperty() {
return false;
}
@Override
public boolean supportsRemoveProperty() {
return false;
}
@Override
public boolean supportsUserSuppliedIds() {
return false;
}
@Override
public boolean supportsNumericIds() {
return false;
}
@Override
public boolean supportsStringIds() {
return false;
}
@Override
public boolean supportsUuidIds() {
return false;
}
@Override
public boolean supportsCustomIds() {
return false;
}
@Override
public boolean supportsAnyIds() {
return false;
}
}
public class TorcGraphVertexPropertyFeatures implements Features.VertexPropertyFeatures {
private TorcGraphVertexPropertyFeatures() {
}
@Override
public boolean supportsAddProperty() {
return false;
}
@Override
public boolean supportsRemoveProperty() {
return false;
}
@Override
public boolean supportsUserSuppliedIds() {
return false;
}
@Override
public boolean supportsNumericIds() {
return false;
}
@Override
public boolean supportsStringIds() {
return false;
}
@Override
public boolean supportsUuidIds() {
return false;
}
@Override
public boolean supportsCustomIds() {
return false;
}
@Override
public boolean supportsAnyIds() {
return false;
}
@Override
public boolean supportsBooleanValues() {
return false;
}
@Override
public boolean supportsByteValues() {
return false;
}
@Override
public boolean supportsDoubleValues() {
return false;
}
@Override
public boolean supportsFloatValues() {
return false;
}
@Override
public boolean supportsIntegerValues() {
return false;
}
@Override
public boolean supportsLongValues() {
return false;
}
@Override
public boolean supportsMapValues() {
return false;
}
@Override
public boolean supportsMixedListValues() {
return false;
}
@Override
public boolean supportsBooleanArrayValues() {
return false;
}
@Override
public boolean supportsByteArrayValues() {
return false;
}
@Override
public boolean supportsDoubleArrayValues() {
return false;
}
@Override
public boolean supportsFloatArrayValues() {
return false;
}
@Override
public boolean supportsIntegerArrayValues() {
return false;
}
@Override
public boolean supportsStringArrayValues() {
return false;
}
@Override
public boolean supportsLongArrayValues() {
return false;
}
@Override
public boolean supportsSerializableValues() {
return false;
}
@Override
public boolean supportsStringValues() {
return true;
}
@Override
public boolean supportsUniformListValues() {
return false;
}
}
public class TorcGraphEdgePropertyFeatures implements Features.EdgePropertyFeatures {
private TorcGraphEdgePropertyFeatures() {
}
@Override
public boolean supportsBooleanValues() {
return false;
}
@Override
public boolean supportsByteValues() {
return false;
}
@Override
public boolean supportsDoubleValues() {
return false;
}
@Override
public boolean supportsFloatValues() {
return false;
}
@Override
public boolean supportsIntegerValues() {
return false;
}
@Override
public boolean supportsLongValues() {
return false;
}
@Override
public boolean supportsMapValues() {
return false;
}
@Override
public boolean supportsMixedListValues() {
return false;
}
@Override
public boolean supportsBooleanArrayValues() {
return false;
}
@Override
public boolean supportsByteArrayValues() {
return false;
}
@Override
public boolean supportsDoubleArrayValues() {
return false;
}
@Override
public boolean supportsFloatArrayValues() {
return false;
}
@Override
public boolean supportsIntegerArrayValues() {
return false;
}
@Override
public boolean supportsStringArrayValues() {
return false;
}
@Override
public boolean supportsLongArrayValues() {
return false;
}
@Override
public boolean supportsSerializableValues() {
return false;
}
@Override
public boolean supportsStringValues() {
return true;
}
@Override
public boolean supportsUniformListValues() {
return false;
}
}
public class TorcGraphVariableFeatures implements Features.VariableFeatures {
private TorcGraphVariableFeatures() {
}
@Override
public boolean supportsBooleanValues() {
return false;
}
@Override
public boolean supportsByteValues() {
return false;
}
@Override
public boolean supportsDoubleValues() {
return false;
}
@Override
public boolean supportsFloatValues() {
return false;
}
@Override
public boolean supportsIntegerValues() {
return false;
}
@Override
public boolean supportsLongValues() {
return false;
}
@Override
public boolean supportsMapValues() {
return false;
}
@Override
public boolean supportsMixedListValues() {
return false;
}
@Override
public boolean supportsBooleanArrayValues() {
return false;
}
@Override
public boolean supportsByteArrayValues() {
return false;
}
@Override
public boolean supportsDoubleArrayValues() {
return false;
}
@Override
public boolean supportsFloatArrayValues() {
return false;
}
@Override
public boolean supportsIntegerArrayValues() {
return false;
}
@Override
public boolean supportsStringArrayValues() {
return false;
}
@Override
public boolean supportsLongArrayValues() {
return false;
}
@Override
public boolean supportsSerializableValues() {
return false;
}
@Override
public boolean supportsStringValues() {
return false;
}
@Override
public boolean supportsUniformListValues() {
return false;
}
}
}
| Improved log messaging for doRollbackAllThreads()
| src/main/java/org/ellitron/tinkerpop/gremlin/torc/structure/TorcGraph.java | Improved log messaging for doRollbackAllThreads() | <ide><path>rc/main/java/org/ellitron/tinkerpop/gremlin/torc/structure/TorcGraph.java
<ide> logger.error("TorcGraphTransaction.doRollbackAllThreads(): could not close transaction of thread " + thread.getId());
<ide> }
<ide>
<del> logger.debug(String.format("TorcGraphTransaction.doRollbackAllThreads(): %d", thread.getId()));
<add> logger.debug(String.format("TorcGraphTransaction.doRollbackAllThreads(): rolling back oustanding transaction of thread %d", thread.getId()));
<ide> });
<ide>
<ide> threadLocalRCTXMap.clear(); |
|
JavaScript | isc | 10ea08b41d829a58eac7dbf62c666dad041dcc34 | 0 | breard-r/chromesoul | //
// Copyright (c) 2012 Rodolphe Breard
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
//
var ContactList = function() {
this.storage = chrome.storage.sync;
this.contacts = {};
this.lst = document.getElementById("contact-lst");
};
ContactList.prototype.insertContact = function(elem) {
var i, nb_el = this.lst.children.length;
for (i = 0; i < nb_el; i++) {
if (this.lst.children[i].children[0].innerHTML > elem.children[0].innerHTML) {
this.lst.insertBefore(elem, this.lst.children[i]);
return ;
}
}
this.lst.appendChild(elem);
};
ContactList.prototype.addContact = function(name) {
var li = null, login = null, close = null;
if (typeof this.contacts[name] === "undefined") {
li = document.createElement("li");
login = document.createElement("span");
close = document.createElement("span");
close.classList.add("remove");
login.innerHTML = name;
close.innerHTML = "x";
li.appendChild(login);
li.appendChild(close);
li.addEventListener("dblclick", function() {
var nel = $cs.ui.addNewTab(name);
$cs.ui.hideAllTabs();
nel.show();
});
close.addEventListener("click", (function(elem) {
return function() {
elem.rmContact(name);
};
})(this));
this.contacts[name] = li;
this.save();
this.insertContact(li);
}
};
ContactList.prototype.rmContact = function(name) {
console.log('removing ' + name + 'from contacts');
for (var i = this.lst.children.length - 1; i >= 0; --i) {
if (this.lst.children[i].children[0].innerHTML === name) {
this.lst.removeChild(this.lst.children[i]);
delete this.contacts[name];
break ;
}
}
};
ContactList.prototype.save = function() {
var i, data = {"contact_list": []};
for (i in this.contacts) {
if (this.contacts.hasOwnProperty(i)) {
data.contact_list.push(i);
}
}
data.contact_list.sort();
this.storage.set(data, function() {});
};
ContactList.prototype.restore = function() {
this.storage.get("contact_list", (function(elem) {
return function(items) {
elem.contacts = {};
elem.lst.innerHTML = "";
if (typeof items.contact_list !== "undefined") {
for (i = items.contact_list.length - 1; i >= 0; --i) {
elem.addContact(items.contact_list[i]);
}
}
};
})(this));
};
ContactList.prototype.init = function() {
var add_btn = document.getElementById("add-contact");
this.restore();
this.save();
add_btn.addEventListener("keyup", function(event) {
if (event.keyCode == 13 && this.value != "") {
$cs.contacts.addContact(this.value);
this.value = "";
}
});
};
| lib/contacts.nsui.js | //
// Copyright (c) 2012 Rodolphe Breard
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
//
var ContactList = function() {
this.storage = chrome.storage.sync;
this.contacts = {};
this.lst = document.getElementById("contact-lst");
};
ContactList.prototype.insertContact = function(elem) {
var i, nb_el = this.lst.children.length;
for (i = 0; i < nb_el; i++) {
if (this.lst.children[i].children[0].innerHTML > elem.children[0].innerHTML) {
this.lst.insertBefore(elem, this.lst.children[i]);
return ;
}
}
this.lst.appendChild(elem);
};
ContactList.prototype.addContact = function(name) {
var li = null, login = null, close = null;
if (typeof this.contacts[name] === "undefined") {
li = document.createElement("li");
login = document.createElement("span");
close = document.createElement("span");
close.classList.add("remove");
login.innerHTML = name;
close.innerHTML = "x";
li.appendChild(login);
li.appendChild(close);
li.addEventListener("dblclick", function() {
var nel = $cs.ui.addNewTab(name);
$cs.ui.hideAllTabs();
nel.show();
});
close.addEventListener("click", (function(elem) {
return function() {
elem.rmContact(name);
};
})(this));
this.contacts[name] = li;
this.save();
this.insertContact(li);
}
};
ContactList.prototype.rmContact = function(name) {
console.log('removing ' + name + 'from contacts');
for (var i = this.lst.children.length - 1; i >= 0; --i) {
if (this.lst.children[i].children[0].innerHTML === name) {
console.log('deleted');
this.lst.removeChild(this.lst.children[i]);
break ;
}
}
};
ContactList.prototype.save = function() {
var i, data = {"contact_list": []};
for (i in this.contacts) {
if (this.contacts.hasOwnProperty(i)) {
data.contact_list.push(i);
}
}
data.contact_list.sort();
this.storage.set(data, function() {});
};
ContactList.prototype.restore = function() {
this.storage.get("contact_list", (function(elem) {
return function(items) {
elem.contacts = {};
elem.lst.innerHTML = "";
if (typeof items.contact_list !== "undefined") {
for (i = items.contact_list.length - 1; i >= 0; --i) {
elem.addContact(items.contact_list[i]);
}
}
};
})(this));
};
ContactList.prototype.init = function() {
var add_btn = document.getElementById("add-contact");
this.restore();
this.save();
add_btn.addEventListener("keyup", function(event) {
if (event.keyCode == 13 && this.value != "") {
$cs.contacts.addContact(this.value);
this.value = "";
}
});
};
| fixing bug which prevents from adding again a previously removed contact
| lib/contacts.nsui.js | fixing bug which prevents from adding again a previously removed contact | <ide><path>ib/contacts.nsui.js
<ide> console.log('removing ' + name + 'from contacts');
<ide> for (var i = this.lst.children.length - 1; i >= 0; --i) {
<ide> if (this.lst.children[i].children[0].innerHTML === name) {
<del> console.log('deleted');
<ide> this.lst.removeChild(this.lst.children[i]);
<add> delete this.contacts[name];
<ide> break ;
<ide> }
<ide> } |
|
Java | apache-2.0 | 85199e2e29d5d161e1a3294e3ef933ebab1f44b6 | 0 | Inari-Soft/inari-firefly | package com.inari.firefly.physics.collision;
import java.util.Iterator;
import com.inari.commons.GeomUtils;
import com.inari.commons.geom.BitMask;
import com.inari.commons.geom.Rectangle;
import com.inari.commons.lang.IntIterator;
import com.inari.commons.lang.aspect.AspectGroup;
import com.inari.commons.lang.aspect.Aspects;
import com.inari.commons.lang.list.DynArray;
import com.inari.commons.lang.list.IntBag;
import com.inari.firefly.FFInitException;
import com.inari.firefly.entity.EntityActivationEvent;
import com.inari.firefly.entity.EntityActivationListener;
import com.inari.firefly.graphics.ETransform;
import com.inari.firefly.graphics.tile.ETile;
import com.inari.firefly.graphics.tile.TileGrid;
import com.inari.firefly.graphics.tile.TileGrid.TileGridIterator;
import com.inari.firefly.graphics.tile.TileGridSystem;
import com.inari.firefly.graphics.view.ViewEvent;
import com.inari.firefly.graphics.view.ViewEvent.Type;
import com.inari.firefly.graphics.view.ViewEventListener;
import com.inari.firefly.physics.movement.EMovement;
import com.inari.firefly.physics.movement.MoveEvent;
import com.inari.firefly.physics.movement.MoveEventListener;
import com.inari.firefly.system.FFContext;
import com.inari.firefly.system.component.ComponentSystem;
import com.inari.firefly.system.component.SystemBuilderAdapter;
import com.inari.firefly.system.component.SystemComponent.SystemComponentKey;
import com.inari.firefly.system.component.SystemComponentBuilder;
public final class CollisionSystem
extends
ComponentSystem<CollisionSystem>
implements
EntityActivationListener,
ViewEventListener,
MoveEventListener {
public static final FFSystemTypeKey<CollisionSystem> SYSTEM_KEY = FFSystemTypeKey.create( CollisionSystem.class );
public static final AspectGroup MATERIAL_ASPECT_GROUP = new AspectGroup( "MATERIAL_ASPECT_GROUP" );
public static final AspectGroup CONTACT_ASPECT_GROUP = new AspectGroup( "CONTACT_ASPECT_GROUP" );
private static final SystemComponentKey<?>[] SUPPORTED_COMPONENT_TYPES = new SystemComponentKey[] {
CollisionQuadTree.TYPE_KEY,
CollisionResolver.TYPE_KEY
};
private final DynArray<ContactPool> contactPools;
private final DynArray<DynArray<ContactPool>> contactPoolsPerViewAndLayer;
private final DynArray<CollisionResolver> collisionResolvers;
private TileGridSystem tileGridSystem;
private final Rectangle checkPivot = new Rectangle( 0, 0, 0, 0 );
// TODO make Event pooling within ContactEvent
private final ContactEvent contactEvent = new ContactEvent();
CollisionSystem() {
super( SYSTEM_KEY );
contactPools = DynArray.create( ContactPool.class, 10, 10 );
contactPoolsPerViewAndLayer = DynArray.createTyped( DynArray.class, 10, 10 );
collisionResolvers = DynArray.create( CollisionResolver.class, 20, 10 );
}
@Override
public final boolean match( Aspects aspects ) {
return aspects.contains( ECollision.TYPE_KEY ) && !aspects.contains( ETile.TYPE_KEY );
}
@Override
public final void init( FFContext context ) {
super.init( context );
context.registerListener( EntityActivationEvent.TYPE_KEY, this );
context.registerListener( ViewEvent.TYPE_KEY, this );
context.registerListener( MoveEvent.TYPE_KEY, this );
tileGridSystem = context.getSystem( TileGridSystem.SYSTEM_KEY );
}
@Override
public final void dispose( FFContext context ) {
clear();
context.disposeListener( EntityActivationEvent.TYPE_KEY, this );
context.disposeListener( ViewEvent.TYPE_KEY, this );
context.disposeListener( MoveEvent.TYPE_KEY, this );
}
@Override
public final void onViewEvent( ViewEvent event ) {
if ( event.isOfType( Type.VIEW_DELETED ) ) {
contactPoolsPerViewAndLayer.remove( event.getView().index() );
return;
}
}
public final void entityActivated( int entityId, final Aspects aspects ) {
final ContactPool pool = getContactPoolForEntity( entityId );
if ( pool != null ) {
pool.add( entityId );
}
}
public final void entityDeactivated( int entityId, final Aspects aspects ) {
final ContactPool pool = getContactPoolForEntity( entityId );
if ( pool != null ) {
pool.remove( entityId );
}
}
@Override
public final void onMoveEvent( final MoveEvent event ) {
final IntBag movedEntityIds = event.movedEntityIds();
final int nullValue = movedEntityIds.getNullValue();
for ( int i = 0; i < movedEntityIds.length(); i++ ) {
final int entityId = movedEntityIds.get( i );
if ( entityId == nullValue ) {
continue;
}
final ECollision collision = context.getEntityComponent( entityId, ECollision.TYPE_KEY );
final ETransform transform = context.getEntityComponent( entityId, ETransform.TYPE_KEY );
final ContactScan contactScan = collision.getContactScan();
final int collisionResolverId = collision.getCollisionResolverId();
scanContacts( entityId, collision );
if ( collisionResolverId >= 0 ) {
collisionResolvers.get( collisionResolverId ).resolve( entityId );
}
if ( contactScan.hasAnyContact() ) {
contactEvent.entityId = entityId;
context.notify( contactEvent );
}
// update the contact pool if there is one for the moved entity
ContactPool contactPool = getContactPool( transform.getViewId(), transform.getLayerId() );
if ( contactPool != null ) {
contactPool.update( entityId );
}
}
}
public final void updateContacts( int entityId ) {
final ECollision collision = context.getEntityComponent( entityId, ECollision.TYPE_KEY );
scanContacts( entityId, collision );
}
private void scanContacts( int entityId, ECollision collision ) {
final Aspects aspects = context.getEntityComponentAspects( entityId );
if ( !aspects.contains( ECollision.TYPE_KEY ) ) {
return;
}
final ETransform transform = context.getEntityComponent( entityId, ETransform.TYPE_KEY );
final EMovement movement = context.getEntityComponent( entityId, EMovement.TYPE_KEY );
final ContactScan contactScan = collision.getContactScan();
contactScan.clearContacts();
contactScan.update(
transform.getXpos(),
transform.getYpos(),
movement.getVelocityX(),
movement.getVelocityY()
);
final int viewId = transform.getViewId();
for ( ContactConstraint constraint : contactScan ) {
int layerId = constraint.layerId;
if ( layerId < 0 ) {
layerId = transform.getLayerId();
}
scanTileContacts( entityId, viewId, layerId, constraint );
scanSpriteContacts( entityId, viewId, layerId, constraint );
}
}
private void scanSpriteContacts( final int entityId, final int viewId, final int layerId, final ContactConstraint constraint ) {
final ContactPool pool = getContactPool( viewId, layerId );
if ( pool == null ) {
return;
}
IntIterator entityIterator = pool.get( constraint.worldBounds );
if ( entityIterator == null || !entityIterator.hasNext() ) {
return;
}
while ( entityIterator.hasNext() ) {
final int entityId2 = entityIterator.next();
if ( entityId == entityId2 ) {
continue;
}
final ETransform transform = context.getEntityComponent( entityId2, ETransform.TYPE_KEY );
scanContact( constraint, entityId2, transform.getXpos(), transform.getYpos() );
}
}
private final void scanTileContacts( final int entityId, final int viewId, final int layerId, final ContactConstraint constraint ) {
TileGrid tileGrid = tileGridSystem.getTileGrid( viewId, layerId );
if ( tileGrid == null ) {
return;
}
TileGridIterator tileGridIterator = tileGrid.getTileGridIterator( constraint.worldBounds );
while ( tileGridIterator.hasNext() ) {
final int entityId2 = tileGridIterator.next();
if ( entityId == entityId2 ) {
continue;
}
scanContact( constraint, entityId2, tileGridIterator.getWorldXPos(), tileGridIterator.getWorldYPos() );
}
}
private void scanContact( final ContactConstraint constraint, final int entityId, final float xpos, final float ypos ) {
if ( entityId < 0 || !context.getEntityComponentAspects( entityId ).contains( ECollision.TYPE_KEY ) ) {
return;
}
final ECollision collision = context.getEntityComponent( entityId, ECollision.TYPE_KEY );
if ( !constraint.match( collision ) ) {
return;
}
final Rectangle collisionBounds = collision.getCollisionBounds();
final Contact contact = Contact.createContact(
entityId,
collision.getMaterialType(),
collision.getContactType(),
(int) Math.floor( xpos ) + collisionBounds.x,
(int) Math.floor( ypos ) + collisionBounds.y,
collisionBounds.width,
collisionBounds.height
);
final Rectangle constraintWorldBounds = constraint.worldBounds;
final Rectangle contactWorldBounds = contact.worldBounds();
final Rectangle intersectionBounds = contact.intersectionBounds();
final BitMask intersectionMask = contact.intersectionMask();
GeomUtils.intersection(
constraintWorldBounds,
contactWorldBounds,
intersectionBounds
);
if ( intersectionBounds.area() <= 0 ) {
contact.dispose();
return;
}
// normalize the intersection to origin of coordinate system
intersectionBounds.x = intersectionBounds.x - constraintWorldBounds.x;
intersectionBounds.y = intersectionBounds.y - constraintWorldBounds.y;
final BitMask bitmask2 = collision.getCollisionMask();
if ( bitmask2 == null ) {
constraint.addContact( contact );
return;
}
checkPivot.x = constraintWorldBounds.x - contactWorldBounds.x;
checkPivot.y = constraintWorldBounds.y - contactWorldBounds.y;
checkPivot.width = constraintWorldBounds.width;
checkPivot.height = constraintWorldBounds.height;
if ( bitmask2 != null && BitMask.createIntersectionMask( checkPivot, bitmask2, intersectionMask, true ) ) {
constraint.addContact( contact );
return;
}
contact.dispose();
}
public final ContactPool getContactPool( int id ) {
return contactPools.get( id );
}
public final ContactPool getContactPool( String name ) {
for ( int i = 0; i < contactPools.capacity(); i++ ) {
final ContactPool contactPool = contactPools.get( i );
if ( contactPool == null ) {
continue;
}
if ( name.equals( contactPool.getName() ) ) {
return contactPool;
}
}
return null;
}
public final int getContactPoolId( String name ) {
for ( int i = 0; i < contactPools.capacity(); i++ ) {
final ContactPool contactPool = contactPools.get( i );
if ( contactPool == null ) {
continue;
}
if ( name.equals( contactPool.getName() ) ) {
return contactPool.index();
}
}
return -1;
}
public final ContactPool getContactPool( int viewId, int layerId ) {
if ( !contactPoolsPerViewAndLayer.contains( viewId ) ) {
return null;
}
final DynArray<ContactPool> ofLayer = contactPoolsPerViewAndLayer.get( viewId );
if ( !ofLayer.contains( layerId ) ) {
return null;
}
return ofLayer.get( layerId );
}
public final ContactPool getContactPoolForEntity( int entityId ) {
final ETransform transform = context.getEntityComponent( entityId, ETransform.TYPE_KEY );
int viewId = transform.getViewId();
int layerId = transform.getLayerId();
if ( !contactPoolsPerViewAndLayer.contains( viewId ) ) {
return null;
}
DynArray<ContactPool> poolsPerView = contactPoolsPerViewAndLayer.get( viewId );
if ( !poolsPerView.contains( layerId ) ) {
return null;
}
ContactPool quadTree = poolsPerView.get( layerId );
if ( quadTree == null ) {
return null;
}
return quadTree;
}
public final void deleteContactPool( int id ) {
ContactPool pool = getContactPool( id );
if ( pool == null ) {
return;
}
disposeContactPool( contactPools.remove( pool.index() ) );
contactPoolsPerViewAndLayer.get( pool.getViewId() ).remove( pool.getLayerId() );
}
public final void deleteContactPool( String name ) {
ContactPool pool = getContactPool( name );
if ( pool == null ) {
return;
}
disposeContactPool( contactPools.remove( pool.index() ) );
contactPoolsPerViewAndLayer.get( pool.getViewId() ).remove( pool.getLayerId() );
}
private final void disposeContactPool( ContactPool contactPool ) {
if ( contactPool != null ) {
contactPool.dispose();
}
}
public final CollisionResolver getCollisionResolver( int id ) {
if ( collisionResolvers.contains( id ) ) {
return collisionResolvers.get( id );
}
return null;
}
public final CollisionResolver getCollisionResolver( String name ) {
for ( CollisionResolver cr : collisionResolvers ) {
if ( name.equals( cr.getName() ) ) {
return cr;
}
}
return null;
}
public final int getCollisionResolverId( String name ) {
for ( CollisionResolver cr : collisionResolvers ) {
if ( name.equals( cr.getName() ) ) {
return cr.index();
}
}
return -1;
}
public final void deleteCollisionResolver( String name ) {
CollisionResolver cr = getCollisionResolver( name );
if ( cr == null ) {
return;
}
deleteCollisionResolver( cr.index() );
}
public final void deleteCollisionResolver( int id ) {
disposeCollisionConstraint( collisionResolvers.remove( id ) );
}
private void disposeCollisionConstraint( CollisionResolver cr ) {
if ( cr != null ) {
cr.dispose();
}
}
@Override
public final SystemComponentKey<?>[] supportedComponentTypes() {
return SUPPORTED_COMPONENT_TYPES;
}
@Override
public final SystemBuilderAdapter<?>[] getSupportedBuilderAdapter() {
return new SystemBuilderAdapter<?>[] {
new ContactPoolBuilderAdapter(),
new CollisionResolverBuilderAdapter()
};
}
public final SystemComponentBuilder getContactPoolBuilder( Class<? extends ContactPool> componentType ) {
return new ContactPoolBuilder( componentType );
}
public final SystemComponentBuilder getCollisionResolverBuilder( Class<? extends CollisionResolver> componentType ) {
if ( componentType == null ) {
throw new IllegalArgumentException( "componentType is needed for SystemComponentBuilder for component: " + CollisionResolver.TYPE_KEY.name() );
}
return new CollisionResolverBuilder( componentType );
}
@Override
public final void clear() {
for ( ContactPool pool : contactPools ) {
disposeContactPool( pool );
}
for ( CollisionResolver cr : collisionResolvers ) {
disposeCollisionConstraint( cr );
}
contactPools.clear();
contactPoolsPerViewAndLayer.clear();
collisionResolvers.clear();
}
private final class ContactPoolBuilder extends SystemComponentBuilder {
private ContactPoolBuilder( Class<? extends ContactPool> componentType ) {
super( context, componentType );
}
@Override
public final SystemComponentKey<ContactPool> systemComponentKey() {
return ContactPool.TYPE_KEY;
}
public final int doBuild( int componentId, Class<?> componentType, boolean activate ) {
ContactPool pool = createSystemComponent( componentId, componentType, context );
int viewId = pool.getViewId();
int layerId = pool.getLayerId();
if ( viewId < 0 ) {
throw new FFInitException( "ViewId is mandatory for CollisionQuadTree" );
}
if ( layerId < 0 ) {
throw new FFInitException( "LayerId is mandatory for CollisionQuadTree" );
}
if ( !contactPoolsPerViewAndLayer.contains( viewId ) ) {
contactPoolsPerViewAndLayer.set( viewId, DynArray.create( ContactPool.class, 20, 10 ) );
}
contactPools.set( pool.index(), pool );
contactPoolsPerViewAndLayer
.get( viewId )
.set( layerId, pool );
return pool.index();
}
}
private final class CollisionResolverBuilder extends SystemComponentBuilder {
private CollisionResolverBuilder( Class<? extends CollisionResolver> componentType ) {
super( context, componentType );
}
@Override
public final SystemComponentKey<CollisionResolver> systemComponentKey() {
return CollisionResolver.TYPE_KEY;
}
public final int doBuild( int componentId, Class<?> componentType, boolean activate ) {
CollisionResolver cr = createSystemComponent( componentId, componentType, context );
collisionResolvers.set( cr.index(), cr );
return cr.index();
}
}
private final class ContactPoolBuilderAdapter extends SystemBuilderAdapter<ContactPool> {
private ContactPoolBuilderAdapter() {
super( CollisionSystem.this, ContactPool.TYPE_KEY );
}
@Override
public final ContactPool get( int id ) {
return getContactPool( id );
}
@Override
public final Iterator<ContactPool> getAll() {
return contactPools.iterator();
}
@Override
public final void delete( int id ) {
deleteContactPool( id );
}
@Override
public final int getId( String name ) {
return getContactPoolId( name );
}
@Override
public final void activate( int id ) {
throw new UnsupportedOperationException( componentTypeKey() + " is not activable" );
}
@Override
public final void deactivate( int id ) {
throw new UnsupportedOperationException( componentTypeKey() + " is not activable" );
}
@Override
public final SystemComponentBuilder createComponentBuilder( Class<? extends ContactPool> componentType ) {
return new ContactPoolBuilder( componentType );
}
}
private final class CollisionResolverBuilderAdapter extends SystemBuilderAdapter<CollisionResolver> {
private CollisionResolverBuilderAdapter() {
super( CollisionSystem.this, CollisionResolver.TYPE_KEY );
}
@Override
public final CollisionResolver get( int id ) {
return getCollisionResolver( id );
}
@Override
public final Iterator<CollisionResolver> getAll() {
return collisionResolvers.iterator();
}
@Override
public final void delete( int id ) {
deleteCollisionResolver( id );
}
@Override
public final int getId( String name ) {
return getCollisionResolverId( name );
}
@Override
public final void activate( int id ) {
throw new UnsupportedOperationException( componentTypeKey() + " is not activable" );
}
@Override
public final void deactivate( int id ) {
throw new UnsupportedOperationException( componentTypeKey() + " is not activable" );
}
@Override
public final SystemComponentBuilder createComponentBuilder( Class<? extends CollisionResolver> componentType ) {
return getCollisionResolverBuilder( componentType );
}
}
}
| src/main/java/com/inari/firefly/physics/collision/CollisionSystem.java | package com.inari.firefly.physics.collision;
import java.util.Iterator;
import com.inari.commons.GeomUtils;
import com.inari.commons.geom.BitMask;
import com.inari.commons.geom.Rectangle;
import com.inari.commons.lang.IntIterator;
import com.inari.commons.lang.aspect.AspectGroup;
import com.inari.commons.lang.aspect.Aspects;
import com.inari.commons.lang.list.DynArray;
import com.inari.commons.lang.list.IntBag;
import com.inari.firefly.FFInitException;
import com.inari.firefly.entity.EntityActivationEvent;
import com.inari.firefly.entity.EntityActivationListener;
import com.inari.firefly.graphics.ETransform;
import com.inari.firefly.graphics.tile.ETile;
import com.inari.firefly.graphics.tile.TileGrid;
import com.inari.firefly.graphics.tile.TileGrid.TileGridIterator;
import com.inari.firefly.graphics.tile.TileGridSystem;
import com.inari.firefly.graphics.view.ViewEvent;
import com.inari.firefly.graphics.view.ViewEvent.Type;
import com.inari.firefly.graphics.view.ViewEventListener;
import com.inari.firefly.physics.movement.EMovement;
import com.inari.firefly.physics.movement.MoveEvent;
import com.inari.firefly.physics.movement.MoveEventListener;
import com.inari.firefly.system.FFContext;
import com.inari.firefly.system.component.ComponentSystem;
import com.inari.firefly.system.component.SystemBuilderAdapter;
import com.inari.firefly.system.component.SystemComponent.SystemComponentKey;
import com.inari.firefly.system.component.SystemComponentBuilder;
public final class CollisionSystem
extends
ComponentSystem<CollisionSystem>
implements
EntityActivationListener,
ViewEventListener,
MoveEventListener {
public static final FFSystemTypeKey<CollisionSystem> SYSTEM_KEY = FFSystemTypeKey.create( CollisionSystem.class );
public static final AspectGroup MATERIAL_ASPECT_GROUP = new AspectGroup( "MATERIAL_ASPECT_GROUP" );
public static final AspectGroup CONTACT_ASPECT_GROUP = new AspectGroup( "CONTACT_ASPECT_GROUP" );
private static final SystemComponentKey<?>[] SUPPORTED_COMPONENT_TYPES = new SystemComponentKey[] {
CollisionQuadTree.TYPE_KEY,
CollisionResolver.TYPE_KEY
};
private final DynArray<ContactPool> contactPools;
private final DynArray<DynArray<ContactPool>> contactPoolsPerViewAndLayer;
private final DynArray<CollisionResolver> collisionResolvers;
private TileGridSystem tileGridSystem;
private final Rectangle checkPivot = new Rectangle( 0, 0, 0, 0 );
// TODO make Event pooling within ContactEvent
private final ContactEvent contactEvent = new ContactEvent();
CollisionSystem() {
super( SYSTEM_KEY );
contactPools = DynArray.create( ContactPool.class, 10, 10 );
contactPoolsPerViewAndLayer = DynArray.createTyped( DynArray.class, 10, 10 );
collisionResolvers = DynArray.create( CollisionResolver.class, 20, 10 );
}
@Override
public final boolean match( Aspects aspects ) {
return aspects.contains( ECollision.TYPE_KEY ) && !aspects.contains( ETile.TYPE_KEY );
}
@Override
public final void init( FFContext context ) {
super.init( context );
context.registerListener( EntityActivationEvent.TYPE_KEY, this );
context.registerListener( ViewEvent.TYPE_KEY, this );
context.registerListener( MoveEvent.TYPE_KEY, this );
tileGridSystem = context.getSystem( TileGridSystem.SYSTEM_KEY );
}
@Override
public final void dispose( FFContext context ) {
clear();
context.disposeListener( EntityActivationEvent.TYPE_KEY, this );
context.disposeListener( ViewEvent.TYPE_KEY, this );
context.disposeListener( MoveEvent.TYPE_KEY, this );
}
@Override
public final void onViewEvent( ViewEvent event ) {
if ( event.isOfType( Type.VIEW_DELETED ) ) {
contactPoolsPerViewAndLayer.remove( event.getView().index() );
return;
}
}
public final void entityActivated( int entityId, final Aspects aspects ) {
final ContactPool pool = getContactPoolForEntity( entityId );
if ( pool != null ) {
pool.add( entityId );
}
}
public final void entityDeactivated( int entityId, final Aspects aspects ) {
final ContactPool pool = getContactPoolForEntity( entityId );
if ( pool != null ) {
pool.remove( entityId );
}
}
@Override
public final void onMoveEvent( final MoveEvent event ) {
final IntBag movedEntityIds = event.movedEntityIds();
final int nullValue = movedEntityIds.getNullValue();
for ( int i = 0; i < movedEntityIds.length(); i++ ) {
final int entityId = movedEntityIds.get( i );
if ( entityId == nullValue ) {
continue;
}
final ECollision collision = context.getEntityComponent( entityId, ECollision.TYPE_KEY );
final ContactScan contactScan = collision.getContactScan();
final int collisionResolverId = collision.getCollisionResolverId();
scanContacts( entityId, collision );
if ( collisionResolverId >= 0 ) {
collisionResolvers.get( collisionResolverId ).resolve( entityId );
}
if ( contactScan.hasAnyContact() ) {
contactEvent.entityId = entityId;
context.notify( contactEvent );
}
}
}
public final void updateContacts( int entityId ) {
final ECollision collision = context.getEntityComponent( entityId, ECollision.TYPE_KEY );
scanContacts( entityId, collision );
}
private void scanContacts( int entityId, ECollision collision ) {
final Aspects aspects = context.getEntityComponentAspects( entityId );
if ( !aspects.contains( ECollision.TYPE_KEY ) ) {
return;
}
final ETransform transform = context.getEntityComponent( entityId, ETransform.TYPE_KEY );
final EMovement movement = context.getEntityComponent( entityId, EMovement.TYPE_KEY );
final ContactScan contactScan = collision.getContactScan();
contactScan.clearContacts();
contactScan.update(
transform.getXpos(),
transform.getYpos(),
movement.getVelocityX(),
movement.getVelocityY()
);
final int viewId = transform.getViewId();
for ( ContactConstraint constraint : contactScan ) {
int layerId = constraint.layerId;
if ( layerId < 0 ) {
layerId = transform.getLayerId();
}
scanTileContacts( entityId, viewId, layerId, constraint );
scanSpriteContacts( entityId, viewId, layerId, constraint );
}
}
private void scanSpriteContacts( final int entityId, final int viewId, final int layerId, final ContactConstraint constraint ) {
final ContactPool pool = getContactPool( viewId, layerId );
if ( pool == null ) {
return;
}
IntIterator entityIterator = pool.get( constraint.worldBounds );
if ( entityIterator == null || !entityIterator.hasNext() ) {
return;
}
while ( entityIterator.hasNext() ) {
final int entityId2 = entityIterator.next();
if ( entityId == entityId2 ) {
continue;
}
final ETransform transform = context.getEntityComponent( entityId2, ETransform.TYPE_KEY );
scanContact( constraint, entityId2, transform.getXpos(), transform.getYpos() );
}
}
private final void scanTileContacts( final int entityId, final int viewId, final int layerId, final ContactConstraint constraint ) {
TileGrid tileGrid = tileGridSystem.getTileGrid( viewId, layerId );
if ( tileGrid == null ) {
return;
}
TileGridIterator tileGridIterator = tileGrid.getTileGridIterator( constraint.worldBounds );
while ( tileGridIterator.hasNext() ) {
final int entityId2 = tileGridIterator.next();
if ( entityId == entityId2 ) {
continue;
}
scanContact( constraint, entityId2, tileGridIterator.getWorldXPos(), tileGridIterator.getWorldYPos() );
}
}
private void scanContact( final ContactConstraint constraint, final int entityId, final float xpos, final float ypos ) {
if ( entityId < 0 || !context.getEntityComponentAspects( entityId ).contains( ECollision.TYPE_KEY ) ) {
return;
}
final ECollision collision = context.getEntityComponent( entityId, ECollision.TYPE_KEY );
if ( !constraint.match( collision ) ) {
return;
}
final Rectangle collisionBounds = collision.getCollisionBounds();
final Contact contact = Contact.createContact(
entityId,
collision.getMaterialType(),
collision.getContactType(),
(int) Math.floor( xpos ) + collisionBounds.x,
(int) Math.floor( ypos ) + collisionBounds.y,
collisionBounds.width,
collisionBounds.height
);
final Rectangle constraintWorldBounds = constraint.worldBounds;
final Rectangle contactWorldBounds = contact.worldBounds();
final Rectangle intersectionBounds = contact.intersectionBounds();
final BitMask intersectionMask = contact.intersectionMask();
GeomUtils.intersection(
constraintWorldBounds,
contactWorldBounds,
intersectionBounds
);
if ( intersectionBounds.area() <= 0 ) {
contact.dispose();
return;
}
// normalize the intersection to origin of coordinate system
intersectionBounds.x = intersectionBounds.x - constraintWorldBounds.x;
intersectionBounds.y = intersectionBounds.y - constraintWorldBounds.y;
final BitMask bitmask2 = collision.getCollisionMask();
if ( bitmask2 == null ) {
constraint.addContact( contact );
return;
}
checkPivot.x = constraintWorldBounds.x - contactWorldBounds.x;
checkPivot.y = constraintWorldBounds.y - contactWorldBounds.y;
checkPivot.width = constraintWorldBounds.width;
checkPivot.height = constraintWorldBounds.height;
if ( bitmask2 != null && BitMask.createIntersectionMask( checkPivot, bitmask2, intersectionMask, true ) ) {
constraint.addContact( contact );
return;
}
contact.dispose();
}
public final ContactPool getContactPool( int id ) {
return contactPools.get( id );
}
public final ContactPool getContactPool( String name ) {
for ( int i = 0; i < contactPools.capacity(); i++ ) {
final ContactPool contactPool = contactPools.get( i );
if ( contactPool == null ) {
continue;
}
if ( name.equals( contactPool.getName() ) ) {
return contactPool;
}
}
return null;
}
public final int getContactPoolId( String name ) {
for ( int i = 0; i < contactPools.capacity(); i++ ) {
final ContactPool contactPool = contactPools.get( i );
if ( contactPool == null ) {
continue;
}
if ( name.equals( contactPool.getName() ) ) {
return contactPool.index();
}
}
return -1;
}
public final ContactPool getContactPool( int viewId, int layerId ) {
if ( !contactPoolsPerViewAndLayer.contains( viewId ) ) {
return null;
}
final DynArray<ContactPool> ofLayer = contactPoolsPerViewAndLayer.get( viewId );
if ( !ofLayer.contains( layerId ) ) {
return null;
}
return ofLayer.get( layerId );
}
public final ContactPool getContactPoolForEntity( int entityId ) {
final ETransform transform = context.getEntityComponent( entityId, ETransform.TYPE_KEY );
int viewId = transform.getViewId();
int layerId = transform.getLayerId();
if ( !contactPoolsPerViewAndLayer.contains( viewId ) ) {
return null;
}
DynArray<ContactPool> poolsPerView = contactPoolsPerViewAndLayer.get( viewId );
if ( !poolsPerView.contains( layerId ) ) {
return null;
}
ContactPool quadTree = poolsPerView.get( layerId );
if ( quadTree == null ) {
return null;
}
return quadTree;
}
public final void deleteContactPool( int id ) {
ContactPool pool = getContactPool( id );
if ( pool == null ) {
return;
}
disposeContactPool( contactPools.remove( pool.index() ) );
contactPoolsPerViewAndLayer.get( pool.getViewId() ).remove( pool.getLayerId() );
}
public final void deleteContactPool( String name ) {
ContactPool pool = getContactPool( name );
if ( pool == null ) {
return;
}
disposeContactPool( contactPools.remove( pool.index() ) );
contactPoolsPerViewAndLayer.get( pool.getViewId() ).remove( pool.getLayerId() );
}
private final void disposeContactPool( ContactPool contactPool ) {
if ( contactPool != null ) {
contactPool.dispose();
}
}
public final CollisionResolver getCollisionResolver( int id ) {
if ( collisionResolvers.contains( id ) ) {
return collisionResolvers.get( id );
}
return null;
}
public final CollisionResolver getCollisionResolver( String name ) {
for ( CollisionResolver cr : collisionResolvers ) {
if ( name.equals( cr.getName() ) ) {
return cr;
}
}
return null;
}
public final int getCollisionResolverId( String name ) {
for ( CollisionResolver cr : collisionResolvers ) {
if ( name.equals( cr.getName() ) ) {
return cr.index();
}
}
return -1;
}
public final void deleteCollisionResolver( String name ) {
CollisionResolver cr = getCollisionResolver( name );
if ( cr == null ) {
return;
}
deleteCollisionResolver( cr.index() );
}
public final void deleteCollisionResolver( int id ) {
disposeCollisionConstraint( collisionResolvers.remove( id ) );
}
private void disposeCollisionConstraint( CollisionResolver cr ) {
if ( cr != null ) {
cr.dispose();
}
}
@Override
public final SystemComponentKey<?>[] supportedComponentTypes() {
return SUPPORTED_COMPONENT_TYPES;
}
@Override
public final SystemBuilderAdapter<?>[] getSupportedBuilderAdapter() {
return new SystemBuilderAdapter<?>[] {
new ContactPoolBuilderAdapter(),
new CollisionResolverBuilderAdapter()
};
}
public final SystemComponentBuilder getContactPoolBuilder( Class<? extends ContactPool> componentType ) {
return new ContactPoolBuilder( componentType );
}
public final SystemComponentBuilder getCollisionResolverBuilder( Class<? extends CollisionResolver> componentType ) {
if ( componentType == null ) {
throw new IllegalArgumentException( "componentType is needed for SystemComponentBuilder for component: " + CollisionResolver.TYPE_KEY.name() );
}
return new CollisionResolverBuilder( componentType );
}
@Override
public final void clear() {
for ( ContactPool pool : contactPools ) {
disposeContactPool( pool );
}
for ( CollisionResolver cr : collisionResolvers ) {
disposeCollisionConstraint( cr );
}
contactPools.clear();
contactPoolsPerViewAndLayer.clear();
collisionResolvers.clear();
}
private final class ContactPoolBuilder extends SystemComponentBuilder {
private ContactPoolBuilder( Class<? extends ContactPool> componentType ) {
super( context, componentType );
}
@Override
public final SystemComponentKey<ContactPool> systemComponentKey() {
return ContactPool.TYPE_KEY;
}
public final int doBuild( int componentId, Class<?> componentType, boolean activate ) {
ContactPool pool = createSystemComponent( componentId, componentType, context );
int viewId = pool.getViewId();
int layerId = pool.getLayerId();
if ( viewId < 0 ) {
throw new FFInitException( "ViewId is mandatory for CollisionQuadTree" );
}
if ( layerId < 0 ) {
throw new FFInitException( "LayerId is mandatory for CollisionQuadTree" );
}
if ( !contactPoolsPerViewAndLayer.contains( viewId ) ) {
contactPoolsPerViewAndLayer.set( viewId, DynArray.create( ContactPool.class, 20, 10 ) );
}
contactPools.set( pool.index(), pool );
contactPoolsPerViewAndLayer
.get( viewId )
.set( layerId, pool );
return pool.index();
}
}
private final class CollisionResolverBuilder extends SystemComponentBuilder {
private CollisionResolverBuilder( Class<? extends CollisionResolver> componentType ) {
super( context, componentType );
}
@Override
public final SystemComponentKey<CollisionResolver> systemComponentKey() {
return CollisionResolver.TYPE_KEY;
}
public final int doBuild( int componentId, Class<?> componentType, boolean activate ) {
CollisionResolver cr = createSystemComponent( componentId, componentType, context );
collisionResolvers.set( cr.index(), cr );
return cr.index();
}
}
private final class ContactPoolBuilderAdapter extends SystemBuilderAdapter<ContactPool> {
private ContactPoolBuilderAdapter() {
super( CollisionSystem.this, ContactPool.TYPE_KEY );
}
@Override
public final ContactPool get( int id ) {
return getContactPool( id );
}
@Override
public final Iterator<ContactPool> getAll() {
return contactPools.iterator();
}
@Override
public final void delete( int id ) {
deleteContactPool( id );
}
@Override
public final int getId( String name ) {
return getContactPoolId( name );
}
@Override
public final void activate( int id ) {
throw new UnsupportedOperationException( componentTypeKey() + " is not activable" );
}
@Override
public final void deactivate( int id ) {
throw new UnsupportedOperationException( componentTypeKey() + " is not activable" );
}
@Override
public final SystemComponentBuilder createComponentBuilder( Class<? extends ContactPool> componentType ) {
return new ContactPoolBuilder( componentType );
}
}
private final class CollisionResolverBuilderAdapter extends SystemBuilderAdapter<CollisionResolver> {
private CollisionResolverBuilderAdapter() {
super( CollisionSystem.this, CollisionResolver.TYPE_KEY );
}
@Override
public final CollisionResolver get( int id ) {
return getCollisionResolver( id );
}
@Override
public final Iterator<CollisionResolver> getAll() {
return collisionResolvers.iterator();
}
@Override
public final void delete( int id ) {
deleteCollisionResolver( id );
}
@Override
public final int getId( String name ) {
return getCollisionResolverId( name );
}
@Override
public final void activate( int id ) {
throw new UnsupportedOperationException( componentTypeKey() + " is not activable" );
}
@Override
public final void deactivate( int id ) {
throw new UnsupportedOperationException( componentTypeKey() + " is not activable" );
}
@Override
public final SystemComponentBuilder createComponentBuilder( Class<? extends CollisionResolver> componentType ) {
return getCollisionResolverBuilder( componentType );
}
}
}
| added the update of ContactPool on moving entity event | src/main/java/com/inari/firefly/physics/collision/CollisionSystem.java | added the update of ContactPool on moving entity event | <ide><path>rc/main/java/com/inari/firefly/physics/collision/CollisionSystem.java
<ide> }
<ide>
<ide> final ECollision collision = context.getEntityComponent( entityId, ECollision.TYPE_KEY );
<add> final ETransform transform = context.getEntityComponent( entityId, ETransform.TYPE_KEY );
<ide> final ContactScan contactScan = collision.getContactScan();
<ide> final int collisionResolverId = collision.getCollisionResolverId();
<ide>
<ide> if ( contactScan.hasAnyContact() ) {
<ide> contactEvent.entityId = entityId;
<ide> context.notify( contactEvent );
<add> }
<add>
<add> // update the contact pool if there is one for the moved entity
<add> ContactPool contactPool = getContactPool( transform.getViewId(), transform.getLayerId() );
<add> if ( contactPool != null ) {
<add> contactPool.update( entityId );
<ide> }
<ide> }
<ide> } |
|
Java | apache-2.0 | 6f1e47743891c52a71f606abbb38447dbc0cb94b | 0 | francescomari/jackrabbit-oak,francescomari/jackrabbit-oak,stillalex/jackrabbit-oak,alexkli/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,alexparvulescu/jackrabbit-oak,alexkli/jackrabbit-oak,stillalex/jackrabbit-oak,anchela/jackrabbit-oak,francescomari/jackrabbit-oak,catholicon/jackrabbit-oak,stillalex/jackrabbit-oak,stillalex/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,alexkli/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,alexkli/jackrabbit-oak,anchela/jackrabbit-oak,anchela/jackrabbit-oak,alexparvulescu/jackrabbit-oak,francescomari/jackrabbit-oak,alexparvulescu/jackrabbit-oak,alexparvulescu/jackrabbit-oak,catholicon/jackrabbit-oak,alexparvulescu/jackrabbit-oak,anchela/jackrabbit-oak,francescomari/jackrabbit-oak,catholicon/jackrabbit-oak,anchela/jackrabbit-oak,alexkli/jackrabbit-oak,stillalex/jackrabbit-oak,catholicon/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,catholicon/jackrabbit-oak | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.jackrabbit.oak.plugins.index.lucene.property;
import java.util.HashSet;
import java.util.Set;
import javax.annotation.Nullable;
import javax.jcr.PropertyType;
import org.apache.jackrabbit.oak.api.CommitFailedException;
import org.apache.jackrabbit.oak.api.PropertyState;
import org.apache.jackrabbit.oak.plugins.index.lucene.PropertyDefinition;
import org.apache.jackrabbit.oak.plugins.index.lucene.PropertyUpdateCallback;
import org.apache.jackrabbit.oak.plugins.index.property.ValuePattern;
import org.apache.jackrabbit.oak.plugins.index.property.strategy.ContentMirrorStoreStrategy;
import org.apache.jackrabbit.oak.plugins.index.property.strategy.UniqueEntryStoreStrategy;
import org.apache.jackrabbit.oak.plugins.memory.PropertyValues;
import org.apache.jackrabbit.oak.spi.state.NodeBuilder;
import org.apache.jackrabbit.oak.stats.Clock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Suppliers.ofInstance;
import static com.google.common.collect.Sets.newHashSet;
import static java.util.Collections.emptySet;
import static org.apache.jackrabbit.oak.plugins.index.IndexConstants.INDEX_CONTENT_NODE_NAME;
import static org.apache.jackrabbit.oak.plugins.index.lucene.property.HybridPropertyIndexUtil.PROPERTY_INDEX;
import static org.apache.jackrabbit.oak.plugins.index.lucene.property.HybridPropertyIndexUtil.PROP_CREATED;
import static org.apache.jackrabbit.oak.plugins.index.lucene.property.HybridPropertyIndexUtil.PROP_HEAD_BUCKET;
import static org.apache.jackrabbit.oak.plugins.index.lucene.property.HybridPropertyIndexUtil.PROP_STORAGE_TYPE;
import static org.apache.jackrabbit.oak.plugins.index.lucene.property.HybridPropertyIndexUtil.STORAGE_TYPE_CONTENT_MIRROR;
import static org.apache.jackrabbit.oak.plugins.index.lucene.property.HybridPropertyIndexUtil.STORAGE_TYPE_UNIQUE;
import static org.apache.jackrabbit.oak.plugins.index.property.PropertyIndexUtil.encode;
public class PropertyIndexUpdateCallback implements PropertyUpdateCallback {
private static final Logger log = LoggerFactory.getLogger(PropertyIndexUpdateCallback.class);
private static final String DEFAULT_HEAD_BUCKET = String.valueOf(1);
private final NodeBuilder builder;
private final String indexPath;
private final UniquenessConstraintValidator uniquenessConstraintValidator;
private final long updateTime;
public PropertyIndexUpdateCallback(String indexPath, NodeBuilder builder) {
this(indexPath, builder, Clock.SIMPLE);
}
public PropertyIndexUpdateCallback(String indexPath, NodeBuilder builder, Clock clock) {
this.builder = builder;
this.indexPath = indexPath;
this.updateTime = clock.getTime();
this.uniquenessConstraintValidator = new UniquenessConstraintValidator(indexPath, builder);
}
@Override
public void propertyUpdated(String nodePath, String propertyRelativePath, PropertyDefinition pd,
@Nullable PropertyState before, @Nullable PropertyState after) {
if (!pd.sync) {
return;
}
Set<String> beforeKeys = getValueKeys(before, pd.valuePattern);
Set<String> afterKeys = getValueKeys(after, pd.valuePattern);
//Remove duplicates
Set<String> sharedKeys = newHashSet(beforeKeys);
sharedKeys.retainAll(afterKeys);
beforeKeys.removeAll(sharedKeys);
afterKeys.removeAll(sharedKeys);
if (!beforeKeys.isEmpty() || !afterKeys.isEmpty()){
NodeBuilder indexNode = getIndexNode(propertyRelativePath, pd.unique);
if (pd.unique) {
UniqueEntryStoreStrategy s = new UniqueEntryStoreStrategy(INDEX_CONTENT_NODE_NAME,
(nb) -> nb.setProperty(PROP_CREATED, updateTime));
s.update(ofInstance(indexNode),
nodePath,
null,
null,
beforeKeys,
afterKeys);
uniquenessConstraintValidator.add(propertyRelativePath, afterKeys);
} else {
ContentMirrorStoreStrategy s = new ContentMirrorStoreStrategy();
s.update(ofInstance(indexNode),
nodePath,
null,
null,
emptySet(), //Disable pruning with empty before keys
afterKeys);
}
if (log.isTraceEnabled()) {
log.trace("[{}] Property index updated for [{}/@{}] with values {}", indexPath, nodePath,
propertyRelativePath, afterKeys);
}
}
}
@Override
public void done() throws CommitFailedException {
uniquenessConstraintValidator.validate();
}
public UniquenessConstraintValidator getUniquenessConstraintValidator() {
return uniquenessConstraintValidator;
}
private NodeBuilder getIndexNode(String propertyRelativePath, boolean unique) {
NodeBuilder propertyIndex = builder.child(PROPERTY_INDEX);
String nodeName = HybridPropertyIndexUtil.getNodeName(propertyRelativePath);
if (unique) {
return getUniqueIndexBuilder(propertyIndex, nodeName);
} else {
return getSimpleIndexBuilder(propertyIndex, nodeName);
}
}
private NodeBuilder getSimpleIndexBuilder(NodeBuilder propertyIndex, String nodeName) {
NodeBuilder idx = propertyIndex.child(nodeName);
if (idx.isNew()) {
idx.setProperty(PROP_HEAD_BUCKET, DEFAULT_HEAD_BUCKET);
idx.setProperty(PROP_STORAGE_TYPE, STORAGE_TYPE_CONTENT_MIRROR);
}
String headBucketName = idx.getString(PROP_HEAD_BUCKET);
checkNotNull(headBucketName, "[%s] property not found in [%s] for index [%s]",
PROP_HEAD_BUCKET, idx, indexPath);
return idx.child(headBucketName);
}
private static NodeBuilder getUniqueIndexBuilder(NodeBuilder propertyIndex, String nodeName) {
NodeBuilder idx = propertyIndex.child(nodeName);
if (idx.isNew()) {
idx.setProperty(PROP_STORAGE_TYPE, STORAGE_TYPE_UNIQUE);
}
return idx;
}
private static Set<String> getValueKeys(PropertyState property, ValuePattern pattern) {
Set<String> keys = new HashSet<>();
if (property != null
&& property.getType().tag() != PropertyType.BINARY
&& property.count() != 0) {
keys.addAll(encode(PropertyValues.create(property), pattern));
}
return keys;
}
}
| oak-lucene/src/main/java/org/apache/jackrabbit/oak/plugins/index/lucene/property/PropertyIndexUpdateCallback.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.jackrabbit.oak.plugins.index.lucene.property;
import java.util.HashSet;
import java.util.Set;
import javax.annotation.Nullable;
import javax.jcr.PropertyType;
import org.apache.jackrabbit.oak.api.CommitFailedException;
import org.apache.jackrabbit.oak.api.PropertyState;
import org.apache.jackrabbit.oak.plugins.index.lucene.PropertyDefinition;
import org.apache.jackrabbit.oak.plugins.index.lucene.PropertyUpdateCallback;
import org.apache.jackrabbit.oak.plugins.index.property.ValuePattern;
import org.apache.jackrabbit.oak.plugins.index.property.strategy.ContentMirrorStoreStrategy;
import org.apache.jackrabbit.oak.plugins.index.property.strategy.UniqueEntryStoreStrategy;
import org.apache.jackrabbit.oak.plugins.memory.PropertyValues;
import org.apache.jackrabbit.oak.spi.state.NodeBuilder;
import org.apache.jackrabbit.oak.stats.Clock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Suppliers.ofInstance;
import static com.google.common.collect.Sets.newHashSet;
import static java.util.Collections.emptySet;
import static org.apache.jackrabbit.oak.plugins.index.IndexConstants.INDEX_CONTENT_NODE_NAME;
import static org.apache.jackrabbit.oak.plugins.index.lucene.property.HybridPropertyIndexUtil.PROPERTY_INDEX;
import static org.apache.jackrabbit.oak.plugins.index.lucene.property.HybridPropertyIndexUtil.PROP_CREATED;
import static org.apache.jackrabbit.oak.plugins.index.lucene.property.HybridPropertyIndexUtil.PROP_HEAD_BUCKET;
import static org.apache.jackrabbit.oak.plugins.index.lucene.property.HybridPropertyIndexUtil.PROP_STORAGE_TYPE;
import static org.apache.jackrabbit.oak.plugins.index.lucene.property.HybridPropertyIndexUtil.STORAGE_TYPE_CONTENT_MIRROR;
import static org.apache.jackrabbit.oak.plugins.index.lucene.property.HybridPropertyIndexUtil.STORAGE_TYPE_UNIQUE;
import static org.apache.jackrabbit.oak.plugins.index.property.PropertyIndexUtil.encode;
public class PropertyIndexUpdateCallback implements PropertyUpdateCallback {
private static final Logger log = LoggerFactory.getLogger(PropertyIndexUpdateCallback.class);
private static final String DEFAULT_HEAD_BUCKET = String.valueOf(1);
private final NodeBuilder builder;
private final String indexPath;
private final UniquenessConstraintValidator uniquenessConstraintValidator;
private final long updateTime;
public PropertyIndexUpdateCallback(String indexPath, NodeBuilder builder) {
this(indexPath, builder, Clock.SIMPLE);
}
public PropertyIndexUpdateCallback(String indexPath, NodeBuilder builder, Clock clock) {
this.builder = builder;
this.indexPath = indexPath;
this.updateTime = clock.getTime();
this.uniquenessConstraintValidator = new UniquenessConstraintValidator(indexPath, builder);
}
@Override
public void propertyUpdated(String nodePath, String propertyRelativePath, PropertyDefinition pd,
@Nullable PropertyState before, @Nullable PropertyState after) {
if (!pd.sync) {
return;
}
Set<String> beforeKeys = getValueKeys(before, pd.valuePattern);
Set<String> afterKeys = getValueKeys(after, pd.valuePattern);
//Remove duplicates
Set<String> sharedKeys = newHashSet(beforeKeys);
sharedKeys.retainAll(afterKeys);
beforeKeys.removeAll(sharedKeys);
afterKeys.removeAll(sharedKeys);
if (!beforeKeys.isEmpty() || !afterKeys.isEmpty()){
NodeBuilder indexNode = getIndexNode(propertyRelativePath, pd.unique);
if (pd.unique) {
UniqueEntryStoreStrategy s = new UniqueEntryStoreStrategy(INDEX_CONTENT_NODE_NAME,
(nb) -> nb.setProperty(PROP_CREATED, updateTime));
s.update(ofInstance(indexNode),
nodePath,
null,
null,
beforeKeys,
afterKeys);
uniquenessConstraintValidator.add(propertyRelativePath, afterKeys);
} else {
ContentMirrorStoreStrategy s = new ContentMirrorStoreStrategy();
s.update(ofInstance(indexNode),
nodePath,
null,
null,
emptySet(), //Disable pruning with empty before keys
afterKeys);
}
if (log.isTraceEnabled()) {
log.trace("[{}] Property index updated for [{}/@{}] with values [{}]", indexPath, nodePath,
propertyRelativePath, afterKeys);
}
}
}
@Override
public void done() throws CommitFailedException {
uniquenessConstraintValidator.validate();
}
public UniquenessConstraintValidator getUniquenessConstraintValidator() {
return uniquenessConstraintValidator;
}
private NodeBuilder getIndexNode(String propertyRelativePath, boolean unique) {
NodeBuilder propertyIndex = builder.child(PROPERTY_INDEX);
String nodeName = HybridPropertyIndexUtil.getNodeName(propertyRelativePath);
if (unique) {
return getUniqueIndexBuilder(propertyIndex, nodeName);
} else {
return getSimpleIndexBuilder(propertyIndex, nodeName);
}
}
private NodeBuilder getSimpleIndexBuilder(NodeBuilder propertyIndex, String nodeName) {
NodeBuilder idx = propertyIndex.child(nodeName);
if (idx.isNew()) {
idx.setProperty(PROP_HEAD_BUCKET, DEFAULT_HEAD_BUCKET);
idx.setProperty(PROP_STORAGE_TYPE, STORAGE_TYPE_CONTENT_MIRROR);
}
String headBucketName = idx.getString(PROP_HEAD_BUCKET);
checkNotNull(headBucketName, "[%s] property not found in [%s] for index [%s]",
PROP_HEAD_BUCKET, idx, indexPath);
return idx.child(headBucketName);
}
private static NodeBuilder getUniqueIndexBuilder(NodeBuilder propertyIndex, String nodeName) {
NodeBuilder idx = propertyIndex.child(nodeName);
if (idx.isNew()) {
idx.setProperty(PROP_STORAGE_TYPE, STORAGE_TYPE_UNIQUE);
}
return idx;
}
private static Set<String> getValueKeys(PropertyState property, ValuePattern pattern) {
Set<String> keys = new HashSet<>();
if (property != null
&& property.getType().tag() != PropertyType.BINARY
&& property.count() != 0) {
keys.addAll(encode(PropertyValues.create(property), pattern));
}
return keys;
}
}
| OAK-6535 - Synchronous Lucene Property Indexes
Minor fix to logger format as collections toString already have square
brackets '[]' so avoid duplication
git-svn-id: 67138be12999c61558c3dd34328380c8e4523e73@1810647 13f79535-47bb-0310-9956-ffa450edef68
| oak-lucene/src/main/java/org/apache/jackrabbit/oak/plugins/index/lucene/property/PropertyIndexUpdateCallback.java | OAK-6535 - Synchronous Lucene Property Indexes | <ide><path>ak-lucene/src/main/java/org/apache/jackrabbit/oak/plugins/index/lucene/property/PropertyIndexUpdateCallback.java
<ide> }
<ide>
<ide> if (log.isTraceEnabled()) {
<del> log.trace("[{}] Property index updated for [{}/@{}] with values [{}]", indexPath, nodePath,
<add> log.trace("[{}] Property index updated for [{}/@{}] with values {}", indexPath, nodePath,
<ide> propertyRelativePath, afterKeys);
<ide> }
<ide> } |
|
JavaScript | mit | cd1680c54d9b7006dbbbc3d9cf9efd0d175e8850 | 0 | omorandi/TiAssetsLibrary,omorandi/TiAssetsLibrary,omorandi/TiAssetsLibrary | var assetslibrary = require('ti.assetslibrary');
exports.getFirstAsset = function() {
var successCb = function(e) {
var groups = e.groups;
if (!groups || groups.length === 0) {
Ti.API.warn('SINGLE_ASSET: Got no groups');
return;
}
Ti.API.info('SINGLE_ASSET: Got ' + groups.length + ' groups');
//let's consider the first group
var group = groups[0];
Ti.API.info('SINGLE_ASSET: getting assets for group 0');
//get assets for that group
group.getAssets(function(e) {
var assetsList = e.assets;
if (!assetsList || assetsList.assetsCount === 0) {
Ti.API.warn('SINGLE_ASSET: Got no assets');
return;
}
Ti.API.info('SINGLE_ASSET: Got ' + assetsList.assetsCount + ' assets');
//let's consider the first asset
var asset = assetsList.getAssetAtIndex(0);
//let's consider only the default representation
var rep = asset.defaultRepresentation;
var url = rep.url;
//OK let's test assetslibrary.getAsset();
Ti.API.info('SINGLE_ASSET: getting asset from URL: ' + url);
assetslibrary.getAsset(url, function(e) {
Ti.API.info('SINGLE_ASSET: Got Asset with URL: ' + e.asset.URLs[rep.UTI]);
}, function (e) {
Ti.API.error('SINGLE_ASSET: error: ' + e.error);
});
});
};
var errorCb = function(e) {
Ti.API.error('error: ' + e.error);
};
Ti.API.info('SINGLE_ASSET: Getting groups');
var groups = assetslibrary.getGroups([assetslibrary.AssetsGroupTypeAll], successCb, errorCb);
};
| ALTestapp/Resources/single_asset.js | var assetslibrary = require('ti.assetslibrary');
exports.getFirstAsset = function() {
var successCb = function(e) {
var groups = e.groups;
if (!groups || groups.length === 0) {
Ti.API.warn('SINGLE_ASSET: Got no groups');
return;
}
Ti.API.info('SINGLE_ASSET: Got ' + groups.length + ' groups');
//let's consider the first group
var group = groups[0];
Ti.API.info('SINGLE_ASSET: getting assets for group 0');
//get assets for that group
group.getAssets(function(e) {
var assetsList = e.assets;
if (!assetsList || assetsList.assetsCount === 0) {
Ti.API.warn('SINGLE_ASSET: Got no assets');
return;
}
Ti.API.info('SINGLE_ASSET: Got ' + assetsList.assetsCount + ' assets');
//let's consider the first asset
var asset = assetsList.getAssetAtIndex(0);
//extract the asset representations:
var representations = asset.representations;
if (!representations || representations.length === 0) {
Ti.API.warn('SINGLE_ASSET: asset with no representations');
return;
}
//let's consider the first representation
var rep = representations[0];
var url = rep.url;
//OK let's test assetslibrary.getAsset();
Ti.API.info('SINGLE_ASSET: getting asset from URL: ' + url);
assetslibrary.getAsset(url, function(e) {
Ti.API.info('SINGLE_ASSET: Got Asset with URL: ' + e.asset.URLs[rep.UTI]);
}, function (e) {
Ti.API.error('SINGLE_ASSET: error: ' + e.error);
});
});
};
var errorCb = function(e) {
Ti.API.error('error: ' + e.error);
};
Ti.API.info('SINGLE_ASSET: Getting groups');
var groups = assetslibrary.getGroups([assetslibrary.AssetsGroupTypeAll], successCb, errorCb);
};
| simplyfied the test app
| ALTestapp/Resources/single_asset.js | simplyfied the test app | <ide><path>LTestapp/Resources/single_asset.js
<ide> //let's consider the first asset
<ide> var asset = assetsList.getAssetAtIndex(0);
<ide>
<del> //extract the asset representations:
<del> var representations = asset.representations;
<del> if (!representations || representations.length === 0) {
<del> Ti.API.warn('SINGLE_ASSET: asset with no representations');
<del> return;
<del> }
<del>
<del> //let's consider the first representation
<del> var rep = representations[0];
<add> //let's consider only the default representation
<add> var rep = asset.defaultRepresentation;
<ide>
<ide> var url = rep.url;
<ide> |
|
Java | apache-2.0 | 568e6a3b3889a75a8c2d03795f39b88b77975d4c | 0 | spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework | /*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.context.support;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.FileNotFoundException;
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.TestBean;
import org.springframework.beans.factory.BeanDefinitionStoreException;
import org.springframework.beans.factory.BeanInitializationException;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.beans.factory.config.PropertyResourceConfigurer;
import org.springframework.beans.factory.config.RuntimeBeanReference;
import org.springframework.context.ApplicationContext;
import org.springframework.util.StringUtils;
/**
* Integration tests for {@link PropertyResourceConfigurer} implementations requiring
* interaction with an {@link ApplicationContext}. For example, a {@link PropertyPlaceholderConfigurer}
* that contains ${..} tokens in its 'location' property requires being tested through an ApplicationContext
* as opposed to using only a BeanFactory during testing.
*
* @author Chris Beams
* @see org.springframework.beans.factory.config.PropertyResourceConfigurerTests
*/
public class PropertyResourceConfigurerIntegrationTests {
@Test
public void testPropertyPlaceholderConfigurerWithSystemPropertyInLocation() {
StaticApplicationContext ac = new StaticApplicationContext();
MutablePropertyValues pvs = new MutablePropertyValues();
pvs.addPropertyValue("spouse", new RuntimeBeanReference("${ref}"));
ac.registerSingleton("tb", TestBean.class, pvs);
pvs = new MutablePropertyValues();
pvs.addPropertyValue("location", "${user.dir}/test");
ac.registerSingleton("configurer", PropertyPlaceholderConfigurer.class, pvs);
try {
ac.refresh();
fail("Should have thrown BeanInitializationException");
}
catch (BeanInitializationException ex) {
// expected
assertTrue(ex.getCause() instanceof FileNotFoundException);
// slight hack for Linux/Unix systems
String userDir = StringUtils.cleanPath(System.getProperty("user.dir"));
if (userDir.startsWith("/")) {
userDir = userDir.substring(1);
}
assertTrue(ex.getMessage().indexOf(userDir) != -1);
}
}
@Test
public void testPropertyPlaceholderConfigurerWithSystemPropertiesInLocation() {
StaticApplicationContext ac = new StaticApplicationContext();
MutablePropertyValues pvs = new MutablePropertyValues();
pvs.addPropertyValue("spouse", new RuntimeBeanReference("${ref}"));
ac.registerSingleton("tb", TestBean.class, pvs);
pvs = new MutablePropertyValues();
pvs.addPropertyValue("location", "${user.dir}/test/${user.dir}");
ac.registerSingleton("configurer", PropertyPlaceholderConfigurer.class, pvs);
try {
ac.refresh();
fail("Should have thrown BeanInitializationException");
}
catch (BeanInitializationException ex) {
// expected
assertTrue(ex.getCause() instanceof FileNotFoundException);
// slight hack for Linux/Unix systems
String userDir = StringUtils.cleanPath(System.getProperty("user.dir"));
if (userDir.startsWith("/")) {
userDir = userDir.substring(1);
}
/* the above hack doesn't work since the exception message is created without
the leading / stripped so the test fails. Changed 17/11/04. DD */
//assertTrue(ex.getMessage().indexOf(userDir + "/test/" + userDir) != -1);
assertTrue(ex.getMessage().contains(userDir + "/test/" + userDir) ||
ex.getMessage().contains(userDir + "/test//" + userDir));
}
}
@Test
public void testPropertyPlaceholderConfigurerWithUnresolvableSystemPropertiesInLocation() {
StaticApplicationContext ac = new StaticApplicationContext();
MutablePropertyValues pvs = new MutablePropertyValues();
pvs.addPropertyValue("spouse", new RuntimeBeanReference("${ref}"));
ac.registerSingleton("tb", TestBean.class, pvs);
pvs = new MutablePropertyValues();
pvs.addPropertyValue("location", "${myprop}/test/${myprop}");
ac.registerSingleton("configurer", PropertyPlaceholderConfigurer.class, pvs);
try {
ac.refresh();
fail("Should have thrown BeanInitializationException");
}
catch (BeanInitializationException ex) {
// expected
assertTrue(ex.getMessage().contains("myprop"));
}
}
@Test
public void testPropertyPlaceholderConfigurerWithMultiLevelCircularReference() {
StaticApplicationContext ac = new StaticApplicationContext();
MutablePropertyValues pvs = new MutablePropertyValues();
pvs.addPropertyValue("name", "name${var}");
ac.registerSingleton("tb1", TestBean.class, pvs);
pvs = new MutablePropertyValues();
pvs.addPropertyValue("properties", "var=${m}var\nm=${var2}\nvar2=${var}");
ac.registerSingleton("configurer1", PropertyPlaceholderConfigurer.class, pvs);
try {
ac.refresh();
fail("Should have thrown BeanDefinitionStoreException");
}
catch (BeanDefinitionStoreException ex) {
// expected
}
}
@Test
public void testPropertyPlaceholderConfigurerWithNestedCircularReference() {
StaticApplicationContext ac = new StaticApplicationContext();
MutablePropertyValues pvs = new MutablePropertyValues();
pvs.addPropertyValue("name", "name${var}");
ac.registerSingleton("tb1", TestBean.class, pvs);
pvs = new MutablePropertyValues();
pvs.addPropertyValue("properties", "var=${m}var\nm=${var2}\nvar2=${m}");
ac.registerSingleton("configurer1", PropertyPlaceholderConfigurer.class, pvs);
try {
ac.refresh();
fail("Should have thrown BeanDefinitionStoreException");
}
catch (BeanDefinitionStoreException ex) {
// expected
}
}
@Ignore // this test was breaking after the 3.0 repackaging
@Test
public void testPropertyPlaceholderConfigurerWithAutowireByType() {
// StaticApplicationContext ac = new StaticApplicationContext();
// MutablePropertyValues pvs = new MutablePropertyValues();
// pvs.addPropertyValue("touchy", "${test}");
// ac.registerSingleton("tb", TestBean.class, pvs);
// pvs = new MutablePropertyValues();
// pvs.addPropertyValue("target", new RuntimeBeanReference("tb"));
// // uncomment when fixing this test
// // ac.registerSingleton("tbProxy", org.springframework.aop.framework.ProxyFactoryBean.class, pvs);
// pvs = new MutablePropertyValues();
// Properties props = new Properties();
// props.put("test", "mytest");
// pvs.addPropertyValue("properties", new Properties(props));
// RootBeanDefinition ppcDef = new RootBeanDefinition(PropertyPlaceholderConfigurer.class, pvs);
// ppcDef.setAutowireMode(RootBeanDefinition.AUTOWIRE_BY_TYPE);
// ac.registerBeanDefinition("configurer", ppcDef);
// ac.refresh();
// TestBean tb = (TestBean) ac.getBean("tb");
// assertEquals("mytest", tb.getTouchy());
}
}
| org.springframework.context/src/test/java/org/springframework/context/support/PropertyResourceConfigurerIntegrationTests.java | /*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.context.support;
import java.io.FileNotFoundException;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.TestBean;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.BeanDefinitionStoreException;
import org.springframework.beans.factory.BeanInitializationException;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.beans.factory.config.PropertyResourceConfigurer;
import org.springframework.beans.factory.config.RuntimeBeanReference;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.util.StringUtils;
/**
* Integration tests for {@link PropertyResourceConfigurer} implementations requiring
* interaction with an {@link ApplicationContext}. For example, a {@link PropertyPlaceholderConfigurer}
* that contains ${..} tokens in its 'location' property requires being tested through an ApplicationContext
* as opposed to using only a BeanFactory during testing.
*
* @author Chris Beams
* @see org.springframework.beans.factory.config.PropertyResourceConfigurerTests
*/
public class PropertyResourceConfigurerIntegrationTests {
private DefaultListableBeanFactory factory;
@Before
public void setUp() {
factory = new DefaultListableBeanFactory();
}
@Test
public void testPropertyPlaceholderConfigurerWithSystemPropertyInLocation() {
StaticApplicationContext ac = new StaticApplicationContext();
MutablePropertyValues pvs = new MutablePropertyValues();
pvs.addPropertyValue("spouse", new RuntimeBeanReference("${ref}"));
ac.registerSingleton("tb", TestBean.class, pvs);
pvs = new MutablePropertyValues();
pvs.addPropertyValue("location", "${user.dir}/test");
ac.registerSingleton("configurer", PropertyPlaceholderConfigurer.class, pvs);
try {
ac.refresh();
fail("Should have thrown BeanInitializationException");
}
catch (BeanInitializationException ex) {
// expected
assertTrue(ex.getCause() instanceof FileNotFoundException);
// slight hack for Linux/Unix systems
String userDir = StringUtils.cleanPath(System.getProperty("user.dir"));
if (userDir.startsWith("/")) {
userDir = userDir.substring(1);
}
assertTrue(ex.getMessage().indexOf(userDir) != -1);
}
}
@Test
public void testPropertyPlaceholderConfigurerWithSystemPropertiesInLocation() {
StaticApplicationContext ac = new StaticApplicationContext();
MutablePropertyValues pvs = new MutablePropertyValues();
pvs.addPropertyValue("spouse", new RuntimeBeanReference("${ref}"));
ac.registerSingleton("tb", TestBean.class, pvs);
pvs = new MutablePropertyValues();
pvs.addPropertyValue("location", "${user.dir}/test/${user.dir}");
ac.registerSingleton("configurer", PropertyPlaceholderConfigurer.class, pvs);
try {
ac.refresh();
fail("Should have thrown BeanInitializationException");
}
catch (BeanInitializationException ex) {
// expected
assertTrue(ex.getCause() instanceof FileNotFoundException);
// slight hack for Linux/Unix systems
String userDir = StringUtils.cleanPath(System.getProperty("user.dir"));
if (userDir.startsWith("/")) {
userDir = userDir.substring(1);
}
/* the above hack doesn't work since the exception message is created without
the leading / stripped so the test fails. Changed 17/11/04. DD */
//assertTrue(ex.getMessage().indexOf(userDir + "/test/" + userDir) != -1);
assertTrue(ex.getMessage().contains(userDir + "/test/" + userDir) ||
ex.getMessage().contains(userDir + "/test//" + userDir));
}
}
@Test
public void testPropertyPlaceholderConfigurerWithUnresolvableSystemPropertiesInLocation() {
StaticApplicationContext ac = new StaticApplicationContext();
MutablePropertyValues pvs = new MutablePropertyValues();
pvs.addPropertyValue("spouse", new RuntimeBeanReference("${ref}"));
ac.registerSingleton("tb", TestBean.class, pvs);
pvs = new MutablePropertyValues();
pvs.addPropertyValue("location", "${myprop}/test/${myprop}");
ac.registerSingleton("configurer", PropertyPlaceholderConfigurer.class, pvs);
try {
ac.refresh();
fail("Should have thrown BeanCreationException");
}
catch (BeanCreationException ex) {
// expected
assertTrue(ex.getMessage().contains("myprop"));
}
}
@Test
public void testPropertyPlaceholderConfigurerWithMultiLevelCircularReference() {
StaticApplicationContext ac = new StaticApplicationContext();
MutablePropertyValues pvs = new MutablePropertyValues();
pvs.addPropertyValue("name", "name${var}");
ac.registerSingleton("tb1", TestBean.class, pvs);
pvs = new MutablePropertyValues();
pvs.addPropertyValue("properties", "var=${m}var\nm=${var2}\nvar2=${var}");
ac.registerSingleton("configurer1", PropertyPlaceholderConfigurer.class, pvs);
try {
ac.refresh();
fail("Should have thrown BeanDefinitionStoreException");
}
catch (BeanDefinitionStoreException ex) {
// expected
}
}
@Test
public void testPropertyPlaceholderConfigurerWithNestedCircularReference() {
StaticApplicationContext ac = new StaticApplicationContext();
MutablePropertyValues pvs = new MutablePropertyValues();
pvs.addPropertyValue("name", "name${var}");
ac.registerSingleton("tb1", TestBean.class, pvs);
pvs = new MutablePropertyValues();
pvs.addPropertyValue("properties", "var=${m}var\nm=${var2}\nvar2=${m}");
ac.registerSingleton("configurer1", PropertyPlaceholderConfigurer.class, pvs);
try {
ac.refresh();
fail("Should have thrown BeanDefinitionStoreException");
}
catch (BeanDefinitionStoreException ex) {
// expected
}
}
@Ignore // this test was breaking after the 3.0 repackaging
@Test
public void testPropertyPlaceholderConfigurerWithAutowireByType() {
// StaticApplicationContext ac = new StaticApplicationContext();
// MutablePropertyValues pvs = new MutablePropertyValues();
// pvs.addPropertyValue("touchy", "${test}");
// ac.registerSingleton("tb", TestBean.class, pvs);
// pvs = new MutablePropertyValues();
// pvs.addPropertyValue("target", new RuntimeBeanReference("tb"));
// // uncomment when fixing this test
// // ac.registerSingleton("tbProxy", org.springframework.aop.framework.ProxyFactoryBean.class, pvs);
// pvs = new MutablePropertyValues();
// Properties props = new Properties();
// props.put("test", "mytest");
// pvs.addPropertyValue("properties", new Properties(props));
// RootBeanDefinition ppcDef = new RootBeanDefinition(PropertyPlaceholderConfigurer.class, pvs);
// ppcDef.setAutowireMode(RootBeanDefinition.AUTOWIRE_BY_TYPE);
// ac.registerBeanDefinition("configurer", ppcDef);
// ac.refresh();
// TestBean tb = (TestBean) ac.getBean("tb");
// assertEquals("mytest", tb.getTouchy());
}
}
| RESOLVED - issue SPR-6321: Regression: ResourceEditor in 3.0 does not ignore unresolvable placeholders, but it did in 2.5.6
Different initialization exception popped up in app context
| org.springframework.context/src/test/java/org/springframework/context/support/PropertyResourceConfigurerIntegrationTests.java | RESOLVED - issue SPR-6321: Regression: ResourceEditor in 3.0 does not ignore unresolvable placeholders, but it did in 2.5.6 Different initialization exception popped up in app context | <ide><path>rg.springframework.context/src/test/java/org/springframework/context/support/PropertyResourceConfigurerIntegrationTests.java
<ide>
<ide> package org.springframework.context.support;
<ide>
<add>import static org.junit.Assert.assertTrue;
<add>import static org.junit.Assert.fail;
<add>
<ide> import java.io.FileNotFoundException;
<ide>
<del>import static org.junit.Assert.*;
<del>import org.junit.Before;
<ide> import org.junit.Ignore;
<ide> import org.junit.Test;
<del>
<ide> import org.springframework.beans.MutablePropertyValues;
<ide> import org.springframework.beans.TestBean;
<del>import org.springframework.beans.factory.BeanCreationException;
<ide> import org.springframework.beans.factory.BeanDefinitionStoreException;
<ide> import org.springframework.beans.factory.BeanInitializationException;
<ide> import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
<ide> import org.springframework.beans.factory.config.PropertyResourceConfigurer;
<ide> import org.springframework.beans.factory.config.RuntimeBeanReference;
<del>import org.springframework.beans.factory.support.DefaultListableBeanFactory;
<ide> import org.springframework.context.ApplicationContext;
<ide> import org.springframework.util.StringUtils;
<ide>
<ide> */
<ide> public class PropertyResourceConfigurerIntegrationTests {
<ide>
<del> private DefaultListableBeanFactory factory;
<del>
<del> @Before
<del> public void setUp() {
<del> factory = new DefaultListableBeanFactory();
<del> }
<del>
<ide> @Test
<ide> public void testPropertyPlaceholderConfigurerWithSystemPropertyInLocation() {
<ide> StaticApplicationContext ac = new StaticApplicationContext();
<ide> ac.registerSingleton("configurer", PropertyPlaceholderConfigurer.class, pvs);
<ide> try {
<ide> ac.refresh();
<del> fail("Should have thrown BeanCreationException");
<add> fail("Should have thrown BeanInitializationException");
<ide> }
<del> catch (BeanCreationException ex) {
<add> catch (BeanInitializationException ex) {
<ide> // expected
<ide> assertTrue(ex.getMessage().contains("myprop"));
<ide> } |
|
Java | apache-2.0 | b5fc29154a9f31187cc1606ce600431d2ac1da20 | 0 | giovannibianco/Hydra-Service,giovannibianco/Hydra-Service | /*
* Copyright (c) Members of the EGEE Collaboration. 2004.
* See http://eu-egee.org/partners/ for details on the copyright holders.
* For license conditions see the license file or http://www.apache.org/licenses/LICENSE-2.0
*/
package org.glite.data.hydra.helpers.authz;
import org.glite.data.catalog.service.AuthorizationException;
import org.glite.data.catalog.service.InternalException;
import org.glite.data.catalog.service.InvalidArgumentException;
import org.glite.data.catalog.service.NotExistsException;
import org.glite.data.catalog.service.Perm;
import org.glite.data.catalog.service.PermissionEntry;
import org.glite.data.common.helpers.DBManager;
import org.glite.data.hydra.helpers.AuthorizationHelper;
public class NoAuthorizationHelper extends AuthorizationHelper {
public NoAuthorizationHelper(DBManager dbManager) {
super(dbManager);
}
/* (non-Javadoc)
* @see org.glite.data.catalog.service.meta.helpers.AuthorizationHelper#setPermission(org.glite.data.catalog.service.PermissionEntry[])
*/
public void setPermission(PermissionEntry[] permissions)
throws InvalidArgumentException, InternalException {
}
/* (non-Javadoc)
* @see org.glite.data.catalog.service.meta.helpers.AuthorizationHelper#getPermission(java.lang.String[])
*/
public PermissionEntry[] getPermission(String[] items)
throws AuthorizationException, InternalException {
return null;
}
/* (non-Javadoc)
* @see org.glite.data.catalog.service.meta.helpers.AuthorizationHelper#checkPermission(java.lang.String[], org.glite.data.catalog.service.Perm)
*/
public void checkPermission(String[] entries, Perm patternPerm) throws AuthorizationException, NotExistsException, InternalException {
}
/* (non-Javadoc)
* @see org.glite.data.catalog.service.meta.helpers.AuthorizationHelper#checkSchemaPermission(java.lang.String[], org.glite.data.catalog.service.Perm)
*/
public void checkSchemaPermission(String[] entries, Perm patternPerm) throws AuthorizationException, NotExistsException, InternalException {
}
}
| src/org/glite/data/hydra/helpers/authz/NoAuthorizationHelper.java | /*
* Copyright (c) Members of the EGEE Collaboration. 2004.
* See http://eu-egee.org/partners/ for details on the copyright holders.
* For license conditions see the license file or http://www.apache.org/licenses/LICENSE-2.0
*/
package org.glite.data.hydra.helpers.authz;
import org.glite.data.catalog.service.AuthorizationException;
import org.glite.data.catalog.service.InternalException;
import org.glite.data.catalog.service.InvalidArgumentException;
import org.glite.data.catalog.service.NotExistsException;
import org.glite.data.catalog.service.Perm;
import org.glite.data.catalog.service.PermissionEntry;
import org.glite.data.common.helpers.DBManager;
import org.glite.data.hydra.helpers.AuthorizationHelper;
public class NoAuthorizationHelper extends AuthorizationHelper {
public NoAuthorizationHelper(DBManager dbManager) {
super(dbManager);
}
/* (non-Javadoc)
* @see org.glite.data.catalog.service.meta.helpers.AuthorizationHelper#setPermission(org.glite.data.catalog.service.PermissionEntry[])
*/
public void setPermission(PermissionEntry[] permissions)
throws InvalidArgumentException, InternalException {
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see org.glite.data.catalog.service.meta.helpers.AuthorizationHelper#getPermission(java.lang.String[])
*/
public PermissionEntry[] getPermission(String[] items)
throws AuthorizationException, InternalException {
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see org.glite.data.catalog.service.meta.helpers.AuthorizationHelper#checkPermission(java.lang.String[], org.glite.data.catalog.service.Perm)
*/
public void checkPermission(String[] entries, Perm patternPerm) throws AuthorizationException, NotExistsException, InternalException {
// TODO Auto-generated method stub
}
}
| Cleaned code.
| src/org/glite/data/hydra/helpers/authz/NoAuthorizationHelper.java | Cleaned code. | <ide><path>rc/org/glite/data/hydra/helpers/authz/NoAuthorizationHelper.java
<ide> */
<ide> public void setPermission(PermissionEntry[] permissions)
<ide> throws InvalidArgumentException, InternalException {
<del> // TODO Auto-generated method stub
<ide> }
<ide>
<ide> /* (non-Javadoc)
<ide> */
<ide> public PermissionEntry[] getPermission(String[] items)
<ide> throws AuthorizationException, InternalException {
<del> // TODO Auto-generated method stub
<ide> return null;
<ide> }
<ide>
<ide> * @see org.glite.data.catalog.service.meta.helpers.AuthorizationHelper#checkPermission(java.lang.String[], org.glite.data.catalog.service.Perm)
<ide> */
<ide> public void checkPermission(String[] entries, Perm patternPerm) throws AuthorizationException, NotExistsException, InternalException {
<del> // TODO Auto-generated method stub
<del>
<add>
<add> }
<add>
<add> /* (non-Javadoc)
<add> * @see org.glite.data.catalog.service.meta.helpers.AuthorizationHelper#checkSchemaPermission(java.lang.String[], org.glite.data.catalog.service.Perm)
<add> */
<add> public void checkSchemaPermission(String[] entries, Perm patternPerm) throws AuthorizationException, NotExistsException, InternalException {
<add>
<ide> }
<ide> } |
|
Java | apache-2.0 | 9869a221409c71e4c990b673a60c3a93743d27c6 | 0 | Geomatys/sis,desruisseaux/sis,desruisseaux/sis,Geomatys/sis,desruisseaux/sis,desruisseaux/sis,Geomatys/sis,Geomatys/sis | /*
* 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.sis.internal.metadata.sql;
import java.util.Locale;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ServiceLoader;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.lang.reflect.Method;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.spi.NamingManager;
import javax.naming.NameNotFoundException;
import org.apache.sis.internal.system.DataDirectory;
import org.apache.sis.internal.system.Shutdown;
import org.apache.sis.internal.system.Loggers;
import org.apache.sis.util.resources.Messages;
import org.apache.sis.util.logging.Logging;
// Branch-dependent imports
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
* Manages the unique {@link DataSource} instances to the {@code $SIS_DATA/Databases/SpatialMetadata} database.
* This includes initialization of a new database if none existed. The schemas will be created by subclasses of
* this {@code Initializer} class, which must be registered in the following file:
*
* {@preformat text
* META-INF/services/org.apache.sis.internal.metadata.sql.Initializer
* }
*
* @author Martin Desruisseaux (Geomatys)
* @since 0.7
* @version 0.7
* @module
*/
public abstract class Initializer {
/**
* Name of the database to open in the {@code $SIS_DATA/Databases} directory or the directory given by
* the {@code derby.system.home} property.
*/
private static final String DATABASE = "SpatialMetadata";
/**
* The property name for the home of Derby databases.
*/
private static final String HOME_KEY = "derby.system.home";
/**
* The unique, SIS-wide, data source to the {@code $SIS_DATA/Databases/SpatialMetadata} database.
* Created when first needed, and cleared on shutdown.
*
* @see #getDataSource()
*/
private static DataSource source;
/**
* For subclasses only.
*/
protected Initializer() {
}
/**
* Invoked for populating an initially empty database.
*
* @param connection Connection to the empty database.
* @throws SQLException if an error occurred while populating the database.
*/
protected abstract void createSchema(Connection connection) throws SQLException;
/**
* Returns the data source for the SIS-wide "SpatialMetadata" database.
* This method returns the first of the following steps that succeed:
*
* <ol>
* <li>If a JNDI context exists, the data source registered under the {@code jdbc/SpatialMetadata} name.</li>
* <li>If the {@code SIS_DATA} environment variable is defined, {@code jdbc:derby:$SIS_DATA/Databases/SpatialMetadata}.
* This database will be created if it does not exist. Note that this is the only case where we allow database
* creation since we are in the directory managed by SIS.</li>
* <li>If the {@code derby.system.home} property is defined, the data source for {@code jdbc:derby:SpatialMetadata}.
* This database will <strong>not</strong> be created if it does not exist.</li>
* <li>Otherwise (no JNDI, no environment variable, no Derby property set), {@code null}.</li>
* </ol>
*
* @return The data source for the {@code $SIS_DATA/Databases/SpatialMetadata} or equivalent database, or {@code null} if none.
* @throws javax.naming.NamingException if an error occurred while fetching the data source from a JNDI context.
* @throws java.net.MalformedURLException if an error occurred while converting the {@code derby.jar} file to URL.
* @throws java.lang.ClassNotFoundException if {@code derby.jar} has not been found on the JDK installation directory.
* @throws java.lang.InstantiationException if an error occurred while creating {@code org.apache.derby.jdbc.EmbeddedDataSource}.
* @throws java.lang.NoSuchMethodException if a JDBC bean property has not been found on the data source.
* @throws java.lang.IllegalAccessException if a JDBC bean property of the data source is not public.
* @throws java.lang.reflect.InvocationTargetException if an error occurred while setting a data source bean property.
* @throws Exception for any other kind of errors. This include {@link RuntimeException} not documented above like
* {@link IllegalArgumentException}, {@link ClassCastException}, {@link SecurityException}, <i>etc.</i>
*/
public static synchronized DataSource getDataSource() throws Exception {
if (source == null) {
if (hasJNDI()) try {
final Context env = (Context) InitialContext.doLookup("java:comp/env");
return source = (DataSource) env.lookup("jdbc/" + DATABASE);
} catch (NameNotFoundException e) {
final LogRecord record = Messages.getResources(null).getLogRecord(
Level.CONFIG, Messages.Keys.JNDINotSpecified_1, "jdbc/" + DATABASE);
record.setLoggerName(Loggers.SQL);
Logging.log(Initializer.class, "getDataSource", record);
}
final Path dir = DataDirectory.DATABASES.getDirectory();
if (dir != null) {
source = forJavaDB(dir.resolve(DATABASE));
} else if (System.getProperty(HOME_KEY) != null) {
source = forJavaDB(DATABASE);
}
}
return source;
}
/**
* Returns {@code true} if SIS will try to fetch the {@link DataSource} from JNDI.
*
* @return {@code true} if a JNDI environment seems to be present.
*/
public static boolean hasJNDI() {
return NamingManager.hasInitialContextFactoryBuilder() ||
System.getProperty(Context.INITIAL_CONTEXT_FACTORY) != null;
}
/**
* Returns a message for unspecified data source. The message will depend on whether a JNDI context exists or not.
* This message can be used for constructing an exception when {@link #getDataSource()} returned {@code null}.
*
* @param locale The locale for the message to produce, or {@code null} for the default one.
* @return Message for unspecified data source.
*/
public static String unspecified(final Locale locale) {
final short key;
final String value;
if (hasJNDI()) {
key = Messages.Keys.JNDINotSpecified_1;
value = "jdbc/" + DATABASE;
} else {
key = Messages.Keys.DataDirectoryNotSpecified_1;
value = DataDirectory.ENV;
}
return Messages.getResources(locale).getString(key, value);
}
/**
* Creates a data source for a Derby database at the given {@code $SIS_DATA/Databases/SpatialMetadata} location.
* If the database does not exist, it will be created.
*
* @param path The {@code $SIS_DATA/Databases/SpatialMetadata} directory.
* @return The data source.
* @throws Exception if the data source can not be created.
*/
private static DataSource forJavaDB(Path path) throws Exception {
/*
* If a "derby.system.home" property is set, we may be able to get a shorter path by making it
* relative to Derby home. The intend is to have a nicer URL like "jdbc:derby:SpatialMetadata"
* instead than "jdbc:derby:/a/long/path/to/SIS/Data/Databases/SpatialMetadata". In addition
* to making loggings and EPSGDataAccess.getAuthority() output nicer, it also reduces the risk
* of encoding issues if the path contains spaces or non-ASCII characters.
*/
try {
final String home = System.getProperty(HOME_KEY);
if (home != null) {
path = Paths.get(home).relativize(path);
}
} catch (IllegalArgumentException | SecurityException e) {
// The path can not be relativized. This is okay. Use the public method as the logging source.
Logging.recoverableException(Logging.getLogger(Loggers.SQL), Initializer.class, "getDataSource", e);
}
/*
* Create the Derby data source using the context class loader if possible,
* or otherwise a URL class loader to the JavaDB distributed with the JDK.
*/
path = path.normalize();
final DataSource ds = forJavaDB(path.toString());
/*
* If the database does not exist, create it. We allow creation only here because we are inside
* the $SIS_DATA directory. The Java code creating the schemas is provided in other SIS modules.
* For example sis-referencing may create the EPSG dataset.
*/
if (!Files.exists(path)) {
final Method m = ds.getClass().getMethod("setCreateDatabase", String.class);
m.invoke(ds, "create");
try (Connection c = ds.getConnection()) {
for (Initializer init : ServiceLoader.load(Initializer.class)) {
init.createSchema(c);
}
} finally {
m.invoke(ds, "no"); // Any value other than "create".
}
}
return ds;
}
/**
* Creates a data source for a Derby database at the given location. The location may be either the
* {@code $SIS_DATA/Databases/SpatialMetadata} directory, or the {@code SpatialMetadata} database
* in the directory given by the {@code derby.system.home} property.
*
* <p>This method does <strong>not</strong> create the database if it does not exist, because this
* method does not know if we are inside the {@code $SIS_DATA} directory.</p>
*
* @param path Relative or absolute path to the database.
* @return The data source.
* @throws Exception if the data source can not be created.
*/
private static DataSource forJavaDB(final String path) throws Exception {
try {
return forJavaDB(path, Thread.currentThread().getContextClassLoader());
} catch (ClassNotFoundException e) {
final String home = System.getProperty("java.home");
if (home != null) {
final Path file = Paths.get(home).resolveSibling("db/lib/derby.jar");
if (Files.isRegularFile(file)) {
return forJavaDB(path, new URLClassLoader(new URL[] {file.toUri().toURL()}));
}
}
throw e;
}
}
/**
* Creates a data source for the given path using the given class loader.
* If this method succeed in creating a data source, then it registers a shutdown hook
* for shutting down the database at JVM shutdown time of Servlet/OSGi bundle uninstall time.
*
* @throws ClassNotFoundException if Derby is not on the classpath.
*/
private static DataSource forJavaDB(final String path, final ClassLoader loader) throws Exception {
final Class<?> c = Class.forName("org.apache.derby.jdbc.EmbeddedDataSource", true, loader);
final DataSource ds = (DataSource) c.newInstance();
final Class<?>[] args = {String.class};
c.getMethod("setDatabaseName", args).invoke(ds, path);
c.getMethod("setDataSourceName", args).invoke(ds, "Apache SIS spatial metadata");
Shutdown.register(() -> {
shutdown();
return null;
});
return ds;
}
/**
* Invoked when the JVM is shutting down, or when the Servlet or OSGi bundle is uninstalled.
* This method shutdowns the Derby database.
*
* @throws ReflectiveOperationException if an error occurred while
* setting the shutdown property on the Derby data source.
*/
private static synchronized void shutdown() throws ReflectiveOperationException {
final DataSource ds = source;
if (ds != null) { // Should never be null, but let be safe.
source = null; // Clear now in case of failure in remaining code.
ds.getClass().getMethod("setShutdownDatabase", String.class).invoke(ds, "shutdown");
try {
ds.getConnection().close(); // Does the actual shutdown.
} catch (SQLException e) { // This is the expected exception.
final LogRecord record = new LogRecord(Level.CONFIG, e.getLocalizedMessage()); // Not WARNING.
record.setLoggerName(Loggers.SQL);
Logging.log(Initializer.class, "shutdown", record);
}
}
}
}
| core/sis-metadata/src/main/java/org/apache/sis/internal/metadata/sql/Initializer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.sis.internal.metadata.sql;
import java.util.Locale;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ServiceLoader;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.lang.reflect.Method;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.spi.NamingManager;
import javax.naming.NameNotFoundException;
import org.apache.sis.internal.system.DataDirectory;
import org.apache.sis.internal.system.Shutdown;
import org.apache.sis.internal.system.Loggers;
import org.apache.sis.util.resources.Messages;
import org.apache.sis.util.logging.Logging;
// Branch-dependent imports
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
* Manages the unique {@link DataSource} instances to the {@code $SIS_DATA/Databases/SpatialMetadata} database.
* This includes initialization of a new database if none existed. The schemas will be created by subclasses of
* this {@code Initializer} class, which must be registered in the following file:
*
* {@preformat text
* META-INF/services/org.apache.sis.internal.metadata.sql.Initializer
* }
*
* @author Martin Desruisseaux (Geomatys)
* @since 0.7
* @version 0.7
* @module
*/
public abstract class Initializer {
/**
* Name of the database to open in the {@code $SIS_DATA/Databases} directory or the directory given by
* the {@code derby.system.home} property.
*/
private static final String DATABASE = "SpatialMetadata";
/**
* The property name for the home of Derby databases.
*/
private static final String HOME_KEY = "derby.system.home";
/**
* The unique, SIS-wide, data source to the {@code $SIS_DATA/Databases/SpatialMetadata} database.
* Created when first needed, and cleared on shutdown.
*
* @see #getDataSource()
*/
private static DataSource source;
/**
* For subclasses only.
*/
protected Initializer() {
}
/**
* Invoked for populating an initially empty database.
*
* @param connection Connection to the empty database.
* @throws SQLException if an error occurred while populating the database.
*/
protected abstract void createSchema(Connection connection) throws SQLException;
/**
* Returns the data source for the SIS-wide "SpatialMetadata" database.
* This method returns the first of the following steps that succeed:
*
* <ol>
* <li>If a JNDI context exists, the data source registered under the {@code jdbc/SpatialMetadata} name.</li>
* <li>If the {@code SIS_DATA} environment variable is defined, {@code jdbc:derby:$SIS_DATA/Databases/SpatialMetadata}.
* This database will be created if it does not exist. Note that this is the only case where we allow database
* creation since we are in the directory managed by SIS.</li>
* <li>If the {@code derby.system.home} property is defined, the data source for {@code jdbc:derby:SpatialMetadata}.
* This database will <strong>not</strong> be created if it does not exist.</li>
* <li>Otherwise (no JNDI, no environment variable, no Derby property set), {@code null}.</li>
* </ol>
*
* @return The data source for the {@code $SIS_DATA/Databases/SpatialMetadata} or equivalent database, or {@code null} if none.
* @throws javax.naming.NamingException if an error occurred while fetching the data source from a JNDI context.
* @throws java.net.MalformedURLException if an error occurred while converting the {@code derby.jar} file to URL.
* @throws java.lang.ClassNotFoundException if {@code derby.jar} has not been found on the JDK installation directory.
* @throws java.lang.InstantiationException if an error occurred while creating {@code org.apache.derby.jdbc.EmbeddedDataSource}.
* @throws java.lang.NoSuchMethodException if a JDBC bean property has not been found on the data source.
* @throws java.lang.IllegalAccessException if a JDBC bean property of the data source is not public.
* @throws java.lang.reflect.InvocationTargetException if an error occurred while setting a data source bean property.
* @throws Exception for any other kind of errors. This include {@link RuntimeException} not documented above like
* {@link IllegalArgumentException}, {@link ClassCastException}, {@link SecurityException}, <i>etc.</i>
*/
public static synchronized DataSource getDataSource() throws Exception {
if (source == null) {
if (NamingManager.hasInitialContextFactoryBuilder()) try {
final Context env = (Context) InitialContext.doLookup("java:comp/env");
return source = (DataSource) env.lookup("jdbc/" + DATABASE);
} catch (NameNotFoundException e) {
Logging.unexpectedException(Logging.getLogger(Loggers.SQL), Initializer.class, "getDataSource", e);
}
final Path dir = DataDirectory.DATABASES.getDirectory();
if (dir != null) {
source = forJavaDB(dir.resolve(DATABASE));
} else if (System.getProperty(HOME_KEY) != null) {
source = forJavaDB(DATABASE);
}
}
return source;
}
/**
* Returns a message for unspecified data source. The message will depend on whether a JNDI context exists or not.
* This message can be used for constructing an exception when {@link #getDataSource()} returned {@code null}.
*
* @param locale The locale for the message to produce, or {@code null} for the default one.
* @return Message for unspecified data source.
*/
public static String unspecified(final Locale locale) {
final short key;
final String value;
if (NamingManager.hasInitialContextFactoryBuilder()) {
key = Messages.Keys.JNDINotSpecified_1;
value = "jdbc/" + DATABASE;
} else {
key = Messages.Keys.DataDirectoryNotSpecified_1;
value = DataDirectory.ENV;
}
return Messages.getResources(locale).getString(key, value);
}
/**
* Creates a data source for a Derby database at the given {@code $SIS_DATA/Databases/SpatialMetadata} location.
* If the database does not exist, it will be created.
*
* @param path The {@code $SIS_DATA/Databases/SpatialMetadata} directory.
* @return The data source.
* @throws Exception if the data source can not be created.
*/
private static DataSource forJavaDB(Path path) throws Exception {
/*
* If a "derby.system.home" property is set, we may be able to get a shorter path by making it
* relative to Derby home. The intend is to have a nicer URL like "jdbc:derby:SpatialMetadata"
* instead than "jdbc:derby:/a/long/path/to/SIS/Data/Databases/SpatialMetadata". In addition
* to making loggings and EPSGDataAccess.getAuthority() output nicer, it also reduces the risk
* of encoding issues if the path contains spaces or non-ASCII characters.
*/
try {
final String home = System.getProperty(HOME_KEY);
if (home != null) {
path = Paths.get(home).relativize(path);
}
} catch (IllegalArgumentException | SecurityException e) {
// The path can not be relativized. This is okay. Use the public method as the logging source.
Logging.recoverableException(Logging.getLogger(Loggers.SQL), Initializer.class, "getDataSource", e);
}
/*
* Create the Derby data source using the context class loader if possible,
* or otherwise a URL class loader to the JavaDB distributed with the JDK.
*/
path = path.normalize();
final DataSource ds = forJavaDB(path.toString());
/*
* If the database does not exist, create it. We allow creation only here because we are inside
* the $SIS_DATA directory. The Java code creating the schemas is provided in other SIS modules.
* For example sis-referencing may create the EPSG dataset.
*/
if (!Files.exists(path)) {
final Method m = ds.getClass().getMethod("setCreateDatabase", String.class);
m.invoke(ds, "create");
try (Connection c = ds.getConnection()) {
for (Initializer init : ServiceLoader.load(Initializer.class)) {
init.createSchema(c);
}
} finally {
m.invoke(ds, "no"); // Any value other than "create".
}
}
return ds;
}
/**
* Creates a data source for a Derby database at the given location. The location may be either the
* {@code $SIS_DATA/Databases/SpatialMetadata} directory, or the {@code SpatialMetadata} database
* in the directory given by the {@code derby.system.home} property.
*
* <p>This method does <strong>not</strong> create the database if it does not exist, because this
* method does not know if we are inside the {@code $SIS_DATA} directory.</p>
*
* @param path Relative or absolute path to the database.
* @return The data source.
* @throws Exception if the data source can not be created.
*/
private static DataSource forJavaDB(final String path) throws Exception {
try {
return forJavaDB(path, Thread.currentThread().getContextClassLoader());
} catch (ClassNotFoundException e) {
final String home = System.getProperty("java.home");
if (home != null) {
final Path file = Paths.get(home).resolveSibling("db/lib/derby.jar");
if (Files.isRegularFile(file)) {
return forJavaDB(path, new URLClassLoader(new URL[] {file.toUri().toURL()}));
}
}
throw e;
}
}
/**
* Creates a data source for the given path using the given class loader.
* If this method succeed in creating a data source, then it registers a shutdown hook
* for shutting down the database at JVM shutdown time of Servlet/OSGi bundle uninstall time.
*
* @throws ClassNotFoundException if Derby is not on the classpath.
*/
private static DataSource forJavaDB(final String path, final ClassLoader loader) throws Exception {
final Class<?> c = Class.forName("org.apache.derby.jdbc.EmbeddedDataSource", true, loader);
final DataSource ds = (DataSource) c.newInstance();
final Class<?>[] args = {String.class};
c.getMethod("setDatabaseName", args).invoke(ds, path);
c.getMethod("setDataSourceName", args).invoke(ds, "Apache SIS spatial metadata");
Shutdown.register(() -> {
shutdown();
return null;
});
return ds;
}
/**
* Invoked when the JVM is shutting down, or when the Servlet or OSGi bundle is uninstalled.
* This method shutdowns the Derby database.
*
* @throws ReflectiveOperationException if an error occurred while
* setting the shutdown property on the Derby data source.
*/
private static synchronized void shutdown() throws ReflectiveOperationException {
final DataSource ds = source;
if (ds != null) { // Should never be null, but let be safe.
source = null; // Clear now in case of failure in remaining code.
ds.getClass().getMethod("setShutdownDatabase", String.class).invoke(ds, "shutdown");
try {
ds.getConnection().close(); // Does the actual shutdown.
} catch (SQLException e) { // This is the expected exception.
final LogRecord record = new LogRecord(Level.CONFIG, e.getLocalizedMessage()); // Not WARNING.
record.setLoggerName(Loggers.SQL);
Logging.log(Initializer.class, "shutdown", record);
}
}
}
}
| More accurate detection of if a JNDI context is available.
git-svn-id: bd781a9493159d57baabeab2b59de614917f0f5c@1727533 13f79535-47bb-0310-9956-ffa450edef68
| core/sis-metadata/src/main/java/org/apache/sis/internal/metadata/sql/Initializer.java | More accurate detection of if a JNDI context is available. | <ide><path>ore/sis-metadata/src/main/java/org/apache/sis/internal/metadata/sql/Initializer.java
<ide> */
<ide> public static synchronized DataSource getDataSource() throws Exception {
<ide> if (source == null) {
<del> if (NamingManager.hasInitialContextFactoryBuilder()) try {
<add> if (hasJNDI()) try {
<ide> final Context env = (Context) InitialContext.doLookup("java:comp/env");
<ide> return source = (DataSource) env.lookup("jdbc/" + DATABASE);
<ide> } catch (NameNotFoundException e) {
<del> Logging.unexpectedException(Logging.getLogger(Loggers.SQL), Initializer.class, "getDataSource", e);
<add> final LogRecord record = Messages.getResources(null).getLogRecord(
<add> Level.CONFIG, Messages.Keys.JNDINotSpecified_1, "jdbc/" + DATABASE);
<add> record.setLoggerName(Loggers.SQL);
<add> Logging.log(Initializer.class, "getDataSource", record);
<ide> }
<ide> final Path dir = DataDirectory.DATABASES.getDirectory();
<ide> if (dir != null) {
<ide> }
<ide>
<ide> /**
<add> * Returns {@code true} if SIS will try to fetch the {@link DataSource} from JNDI.
<add> *
<add> * @return {@code true} if a JNDI environment seems to be present.
<add> */
<add> public static boolean hasJNDI() {
<add> return NamingManager.hasInitialContextFactoryBuilder() ||
<add> System.getProperty(Context.INITIAL_CONTEXT_FACTORY) != null;
<add> }
<add>
<add> /**
<ide> * Returns a message for unspecified data source. The message will depend on whether a JNDI context exists or not.
<ide> * This message can be used for constructing an exception when {@link #getDataSource()} returned {@code null}.
<ide> *
<ide> public static String unspecified(final Locale locale) {
<ide> final short key;
<ide> final String value;
<del> if (NamingManager.hasInitialContextFactoryBuilder()) {
<add> if (hasJNDI()) {
<ide> key = Messages.Keys.JNDINotSpecified_1;
<ide> value = "jdbc/" + DATABASE;
<ide> } else { |
|
Java | lgpl-2.1 | f1dc52dad058ed4d142de681ddf184ddf54b62b4 | 0 | zebrafishmine/intermine,Arabidopsis-Information-Portal/intermine,kimrutherford/intermine,JoeCarlson/intermine,drhee/toxoMine,elsiklab/intermine,Arabidopsis-Information-Portal/intermine,Arabidopsis-Information-Portal/intermine,drhee/toxoMine,tomck/intermine,elsiklab/intermine,JoeCarlson/intermine,joshkh/intermine,joshkh/intermine,elsiklab/intermine,kimrutherford/intermine,Arabidopsis-Information-Portal/intermine,joshkh/intermine,Arabidopsis-Information-Portal/intermine,joshkh/intermine,tomck/intermine,kimrutherford/intermine,elsiklab/intermine,zebrafishmine/intermine,drhee/toxoMine,drhee/toxoMine,drhee/toxoMine,kimrutherford/intermine,drhee/toxoMine,kimrutherford/intermine,drhee/toxoMine,joshkh/intermine,zebrafishmine/intermine,elsiklab/intermine,justincc/intermine,elsiklab/intermine,Arabidopsis-Information-Portal/intermine,zebrafishmine/intermine,elsiklab/intermine,joshkh/intermine,elsiklab/intermine,Arabidopsis-Information-Portal/intermine,tomck/intermine,justincc/intermine,tomck/intermine,zebrafishmine/intermine,elsiklab/intermine,kimrutherford/intermine,JoeCarlson/intermine,tomck/intermine,JoeCarlson/intermine,zebrafishmine/intermine,tomck/intermine,joshkh/intermine,zebrafishmine/intermine,zebrafishmine/intermine,drhee/toxoMine,drhee/toxoMine,justincc/intermine,Arabidopsis-Information-Portal/intermine,JoeCarlson/intermine,kimrutherford/intermine,Arabidopsis-Information-Portal/intermine,tomck/intermine,justincc/intermine,tomck/intermine,justincc/intermine,kimrutherford/intermine,justincc/intermine,joshkh/intermine,justincc/intermine,tomck/intermine,justincc/intermine,JoeCarlson/intermine,joshkh/intermine,zebrafishmine/intermine,kimrutherford/intermine,JoeCarlson/intermine,JoeCarlson/intermine,JoeCarlson/intermine,justincc/intermine | package org.flymine.dataconversion;
/*
* Copyright (C) 2002-2005 FlyMine
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. See the LICENSE file for more
* information or http://www.gnu.org/copyleft/lesser.html.
*
*/
import org.intermine.dataconversion.*;
import org.intermine.metadata.Model;
import org.intermine.xml.full.*;
import org.intermine.objectstore.ObjectStoreException;
import org.intermine.InterMineException;
import org.intermine.util.XmlUtil;
//import org.intermine.util.PropertiesUtil;
import org.apache.log4j.Logger;
import java.util.*;
/**
* Convert Ensembl data in fulldata Item format conforming to a source OWL definition
* to fulldata Item format conforming to InterMine OWL definition.
*
* @author Andrew Varley
* @author Mark Woodbridge
* @author Peter McLaren
*/
public class EnsemblDataTranslator extends DataTranslator
{
/**
* USEFULL CONSTANT
* */
public static final String EMPTY_STRING = "";
/**
* USEFULL CONSTANT
* */
public static final String IDENTIFIER = "identifier";
protected static final String PATH_NAME_SPACE = "http://www.flymine.org/model/ensembl#";
protected static final ItemPath TRANSCRIPT_VIA_TRANSLATION =
new ItemPath("(transcript <- translation.transcript)", PATH_NAME_SPACE);
protected static final ItemPath EXON_VIA_EXON_TRANSCRIPT =
new ItemPath("(exon <- exon_transcript.exon)", PATH_NAME_SPACE);
protected static final ItemPath SEQ_REGION_VIA_DNA =
new ItemPath("(seq_region <- dna.seq_region)", PATH_NAME_SPACE);
protected static final ItemPath MARKER_VIA_MARKER_SYNONYM =
new ItemPath("(marker <- marker_synonym.marker)", PATH_NAME_SPACE);
protected static final Logger LOG = Logger.getLogger(EnsemblDataTranslator.class);
private Map seqIdMap = new HashMap();
private Map itemId2SynMap = new HashMap();
private Map markerSynonymMap = new HashMap();
private String srcNs;
//Holds all the information from the Ensembl Config file - i.e. datasources & sets
private EnsemblConfig config;
/**
* @param srcItemReader Our source item provider.
* @param mergeSpec The contents of our mapping spec.
* @param srcModel The data model we are translating items from.
* @param tgtModel The data model we are translating items into.
* @param ensemblProps Properties that are organism specific.
* @param orgAbbrev A suitably short acronym to identify which ogransim to process; 'HS' = Human
*/
public EnsemblDataTranslator(ItemReader srcItemReader,
Properties mergeSpec,
Model srcModel,
Model tgtModel,
Properties ensemblProps,
String orgAbbrev) {
super(srcItemReader, mergeSpec, srcModel, tgtModel);
config = new EnsemblConfig(ensemblProps, orgAbbrev);
}
/**
* @see org.intermine.dataconversion.DataTranslator#translate
*/
public void translate(ItemWriter tgtItemWriter)
throws ObjectStoreException, InterMineException {
super.translate(tgtItemWriter);
tgtItemWriter.store(ItemHelper.convert(config.getOrganism()));
tgtItemWriter.store(ItemHelper.convert(config.getEnsemblDataSet()));
for (Iterator dsIt = config.getDataSrcItemIterator(); dsIt.hasNext(); ) {
tgtItemWriter.store(ItemHelper.convert((Item) dsIt.next()));
}
for (Iterator seqSynIt = itemId2SynMap.values().iterator(); seqSynIt.hasNext();) {
tgtItemWriter.store(ItemHelper.convert((Item) seqSynIt.next()));
}
}
/**
* @see org.intermine.dataconversion.DataTranslator#translateItem
*/
protected Collection translateItem(Item srcItem)
throws ObjectStoreException, InterMineException {
Collection result = new HashSet();
srcNs = XmlUtil.getNamespaceFromURI(srcItem.getClassName());
String srcItemClassName = XmlUtil.getFragmentFromURI(srcItem.getClassName());
Collection translated = super.translateItem(srcItem);
if (translated != null) {
for (Iterator i = translated.iterator(); i.hasNext();) {
boolean storeTgtItem = true;
Item tgtItem = (Item) i.next();
if ("dna".equals(srcItemClassName)) {
if (config.doStoreDna()) {
if (srcItem.hasAttribute("sequence")) {
int seqLen = srcItem.getAttribute("sequence").getValue().length();
tgtItem.setAttribute("length", Integer.toString(seqLen));
} else {
LOG.warn("A DNA item has no sequence! " + srcItem.getIdentifier());
}
} else {
LOG.debug("Skipping a DNA item! " + srcItem.getIdentifier());
storeTgtItem = false;
}
} else if ("karyotype".equals(srcItemClassName)) {
translateKaryotype(srcItem, tgtItem, result);
} else if ("exon".equals(srcItemClassName)) {
//Skip this exon if it points to invalid transcripts!
if (!isExonToBeKept(srcItem, true)) {
LOG.debug("isExonToBeKept false for Exon:" + srcItem.getIdentifier());
return result;
}
tgtItem.addReference(config.getOrganismRef());
Item stableId = getStableId("exon", srcItem.getIdentifier(), srcNs);
// <- exon_stable_id.exon
if (stableId != null) {
moveField(stableId, tgtItem, "stable_id", IDENTIFIER);
}
addReferencedItem(tgtItem, config.getEnsemblDataSet(),
"evidence", true, "", false);
Item location = createLocation(srcItem, tgtItem, true); // seq_region
// seq_region.coord-sys
result.add(location);
} else if ("gene".equals(srcItemClassName)) {
tgtItem.addReference(config.getOrganismRef());
addReferencedItem(tgtItem, config.getEnsemblDataSet(),
"evidence", true, "", false);
Item comment = createComment(srcItem, tgtItem);
if (comment != null) {
result.add(comment);
}
Item location = createLocation(srcItem, tgtItem, true); // seq_region
// seq_region.coord-sys
result.add(location);
Item anaResult = createAnalysisResult(srcItem, tgtItem); // analysis
result.add(anaResult);
// the default gene organismDbId should be its stable id (or identifier if none)
//i.e. for anoph they are the same, but for human they are differant
//note: the organismDbId is effecivly what we choose as a primary accession
// and thus may differ from what we want to assign as the identifier...
if (config.useXrefDbsForGeneIdentifier()) {
result.addAll(doXrefGeneHandling(srcItem, tgtItem, srcNs));
} else {
result.addAll(doDefaultGeneHandling(srcItem, tgtItem, srcNs));
}
} else if ("transcript".equals(srcItemClassName)) {
translateTranscript(srcItem, tgtItem, result, srcNs);
} else if ("translation".equals(srcItemClassName)) {
tgtItem.addReference(config.getOrganismRef());
// if no identifier set the identifier as name (primary key)
if (!tgtItem.hasAttribute(IDENTIFIER)) {
Item stableId = getStableId("translation", srcItem.getIdentifier(), srcNs);
// <- transcript_stable_id.transcript
if (stableId != null) {
moveField(stableId, tgtItem, "stable_id", IDENTIFIER);
} else {
tgtItem.addAttribute(
new Attribute(IDENTIFIER, srcItem.getIdentifier()));
}
}
// stable_ids become syonyms, need ensembl DataSet as evidence
} else if (srcItemClassName.endsWith("_stable_id")) {
//check to see if the exons point to valid transcripts before making a synonym.
if (srcItemClassName.startsWith("exon")) {
//Skip this exon if it points to invalid transcripts!
if (!isExonToBeKept(srcItem, false)) {
return result;
}
}
tgtItem.addToCollection("evidence", config.getEnsemblDataSet());
tgtItem.addReference(config.getEnsemblDataSrcRef());
tgtItem.addAttribute(new Attribute("type", IDENTIFIER));
} else if ("repeat_feature".equals(srcItemClassName)) {
translateRepeatFeature(srcItem, tgtItem, result);
// repeat_consensus
} else if ("marker".equals(srcItemClassName)) {
tgtItem.addReference(config.getOrganismRef());
//is there an identifier set?
if (!srcItem.hasAttribute("identifier")) {
//ok try and look up any related marker_synonym items...
}
addReferencedItem(tgtItem,
config.getEnsemblDataSet(), "evidence", true, "", false);
Set locations = createLocations(srcItem, tgtItem, srcNs);
// <- marker_feature.marker
// (<- marker_feature.marker).seq_region
// (<- marker_feature.marker).seq_region.coord_system
//List locationIds = new ArrayList();
for (Iterator j = locations.iterator(); j.hasNext();) {
Item location = (Item) j.next();
//locationIds.add(location.getIdentifier());
result.add(location);
}
setNameAttribute(srcItem, tgtItem);
// display_marker_synonym
}
if (storeTgtItem) {
result.add(tgtItem);
}
}
} else if ("marker_synonym".equals(srcItemClassName)) {
Item synonym = getMarkerSynonym(srcItem);
if (synonym != null) {
result.add(synonym);
}
// assembly maps to null but want to create location on a supercontig
} else if ("assembly".equals(srcItemClassName)) {
Item location = createAssemblyLocation(result, srcItem);
result.add(location);
// seq_region map to null, become Chromosome, Supercontig, Clone and Contig respectively
} else if ("seq_region".equals(srcItemClassName)) {
Item seq = getSeqItem(srcItem.getIdentifier(), true);
seq.addReference(config.getOrganismRef());
result.add(seq);
//simple_feature map to null, become TRNA/CpGIsland depending on analysis_id(logic_name)
} else if ("simple_feature".equals(srcItemClassName)) {
Item simpleFeature = createSimpleFeature(srcItem);
if (simpleFeature.getIdentifier() != null
&& !simpleFeature.getIdentifier().equals("")) {
result.add(simpleFeature);
result.add(createLocation(srcItem, simpleFeature, true));
result.add(createAnalysisResult(srcItem, simpleFeature));
}
}
return result;
}
private void translateKaryotype(Item srcItem, Item tgtItem, Collection result)
throws ObjectStoreException {
tgtItem.addReference(config.getOrganismRef());
addReferencedItem(tgtItem, config.getEnsemblDataSet(), "evidence", true, "", false);
Item location = createLocation(srcItem, tgtItem, true); // seq_region
// seq_region.coord-sys
location.addAttribute(new Attribute("strand", "0"));
result.add(location);
if (srcItem.hasReference("seq_region")) {
Item seq = getSeqItem(srcItem.getReference("seq_region").getRefId(), true);
tgtItem.addReference(new Reference("chromosome", seq.getIdentifier()));
}
result.add(createSynonym(tgtItem.getIdentifier(), IDENTIFIER,
tgtItem.getAttribute(IDENTIFIER).getValue(), config.getEnsemblDataSrcRef())
);
}
private void translateTranscript(Item srcItem, Item tgtItem, Collection result, String srcNs)
throws ObjectStoreException {
tgtItem.addReference(config.getOrganismRef());
addReferencedItem(tgtItem,
config.getEnsemblDataSet(), "evidence", true, "", false);
// SimpleRelation between Gene and Transcript
result.add(createSimpleRelation(tgtItem.getReference("gene").getRefId(),
tgtItem.getIdentifier()));
// set transcript identifier to be ensembl stable id
if (!tgtItem.hasAttribute(IDENTIFIER)) {
Item stableId = getStableId("transcript", srcItem.getIdentifier(), srcNs);
if (stableId != null) {
moveField(stableId, tgtItem, "stable_id", IDENTIFIER);
} else {
tgtItem.addAttribute(new Attribute(IDENTIFIER,
srcItem.getIdentifier()));
}
}
Item translation = getItemViaItemPath(
srcItem, TRANSCRIPT_VIA_TRANSLATION, srcItemReader);
if (translation != null) {
// need to fetch translation to get identifier for CDS
// create CDS and reference from MRNA
Item cds = createItem(tgtNs + "CDS", "");
Item stableId = getStableId("translation",
translation.getIdentifier(), srcNs);
cds.setAttribute(IDENTIFIER,
stableId.getAttribute("stable_id").getValue() + "_CDS");
cds.addToCollection("polypeptides", translation.getIdentifier());
result.add(createSimpleRelation(cds.getIdentifier(),
translation.getIdentifier()));
Item cdsSyn = createSynonym(
cds.getIdentifier(),
IDENTIFIER,
cds.getAttribute(IDENTIFIER).getValue(),
config.getEnsemblDataSrcRef());
result.add(cdsSyn);
cds.addReference(config.getOrganismRef());
addReferencedItem(cds,
config.getEnsemblDataSet(), "evidence", true, "", false);
tgtItem.addToCollection("CDSs", cds);
result.add(createSimpleRelation(
tgtItem.getIdentifier(), cds.getIdentifier()));
result.add(cds);
} else {
LOG.debug("No Translation found for Transcript:" + tgtItem.getIdentifier());
}
}
private void translateRepeatFeature(Item srcItem, Item tgtItem, Collection result)
throws ObjectStoreException {
tgtItem.addReference(config.getOrganismRef());
addReferencedItem(tgtItem, config.getEnsemblDataSet(), "evidence", true, "", false);
result.add(createAnalysisResult(srcItem, tgtItem));
// analysis
result.add(createLocation(srcItem, tgtItem, true));
// seq_region
// seq_region.coord_system
promoteField(tgtItem, srcItem, "consensus", "repeat_consensus", "repeat_consensus");
// repeat_consensus
promoteField(tgtItem, srcItem, "type", "repeat_consensus", "repeat_class");
// repeat_consensus
promoteField(tgtItem, srcItem, IDENTIFIER, "repeat_consensus", "repeat_name");
//Create a more usable identifier field.
StringBuffer newIdBuff = new StringBuffer();
newIdBuff.append(tgtItem.getAttribute(IDENTIFIER).getValue());
newIdBuff.append("_");
Item seqRegItem = ItemHelper.convert(srcItemReader.getItemById(
srcItem.getReference("seq_region").getRefId()));
newIdBuff.append(seqRegItem.getAttribute("name").getValue());
newIdBuff.append(":");
newIdBuff.append(srcItem.getAttribute("seq_region_start").getValue());
newIdBuff.append("..");
newIdBuff.append(srcItem.getAttribute("seq_region_end").getValue());
tgtItem.removeAttribute(IDENTIFIER);
tgtItem.setAttribute(IDENTIFIER, newIdBuff.toString());
Item rfSyn = createSynonym(tgtItem.getIdentifier(), IDENTIFIER,
tgtItem.getAttribute(IDENTIFIER).getValue(), config.getEnsemblDataSrcRef());
result.add(rfSyn);
}
/**
* @param sourceItem - can be an exon or an exon_stable_id source db item.
* @param srcIsExonNotExonStableId - flag to distinguish between the 2 possible src items.
*
* @return a boolean indicating that the exon will be kept
* - hence we can store it and make a synonym for it
*
* @throws ObjectStoreException if there is a problem finding one of the related items.
* */
private boolean isExonToBeKept(Item sourceItem, boolean srcIsExonNotExonStableId)
throws ObjectStoreException {
int invalidETCount = 0;
int validETCount = 0;
Item srcItem;
if (srcIsExonNotExonStableId) {
srcItem = sourceItem;
} else {
srcItem = ItemHelper.convert(
srcItemReader.getItemById(sourceItem.getReference("exon").getRefId()));
}
List etList = getItemsViaItemPath(srcItem, EXON_VIA_EXON_TRANSCRIPT, srcItemReader);
//Loop over the transcripts for each exon to see if they are valid or not...
for (Iterator etIt = etList.iterator(); etIt.hasNext();) {
Item etNext = (Item) etIt.next();
Item tscrpt = ItemHelper.convert(srcItemReader.getItemById(
etNext.getReference("transcript").getRefId()));
//We only allow protein_coding types in...
String bioType = tscrpt.getAttribute("biotype").getValue();
if (!bioType.equalsIgnoreCase("bacterial_contaminant")) {
validETCount++;
} else {
invalidETCount++;
LOG.debug("Found an invalid biotype:" + bioType);
}
}
//Check to see if any of the exons are pointing to invalid transcripts...
if (validETCount == 0 && invalidETCount == 0) {
LOG.debug("Exon with no transcript found!" + (srcItem.hasAttribute(IDENTIFIER)
? srcItem.getAttribute(IDENTIFIER).getValue() : srcItem.getIdentifier()));
} else if (validETCount >= 1 && invalidETCount == 0) {
return true;
} else if (validETCount == 0 && invalidETCount >= 1) {
LOG.debug("Exon with an invalid transcript found!" + (srcItem.hasAttribute(IDENTIFIER)
? srcItem.getAttribute(IDENTIFIER).getValue() : srcItem.getIdentifier()));
} else if (validETCount >= 1 && invalidETCount >= 1) {
LOG.debug("Exon with valid and invalid transcripts found!"
+ (srcItem.hasAttribute(IDENTIFIER)
? srcItem.getAttribute(IDENTIFIER).getValue() : srcItem.getIdentifier()));
return true; //keep this - but log it
}
return false;
}
private Collection doXrefGeneHandling(Item srcItem, Item tgtItem, String srcNs)
throws ObjectStoreException {
Collection results = new HashSet();
if (srcItem.hasReference("display_xref") && srcItem.getReference("display_xref") != null) {
Item xref = ItemHelper.convert(
srcItemReader.getItemById(srcItem.getReference("display_xref").getRefId()));
Item extDb = ItemHelper.convert(
srcItemReader.getItemById(xref.getReference("external_db").getRefId()));
//If the db xref is ok for setting as the identifier attribute
if (config.getGeneXrefDbName().equalsIgnoreCase(
extDb.getAttribute("db_name").getValue())) {
String xrefDbAc = xref.getAttribute("dbprimary_acc").getValue();
tgtItem.addAttribute(new Attribute("organismDbId", xrefDbAc));
//create the synonym on this xref db id.
//NOTE: we treat it as an identifier not as a db 'accesion' for this purpose.
results.add(createProductSynonym(tgtItem, IDENTIFIER,
xrefDbAc, config.getEnsemblDataSrcRef()));
} else {
//if not - just use the default handling...
doDefaultGeneHandling(srcItem, tgtItem, srcNs);
}
//If this is ever null then there's a problem with the ensembl data!!!
Item stableIdItem = getStableId("gene", srcItem.getIdentifier(), srcNs);
// <- gene_stable_id.gene
String stableId = stableIdItem.getAttribute("stable_id").getValue();
tgtItem.addAttribute(new Attribute(IDENTIFIER, stableId));
//create a synonym based on the enseml stable gene id.
results.add(createProductSynonym(tgtItem, IDENTIFIER,
stableId, config.getEnsemblDataSrcRef()));
//Set up all the optional xref synonyms - if the gene is KNOWN it should
// have an ensembl xref to another db's accesssion for the same gene.
results.addAll(setXrefGeneSynonyms(srcItem, tgtItem));
} else {
LOG.debug("A GENE WITH NO XREF FOUND - RESORTING TO DEFAULT HANDLING FOR THIS ITEM!");
return doDefaultGeneHandling(srcItem, tgtItem, srcNs);
}
return results;
}
private Collection doDefaultGeneHandling(Item srcItem, Item tgtItem, String srcNs)
throws ObjectStoreException {
Collection results = new HashSet();
//If this is ever null then there's a problem with the ensembl data!!!
Item stableIdItem = getStableId("gene", srcItem.getIdentifier(), srcNs);
// <- gene_stable_id.gene
String stableId = stableIdItem.getAttribute("stable_id").getValue();
//Use the default approach of setting both the organismDbId & identifier to
// be the same value - the ensembl stable id.
tgtItem.addAttribute(new Attribute("organismDbId", stableId));
tgtItem.addAttribute(new Attribute(IDENTIFIER, stableId));
//Set up all the optional xref synonyms - if the gene is KNOWN it should
// have an ensembl xref to another db's accesssion for the same gene.
results.addAll(setXrefGeneSynonyms(srcItem, tgtItem));
return results;
}
private Item createSimpleRelation(String objectId, String subjectId) {
Item sr = createItem("SimpleRelation");
sr.setReference("object", objectId);
sr.setReference("subject", subjectId);
return sr;
}
/**
* Translate a "located" Item into an Item and a location
*
* @param srcItem the source Item
* @param tgtItem the target Item (after translation)
* @param srcItemIsChild true if srcItem should be subject of Location
* @return the location item
* @throws org.intermine.objectstore.ObjectStoreException
* when anything goes wrong.
*/
protected Item createLocation(Item srcItem, Item tgtItem,
boolean srcItemIsChild)
throws ObjectStoreException {
Item location = createItem(tgtNs + "Location", "");
if (srcItem.hasAttribute("seq_region_start")) {
moveField(srcItem, location, "seq_region_start", "start");
}
if (srcItem.hasAttribute("seq_region_end")) {
moveField(srcItem, location, "seq_region_end", "end");
}
location.addAttribute(new Attribute("startIsPartial", "false"));
location.addAttribute(new Attribute("endIsPartial", "false"));
if (srcItem.hasAttribute("seq_region_strand")) {
moveField(srcItem, location, "seq_region_strand", "strand");
}
if (srcItem.hasAttribute("phase")) {
moveField(srcItem, location, "phase", "phase");
}
if (srcItem.hasAttribute("end_phase")) {
moveField(srcItem, location, "end_phase", "endPhase");
}
if (srcItem.hasAttribute("ori")) {
moveField(srcItem, location, "ori", "strand");
}
if (srcItem.hasReference("seq_region")) {
LOG.debug("A seq_region was found for:" + srcItem.getClassName()
+ " id:" + srcItem.getIdentifier());
String refId = srcItem.getReference("seq_region").getRefId();
Item seq = getSeqItem(refId, true);
if (srcItemIsChild) {
addReferencedItem(tgtItem, location, "objects", true, "subject", false);
location.addReference(new Reference("object", seq.getIdentifier()));
} else {
addReferencedItem(tgtItem, location, "subjects", true, "object", false);
location.addReference(new Reference("subject", seq.getIdentifier()));
}
} else {
LOG.warn("No seq_region found for:" + srcItem.getClassName()
+ " id:" + srcItem.getIdentifier());
}
return location;
}
/**
* @param srcItem ensembl:marker
* @param tgtItem flymine:Marker
* @param srcNs source namespace
* @return set of locations
* @throws org.intermine.objectstore.ObjectStoreException
* when anything goes wrong.
*/
protected Set createLocations(Item srcItem, Item tgtItem, String srcNs)
throws ObjectStoreException {
Set result = new HashSet();
Set constraints = new HashSet();
String value = srcItem.getIdentifier();
constraints.add(new FieldNameAndValue(ObjectStoreItemPathFollowingImpl.CLASSNAME,
srcNs + "marker_feature", false));
constraints.add(new FieldNameAndValue("marker", value, true));
Item location;
for (Iterator i = srcItemReader.getItemsByDescription(constraints).iterator();
i.hasNext();) {
Item feature = ItemHelper.convert((org.intermine.model.fulldata.Item) i.next());
location = createLocation(feature, tgtItem, true);
location.addAttribute(new Attribute("strand", "0"));
result.add(location);
}
return result;
}
/**
* @param srcItem ensembl:marker
* @param tgtItem flymine:Marker
* @throws org.intermine.objectstore.ObjectStoreException
* when anything goes wrong.
*/
protected void setNameAttribute(Item srcItem, Item tgtItem) throws ObjectStoreException {
if (srcItem.hasReference("display_marker_synonym")) {
String markerSynRefId = srcItem.getReference("display_marker_synonym").getRefId();
org.intermine.model.fulldata.Item markerSyn = srcItemReader.getItemById(markerSynRefId);
//prefetch
if (markerSyn != null) {
if (markerSyn.getClassName().equals(srcNs + "marker_synonym")) {
Item synonym = ItemHelper.convert(markerSyn);
if (synonym.hasAttribute("name")) {
String name = synonym.getAttribute("name").getValue();
tgtItem.addAttribute(new Attribute("name", name));
}
} else {
LOG.warn("Found a " + markerSyn.getClassName()
+ " while looking for a marker_synonym");
}
} else {
LOG.warn("setNameAttribute() failed to find marker_synonym:" + markerSynRefId);
}
}
}
/**
* @param results the current collection of items to be stored.
* @param srcItem = assembly
* @return location item which reflects the relations between chromosome and contig,
* supercontig and contig, clone and contig
* @throws org.intermine.objectstore.ObjectStoreException
* when anything goes wrong.
*/
protected Item createAssemblyLocation(Collection results, Item srcItem)
throws ObjectStoreException {
int start, end, asmStart, cmpStart, cmpEnd; //asmEnd,
int contigLength, bioEntityLength, length;
String ori, contigId, bioEntityId;
contigId = srcItem.getReference("cmp_seq_region").getRefId();
bioEntityId = srcItem.getReference("asm_seq_region").getRefId();
Item contig = ItemHelper.convert(srcItemReader.getItemById(contigId));
Item bioEntity = ItemHelper.convert(srcItemReader.getItemById(bioEntityId));
contigLength = Integer.parseInt(contig.getAttribute("length").getValue());
bioEntityLength = Integer.parseInt(bioEntity.getAttribute("length").getValue());
asmStart = Integer.parseInt(srcItem.getAttribute("asm_start").getValue());
cmpStart = Integer.parseInt(srcItem.getAttribute("cmp_start").getValue());
//asmEnd = Integer.parseInt(srcItem.getAttribute("asm_end").getValue());
cmpEnd = Integer.parseInt(srcItem.getAttribute("cmp_end").getValue());
ori = srcItem.getAttribute("ori").getValue();
//some occasions in ensembl, e.g. contig AC087365.3.1.104495 ||AC144832.1.1.45226
//Chromosome, Supercontig have shorter length than contig
//need to truncate the longer part
if (contigLength < bioEntityLength) {
length = contigLength;
} else {
length = bioEntityLength;
}
if (ori.equals("1")) {
start = asmStart - cmpStart + 1;
end = start + length - 1;
} else {
if (cmpEnd == length) {
start = asmStart;
end = start + length - 1;
} else {
start = asmStart - (length - cmpEnd);
end = start + length - 1;
}
}
Item location = createItem(tgtNs + "Location", "");
location.addAttribute(new Attribute("start", Integer.toString(start)));
location.addAttribute(new Attribute("end", Integer.toString(end)));
location.addAttribute(new Attribute("startIsPartial", "false"));
location.addAttribute(new Attribute("endIsPartial", "false"));
location.addAttribute(new Attribute("strand", srcItem.getAttribute("ori").getValue()));
location.addReference(new Reference("subject",
(getSeqItem(contigId, true)).getIdentifier()));
location.addReference(new Reference("object",
(getSeqItem(bioEntityId, true)).getIdentifier()));
return location;
}
/**
* @param refId = refId for the seq_region
* @param createSynonym = indicates that we should create a synonym for this item if we can.
*
* @return seq item it could be chromosome, supercontig, clone or contig
* @throws org.intermine.objectstore.ObjectStoreException
* when anything goes wrong.
*/
protected Item getSeqItem(String refId, boolean createSynonym) throws ObjectStoreException {
Item seq = null;
Item seqRegion = ItemHelper.convert(srcItemReader.getItemById(refId));
if (seqIdMap.containsKey(refId)) {
seq = (Item) seqIdMap.get(refId);
} else {
String property = null;
if (seqRegion.hasReference("coord_system")) {
Item coord = ItemHelper.convert(srcItemReader.getItemById(
seqRegion.getReference("coord_system").getRefId()));
if (coord.hasAttribute("name")) {
property = coord.getAttribute("name").getValue();
}
}
if (property != null && !property.equals("")) {
//Produces the classname/type of the item, i.e. Chromosome, Contig, Chunk etc etc
String s = (property.substring(0, 1)).toUpperCase().concat(property.substring(1));
seq = createItem(tgtNs + s, "");
if (seqRegion.hasAttribute("name")) {
seq.addAttribute(new Attribute(IDENTIFIER,
seqRegion.getAttribute("name").getValue()));
}
if (seqRegion.hasAttribute("length")) {
seq.addAttribute(new Attribute("length",
seqRegion.getAttribute("length").getValue()));
}
addReferencedItem(seq, config.getEnsemblDataSet(), "evidence", true, "", false);
seqIdMap.put(refId, seq);
if (config.doStoreDna()) {
Item dna = getItemViaItemPath(seqRegion, SEQ_REGION_VIA_DNA, srcItemReader);
if (dna != null) {
seq.setReference("sequence", dna);
} else {
LOG.debug("NO DNA ITEM FOUND FOR THIS SEQ ITEM:" + seq.getIdentifier());
}
} else {
LOG.debug("SKIPPING doStoreDna for this org abbrev:" + config.getOrgAbbrev());
}
}
}
//If we need to create a Synonym and one hasn't been made for the seq item yet...
if (createSynonym && !itemId2SynMap.containsKey(
seq != null ? seq.getIdentifier() : "NO_ID_HERE!")) {
if (seq != null && seq.hasAttribute(IDENTIFIER)) {
Item seqSyn = createSynonym(
seq.getIdentifier(),
IDENTIFIER,
seq.getAttribute(IDENTIFIER).getValue(),
config.getEnsemblDataSrcRef());
itemId2SynMap.put(seq.getIdentifier(), seqSyn);
} else {
LOG.debug("Skipped creating a synonym for a seq item with no identifier:"
+ (seq != null ? seq.getClassName() + " id:"
+ seq.getIdentifier() : "seq is null"));
}
}
return seq;
}
/**
* Create an AnalysisResult pointed to by tgtItem evidence reference. Move srcItem
* analysis reference and score to new AnalysisResult.
*
* @param srcItem item in src namespace to move fields from
* @param tgtItem item that will reference AnalysisResult
* @return new AnalysisResult item
* @throws org.intermine.objectstore.ObjectStoreException
* when anything goes wrong.
*/
protected Item createAnalysisResult(Item srcItem, Item tgtItem)
throws ObjectStoreException {
Item result = createItem(tgtNs + "ComputationalResult", "");
if (srcItem.hasReference("analysis")) {
moveField(srcItem, result, "analysis", "analysis");
}
if (srcItem.hasAttribute("score")) {
moveField(srcItem, result, "score", "score");
}
result.addReference(config.getEnsemblDataSetRef());
ReferenceList evidence = new ReferenceList("evidence", Arrays.asList(new Object[]
{result.getIdentifier(), config.getEnsemblDataSet().getIdentifier()}));
tgtItem.addCollection(evidence);
return result;
}
/**
* Create comment class referenced by Gene item if there is a description field
* in gene
*
* @param srcItem gene
* @param tgtItem gene
* @return new comment item
* @throws org.intermine.objectstore.ObjectStoreException
* when anything goes wrong.
*/
protected Item createComment(Item srcItem, Item tgtItem)
throws ObjectStoreException {
Item comment = null;
if (srcItem.hasAttribute("description")) {
comment = createItem(tgtNs + "Comment", "");
moveField(srcItem, comment, "description", "text");
tgtItem.addReference(new Reference("comment", comment.getIdentifier()));
}
return comment;
}
/**
* Create a simpleFeature item depends on the logic_name attribute in analysis
* will become TRNA, or CpGIsland
*
* @param srcItem ensembl: simple_feature
* @return new simpleFeature item
* @throws org.intermine.objectstore.ObjectStoreException
* when anything goes wrong.
*/
protected Item createSimpleFeature(Item srcItem) throws ObjectStoreException {
Item simpleFeature = new Item();
if (srcItem.hasReference("analysis")) {
Item analysis = ItemHelper.convert(
srcItemReader.getItemById(srcItem.getReference("analysis").getRefId()));
if (analysis.hasAttribute("logic_name")) {
String name = analysis.getAttribute("logic_name").getValue();
if (name.equals("tRNAscan")) {
simpleFeature = createItem(tgtNs + "TRNA", "");
} else if (name.equals("CpG")) {
simpleFeature = createItem(tgtNs + "CpGIsland", "");
} else if (name.equals("Eponine")) {
simpleFeature = createItem(tgtNs + "TranscriptionStartSite", "");
//} else if (name.equals("FirstEF")) {
//5 primer exon and promoter including coding and noncoding
}
StringBuffer newIdBuff = new StringBuffer();
newIdBuff.append(name).append("_");
Item seqRegItem = ItemHelper.convert(srcItemReader.getItemById(
srcItem.getReference("seq_region").getRefId()));
newIdBuff.append(seqRegItem.getAttribute("name").getValue()).append(":");
newIdBuff.append(srcItem.getAttribute("seq_region_start").getValue()).append("..");
newIdBuff.append(srcItem.getAttribute("seq_region_end").getValue());
simpleFeature.addReference(config.getOrganismRef());
simpleFeature.addAttribute(new Attribute(IDENTIFIER, newIdBuff.toString()));
addReferencedItem(simpleFeature,
config.getEnsemblDataSet(), "evidence", true, "", false);
Item sfSyn = createSynonym(
simpleFeature.getIdentifier(),
IDENTIFIER,
newIdBuff.toString(),
config.getEnsemblDataSrcRef());
itemId2SynMap.put(simpleFeature.getIdentifier(), sfSyn);
}
}
return simpleFeature;
}
/**
* Finds external database accession numbers & labels in ensembl to set as Synonyms!
*
* Note: that only a small proportion of the genes in Anoph for example have these external
* references - it is usually only for KNOWN genes. Human on the other hand has >30k genes,
* most of which are known, and of them most have a valid Hugo reference.
*
* @param srcItem - it in source format ensembl:gene
* @param tgtItem - translate item flymine:Gene
*
* @return a set of Synonyms
* @throws org.intermine.objectstore.ObjectStoreException if problem retrieving any items
*/
protected Set setXrefGeneSynonyms(Item srcItem, Item tgtItem)
throws ObjectStoreException {
Set synonyms = new HashSet();
if (srcItem.hasReference("display_xref")) {
Item xref = ItemHelper.convert(srcItemReader.getItemById(
srcItem.getReference("display_xref").getRefId()));
//DBNAME
String dbname;
//look for the reference to an xref database - the external_db
if (xref.hasReference("external_db")) {
Reference extDbRef = xref.getReference("external_db");
Item extDb = ItemHelper.convert(srcItemReader.getItemById(extDbRef.getRefId()));
dbname = extDb.getAttribute("db_name").getValue();
} else {
LOG.debug("No external_db ref found for srcItem:" + srcItem.getIdentifier());
//return as we can't create a synonym without a source db xref
return synonyms;
}
//ACCESSION
String accession = null;
//look for a primary accession - if we have one we may be able to create a synonym
if (xref.hasAttribute("dbprimary_acc")) {
accession = xref.getAttribute("dbprimary_acc").getValue();
} else {
LOG.debug("No dbprimary_acc attr found for srcItem:" + srcItem.getIdentifier());
}
//check to see if we have a valid accession & dbname.
if (accession != null && !accession.equals(EMPTY_STRING)
&& dbname != null && !dbname.equals(EMPTY_STRING)) {
//If we have a valid xref for this dsname then we can create the synonym for the
// external database accession.
//NOTE: if the xref is being used as an alternative identifier it will already have
// a synonym with type 'identifier'.
if (config.containsXrefDataSourceNamed(dbname)) {
Reference extDbRef = config.getDataSrcRefByDataSrcName(dbname);
LOG.debug("Creating Synonym for dbname:" + dbname);
synonyms.add(createProductSynonym(tgtItem, "accession", accession, extDbRef));
} else {
LOG.debug("Skipped! Can't create a Synonym for db:" + dbname);
}
} else {
LOG.debug("Skipped! Bad dbprimary_acc:" + accession + " or dbname:" + dbname);
}
//SYMBOL
String symbol = null;
//look for the display label - since we might be able to use it as a symbol synonym.
if (xref.hasAttribute("display_label")) {
symbol = xref.getAttribute("display_label").getValue();
} else {
LOG.debug("No display_label attr found for srcItem:" + srcItem.getIdentifier());
}
//check to see if we have a valid display_lable (synonym) & dbname.
if (symbol != null && !symbol.equals(EMPTY_STRING)
&& dbname != null && !dbname.equals(EMPTY_STRING)) {
//Now check to see if we can create a synonym that represents a synbol as well.
if (config.containsXrefSymbolDataSourceNamed(dbname)) {
Reference extDbRef = config.getDataSrcRefByDataSrcName(dbname);
LOG.debug("Creating Symbol Synonym for dbname:" + dbname);
synonyms.add(createProductSynonym(tgtItem, "symbol", symbol, extDbRef));
} else {
LOG.debug("Skipped creating a Symbol Synonym for db:" + dbname);
}
} else {
LOG.debug("Skipped! Bad display_label:" + accession + " or dbname:" + dbname);
}
} else {
LOG.debug("Skipped! As no display_xref was found for srcItem:" + srcItem.getClassName()
+ " id:" + srcItem.getIdentifier());
}
return synonyms;
}
/**
* Creates a synonym for a gene/protein product.
* <p/>
* This method is for 1-M
*
* @param refItem - the item that the synonym needs to reference.
* @param type - i.e. accession or symbol
* @param value - the value of the type provided
* @param dsRef - which data source is this synonym from
* @see org.intermine.dataconversion.DataTranslator#addReferencedItem
*/
private Item createProductSynonym(Item refItem,
String type,
String value,
Reference dsRef) {
Item synonym = createSynonym(refItem.getIdentifier(), type, value, dsRef);
addReferencedItem(refItem, synonym, "synonyms", true, "subject", false);
return synonym;
}
/**
* Find stable_id for various ensembl type
*
* @param ensemblType could be gene, exon, transcript or translation
* it should be part of name before _stable_id
* @param identifier srcItem identifier, srcItem could be gene, exon, transcript/translation
* @param srcNs namespace of source model
* @return a set of Synonyms
* @throws org.intermine.objectstore.ObjectStoreException
* if problem retrieving items
*/
private Item getStableId(String ensemblType, String identifier, String srcNs) throws
ObjectStoreException {
Set constraints = new HashSet();
constraints.add(new FieldNameAndValue(ObjectStoreItemPathFollowingImpl.CLASSNAME,
srcNs + ensemblType + "_stable_id", false));
constraints.add(new FieldNameAndValue(ensemblType, identifier, true));
Iterator stableIds = srcItemReader.getItemsByDescription(constraints).iterator();
if (stableIds.hasNext()) {
return ItemHelper.convert((org.intermine.model.fulldata.Item) stableIds.next());
} else {
StringBuffer bob = new StringBuffer();
bob.append("getStableId unable to find a stableId for:");
bob.append(ensemblType);
bob.append("__");
bob.append(identifier);
bob.append("__");
bob.append(srcNs);
LOG.debug(bob.toString());
return null;
}
}
/**
* Create synonym item
*
* @param subjectId = synonym reference to subject
* @param type = synonym type
* @param value = synonym value
* @param ref = synonym reference to source
* @return synonym item
*/
private Item createSynonym(String subjectId, String type, String value, Reference ref) {
Item synonym = createItem(tgtNs + "Synonym", "");
synonym.addReference(new Reference("subject", subjectId));
synonym.addAttribute(new Attribute("type", type));
synonym.addAttribute(new Attribute("value", value));
synonym.addReference(ref);
return synonym;
}
/**
* Create synonym item for marker
*
* @param srcItem = marker_synonym
* marker_synonym in ensembl may have same marker_id, source and name
* but with different marker_synonym_id,
* check before create synonym
* @return synonym item
*/
private Item getMarkerSynonym(Item srcItem) {
Item synonym;
String subjectId = srcItem.getReference("marker").getRefId();
Set synonymSet;
synonymSet = (HashSet) markerSynonymMap.get(subjectId);
String value = srcItem.getAttribute("name").getValue();
Reference ref;
//TODO: NO HARDCODING!!!!!
if (srcItem.hasAttribute("source")) {
String source = srcItem.getAttribute("source").getValue();
if (source.equalsIgnoreCase("genbank")) {
ref = config.getDataSrcRefByDataSrcName("genbank");
} else if (source.equalsIgnoreCase("gdb")) {
ref = config.getDataSrcRefByDataSrcName("gdb");
} else if (source.equalsIgnoreCase("unists")) {
ref = config.getDataSrcRefByDataSrcName("unists");
} else {
ref = config.getEnsemblDataSrcRef();
}
} else {
ref = config.getEnsemblDataSrcRef();
}
int createItem = 1;
int flag;
if (synonymSet == null) {
synonym = createSynonym(subjectId, IDENTIFIER, value, ref);
synonymSet = new HashSet(Arrays.asList(new Object[]{synonym}));
markerSynonymMap.put(subjectId, synonymSet);
} else {
Iterator i = synonymSet.iterator();
while (i.hasNext()) {
Item item = (Item) i.next();
if (item.getReference("source").getRefId().equals(ref.getRefId())
&& item.getAttribute("value").getValue().equalsIgnoreCase(value)) {
flag = 0;
} else {
flag = 1;
}
createItem = createItem * flag;
}
if (createItem == 1) {
synonym = createSynonym(subjectId, IDENTIFIER, value, ref);
synonymSet.add(synonym);
markerSynonymMap.put(subjectId, synonymSet);
} else {
synonym = null;
}
}
return synonym;
}
/**
* @see org.flymine.task.DataTranslatorTask#execute
*/
public static Map getPrefetchDescriptors() {
Map paths = new HashMap();
String identifier = ObjectStoreItemPathFollowingImpl.IDENTIFIER;
String classname = ObjectStoreItemPathFollowingImpl.CLASSNAME;
//karyotype
ItemPrefetchDescriptor desc = new ItemPrefetchDescriptor("karyotype.seq_region");
desc.addConstraint(new ItemPrefetchConstraintDynamic("seq_region", identifier));
ItemPrefetchDescriptor desc1
= new ItemPrefetchDescriptor("karyotype.seq_region.coord_system");
desc1.addConstraint(new ItemPrefetchConstraintDynamic("coord_system", identifier));
desc.addPath(desc1);
paths.put("http://www.flymine.org/model/ensembl#karyotype",
Collections.singleton(desc));
//exon
Set descSet = new HashSet();
desc = new ItemPrefetchDescriptor("exon <- exon_transcript.exon");
desc.addConstraint(new ItemPrefetchConstraintDynamic(identifier, "exon"));
desc.addConstraint(new FieldNameAndValue(classname,
"http://www.flymine.org/model/ensembl#exon_transcript", false));
descSet.add(desc);
desc1 = new ItemPrefetchDescriptor("(<- exon_transcript.exon).transcript");
desc1.addConstraint(new ItemPrefetchConstraintDynamic("transcript", identifier));
desc.addPath(desc1);
descSet.add(desc);
desc = new ItemPrefetchDescriptor("exon <- exon_stable_id.exon");
desc.addConstraint(new ItemPrefetchConstraintDynamic(identifier, "exon"));
desc.addConstraint(new FieldNameAndValue(classname,
"http://www.flymine.org/model/ensembl#exon_stable_id", false));
descSet.add(desc);
desc = new ItemPrefetchDescriptor("exon.seq_region");
desc.addConstraint(new ItemPrefetchConstraintDynamic("seq_region", identifier));
desc1 = new ItemPrefetchDescriptor("exon.seq_region.coord_system");
desc1.addConstraint(new ItemPrefetchConstraintDynamic("coord_system", identifier));
desc.addPath(desc1);
descSet.add(desc);
paths.put("http://www.flymine.org/model/ensembl#exon", descSet);
//exon_stable_id
desc = new ItemPrefetchDescriptor("exon_stable_id.exon");
desc.addConstraint(new ItemPrefetchConstraintDynamic("exon", identifier));
paths.put("http://www.flymine.org/model/ensembl#exon_stable_id",
Collections.singleton(desc));
//gene
descSet = new HashSet();
desc = new ItemPrefetchDescriptor("gene <- gene_stable_id.gene");
desc.addConstraint(new ItemPrefetchConstraintDynamic(identifier, "gene"));
desc.addConstraint(new FieldNameAndValue(classname,
"http://www.flymine.org/model/ensembl#gene_stable_id", false));
descSet.add(desc);
desc = new ItemPrefetchDescriptor("gene.analysis");
desc.addConstraint(new ItemPrefetchConstraintDynamic("analysis", identifier));
descSet.add(desc);
desc = new ItemPrefetchDescriptor("gene.seq_region");
desc.addConstraint(new ItemPrefetchConstraintDynamic("seq_region", identifier));
desc1 = new ItemPrefetchDescriptor("gene.seq_region.coord_system");
desc1.addConstraint(new ItemPrefetchConstraintDynamic("coord_system", identifier));
desc.addPath(desc1);
descSet.add(desc);
desc = new ItemPrefetchDescriptor("gene.display_xref");
desc.addConstraint(new ItemPrefetchConstraintDynamic("display_xref", identifier));
desc1 = new ItemPrefetchDescriptor("gene.display_xref.external_db");
desc1.addConstraint(new ItemPrefetchConstraintDynamic("external_db", identifier));
desc.addPath(desc1);
descSet.add(desc);
paths.put("http://www.flymine.org/model/ensembl#gene", descSet);
//gene_stable_id
desc = new ItemPrefetchDescriptor("gene_stable_id.gene");
desc.addConstraint(new ItemPrefetchConstraintDynamic("gene", identifier));
paths.put("http://www.flymine.org/model/ensembl#gene_stable_id",
Collections.singleton(desc));
//transcript
descSet = new HashSet();
desc = new ItemPrefetchDescriptor("transcript <- translation.transcript");
desc.addConstraint(new ItemPrefetchConstraintDynamic(identifier, "transcript"));
desc.addConstraint(new FieldNameAndValue(classname,
"http://www.flymine.org/model/ensembl#translation", false));
descSet.add(desc);
desc = new ItemPrefetchDescriptor("transcript <- transcript_stable_id.transcript");
desc.addConstraint(new ItemPrefetchConstraintDynamic(identifier, "transcript"));
desc.addConstraint(new FieldNameAndValue(classname,
"http://www.flymine.org/model/ensembl#transcript_stable_id", false));
descSet.add(desc);
desc = new ItemPrefetchDescriptor("transcript.gene");
desc.addConstraint(new ItemPrefetchConstraintDynamic("gene", identifier));
descSet.add(desc);
desc = new ItemPrefetchDescriptor("transcript.seq_region");
desc.addConstraint(new ItemPrefetchConstraintDynamic("seq_region", identifier));
desc1 = new ItemPrefetchDescriptor("transcript.seq_region.coord_system");
desc1.addConstraint(new ItemPrefetchConstraintDynamic("coord_system", identifier));
desc.addPath(desc1);
descSet.add(desc);
paths.put("http://www.flymine.org/model/ensembl#transcript", descSet);
//transcript_stable_id
desc = new ItemPrefetchDescriptor("transcript_stable_id.transcript");
desc.addConstraint(new ItemPrefetchConstraintDynamic("transcript", identifier));
paths.put("http://www.flymine.org/model/ensembl#transcript_stable_id",
Collections.singleton(desc));
//translation
descSet = new HashSet();
desc = new ItemPrefetchDescriptor("translation <- translation_stable_id.translation");
desc.addConstraint(new ItemPrefetchConstraintDynamic(identifier, "translation"));
desc.addConstraint(new FieldNameAndValue(classname,
"http://www.flymine.org/model/ensembl#translation_stable_id", false));
descSet.add(desc);
desc = new ItemPrefetchDescriptor("translation.transcript");
desc.addConstraint(new ItemPrefetchConstraintDynamic("transcript", identifier));
descSet.add(desc);
desc1 = new ItemPrefetchDescriptor("translation.transcript.display_xref");
desc1.addConstraint(new ItemPrefetchConstraintDynamic("display_xref", identifier));
ItemPrefetchDescriptor desc2 =
new ItemPrefetchDescriptor("translation.transcript.display_xref.external_db");
desc2.addConstraint(new ItemPrefetchConstraintDynamic("external_db", identifier));
desc1.addPath(desc2);
desc.addPath(desc1);
descSet.add(desc);
paths.put("http://www.flymine.org/model/ensembl#translation", descSet);
//translation_stable_id
desc = new ItemPrefetchDescriptor("translation_stable_id.translation");
desc.addConstraint(new ItemPrefetchConstraintDynamic("translation", identifier));
paths.put("http://www.flymine.org/model/ensembl#translation_stable_id",
Collections.singleton(desc));
//repeat_feature
descSet = new HashSet();
desc = new ItemPrefetchDescriptor("repeat_feature.analysis");
desc.addConstraint(new ItemPrefetchConstraintDynamic("analysis", identifier));
descSet.add(desc);
desc = new ItemPrefetchDescriptor("repeat_feature.repeat_consensus");
desc.addConstraint(new ItemPrefetchConstraintDynamic("repeat_consensus", identifier));
descSet.add(desc);
desc = new ItemPrefetchDescriptor("repeat_feature.seq_region");
desc.addConstraint(new ItemPrefetchConstraintDynamic("seq_region", identifier));
desc1 = new ItemPrefetchDescriptor("repeat_feature.seq_region.coord_system");
desc1.addConstraint(new ItemPrefetchConstraintDynamic("coord_system", identifier));
desc.addPath(desc1);
descSet.add(desc);
paths.put("http://www.flymine.org/model/ensembl#repeat_feature", descSet);
//marker
descSet = new HashSet();
desc = new ItemPrefetchDescriptor("marker.display_marker_synonym");
desc.addConstraint(new ItemPrefetchConstraintDynamic("display_marker_synonym", identifier));
descSet.add(desc);
desc = new ItemPrefetchDescriptor("marker <- marker_synonym.marker");
desc.addConstraint(new ItemPrefetchConstraintDynamic(identifier, "marker"));
desc.addConstraint(new FieldNameAndValue(classname,
"http://www.flymine.org/model/ensembl#marker_synonym", false));
descSet.add(desc);
desc = new ItemPrefetchDescriptor("marker <- marker_feature.marker");
desc.addConstraint(new ItemPrefetchConstraintDynamic(identifier, "marker"));
desc.addConstraint(new FieldNameAndValue(classname,
"http://www.flymine.org/model/ensembl#marker_feature", false));
desc1 = new ItemPrefetchDescriptor("(<- marker_feature.marker).seq_region");
desc1.addConstraint(new ItemPrefetchConstraintDynamic("seq_region", identifier));
desc2 = new ItemPrefetchDescriptor("(<- marker_feature.marker).seq_region.coord_system");
desc2.addConstraint(new ItemPrefetchConstraintDynamic("coord_system", identifier));
desc1.addPath(desc2);
desc.addPath(desc1);
descSet.add(desc);
paths.put("http://www.flymine.org/model/ensembl#marker",
Collections.singleton(desc));
//assembly
descSet = new HashSet();
desc = new ItemPrefetchDescriptor("assembly.asm_seq_region");
desc.addConstraint(new ItemPrefetchConstraintDynamic("asm_seq_region", identifier));
desc2 = new ItemPrefetchDescriptor("assembly.asm_seq_region.coord_system");
desc2.addConstraint(new ItemPrefetchConstraintDynamic("coord_system", identifier));
desc.addPath(desc2);
descSet.add(desc);
desc = new ItemPrefetchDescriptor("assembly.cmp_seq_region");
desc.addConstraint(new ItemPrefetchConstraintDynamic("cmp_seq_region", identifier));
desc2 = new ItemPrefetchDescriptor("assembly.cmp_seq_region.coord_system");
desc2.addConstraint(new ItemPrefetchConstraintDynamic("coord_system", identifier));
desc.addPath(desc2);
descSet.add(desc);
paths.put("http://www.flymine.org/model/ensembl#assembly", descSet);
//seq_region
desc = new ItemPrefetchDescriptor("seq_region.coord_system");
desc.addConstraint(new ItemPrefetchConstraintDynamic("coord_system", identifier));
paths.put("http://www.flymine.org/model/ensembl#seq_region",
Collections.singleton(desc));
//simple_feature
descSet = new HashSet();
desc = new ItemPrefetchDescriptor("simple_feature.analysis");
desc.addConstraint(new ItemPrefetchConstraintDynamic("analysis", identifier));
descSet.add(desc);
desc = new ItemPrefetchDescriptor("simple_feature.seq_region");
desc.addConstraint(new ItemPrefetchConstraintDynamic("seq_region", identifier));
desc1 = new ItemPrefetchDescriptor("simple_feature.seq_region.coord_system");
desc1.addConstraint(new ItemPrefetchConstraintDynamic("coord_system", identifier));
desc.addPath(desc1);
descSet.add(desc);
paths.put("http://www.flymine.org/model/ensembl#simple_feature", descSet);
return paths;
}
/**
* Utility class to keep the contents of the ensembl_config file in for reference while the
* translator is running...
* */
class EnsemblConfig
{
private String orgAbbrev;
private Item organism = null;
private Reference organismRef = null;
private boolean useXrefDbsForGeneIdentifier;
private boolean storeDna;
private EnsemblPropsUtil propsUtil;
private Map dataSourceName2ItemMap;
private Map dataSourceName2RefMap;
private Item ensemblDataSrc;
private Reference ensemblDataSrcRef;
private Item ensemblDataSet;
private Reference ensemblDataSetRef;
private Set xrefDataSourceNames;
private String geneXrefDbName = null;
private Set xrefSymbolDataSourceNames;
/**
* Constructor.
*
* @param ensemblProps a represesntation of the ensembl_config file's contents.
* @param orgAbbrev A suitably short acronym to identify which ogransim to process.
* */
EnsemblConfig(Properties ensemblProps, String orgAbbrev) {
if (orgAbbrev == null || "".equals(orgAbbrev)) {
throw new RuntimeException(
"EnsemblConfig: must have the organism abbreviation set!");
}
this.orgAbbrev = orgAbbrev;
if (ensemblProps == null) {
throw new RuntimeException(
"EnsemblConfig: can't find any ensembl_config.properties!");
}
propsUtil = new EnsemblPropsUtil(ensemblProps);
Properties organismProps = propsUtil.stripStart(orgAbbrev, ensemblProps);
organism = createItem(tgtNs + "Organism", "");
organism.addAttribute(new Attribute("abbreviation", orgAbbrev));
organism.addAttribute(new Attribute("name",
organismProps.getProperty("organism.name")));
organism.addAttribute(new Attribute("taxonId",
organismProps.getProperty("organism.taxonId")));
organismRef = new Reference("organism", organism.getIdentifier());
//This boolean indicates that we want to use configurable identifier fields...
useXrefDbsForGeneIdentifier = Boolean.valueOf(
organismProps.getProperty("flag.useXrefDbsForGeneIdentifier")).booleanValue();
storeDna = Boolean.valueOf(
organismProps.getProperty("flag.storeDna")).booleanValue();
//Load up all the data source names that we will allow xref synonyms to be set for.
xrefDataSourceNames = new HashSet(propsUtil.getPropertiesStartingWith(
orgAbbrev + ".datasource.xref.synonym").values());
dataSourceName2ItemMap = new HashMap();
dataSourceName2RefMap = new HashMap();
initDataSourceAndDataSourceRefMaps();
initEnsemblDataSrc();
initEnsemblDataSet();
//try and load the props if we need to use custom gene identifiers - i.e. Hugo for Human
if (useXrefDbsForGeneIdentifier) {
geneXrefDbName = organismProps.getProperty("gene.identifier.xref.dataSourceName");
//if it aint set - complain!
if (geneXrefDbName == null) {
throw new RuntimeException(
"EnsemblConfig: gene.identifier.xref.dataSourceName property not set!");
}
if (!dataSourceName2ItemMap.containsKey(geneXrefDbName.toLowerCase())) {
throw new RuntimeException(
"EnsemblConfig(1): gene.identifier.xref.dataSourceName:"
+ geneXrefDbName + " has no matching common.datasource");
}
}
//Load up all the data source names that we will allow xref synonyms to be set for.
xrefSymbolDataSourceNames = new HashSet(propsUtil.getPropertiesStartingWith(
orgAbbrev + ".datasource.xref.synonym.symbol").values());
//Better check there's a matching data source for each of these!
for (Iterator symbolIt = xrefSymbolDataSourceNames.iterator(); symbolIt.hasNext(); ) {
Object nextSymbol = symbolIt.next();
if (!dataSourceName2ItemMap.containsKey(nextSymbol.toString().toLowerCase())) {
throw new RuntimeException(
"EnsemblConfig(2): datasource.xref.synonym.symbol:"
+ nextSymbol.toString() + " has no matching common.datasource");
}
}
}
private void initDataSourceAndDataSourceRefMaps() {
//Get the names of all the available datasources
Properties dsNames = propsUtil.getPropertiesStartingWith("common.datasource.name");
for (Iterator dsnIt = dsNames.values().iterator(); dsnIt.hasNext(); ) {
String dsName = dsnIt.next().toString().toLowerCase();
Properties dsnNextProps = propsUtil.getPropertiesStartingWith(
"common.datasource." + dsName);
Item nextDataSource = createItem(tgtNs + "DataSource", "");
nextDataSource.addAttribute(new Attribute("name", dsName));
nextDataSource.addAttribute(new Attribute("url",
dsnNextProps.getProperty("common.datasource."
+ dsName.toLowerCase() + ".url")));
nextDataSource.addAttribute(new Attribute("description",
dsnNextProps.getProperty("common.datasource."
+ dsName.toLowerCase() + ".description")));
dataSourceName2ItemMap.put(dsName.toLowerCase(), nextDataSource);
dataSourceName2RefMap.put(dsName.toLowerCase(),
new Reference("source", nextDataSource.getIdentifier()));
}
}
private void initEnsemblDataSrc() {
String ensembl = "ensembl";
if (hasDataSourceNamed(ensembl)) {
ensemblDataSrc = getDataSrcByName(ensembl);
ensemblDataSrcRef = getDataSrcRefByDataSrcName(ensembl);
} else {
throw new RuntimeException("!!! Ensembl DataSrc Not Found !!!");
}
}
private void initEnsemblDataSet() {
String propStem = orgAbbrev + ".ensembl.dataset";
Properties props = propsUtil.getPropertiesStartingWith(propStem);
ensemblDataSet = createItem(tgtNs + "DataSet", "");
ensemblDataSet.addAttribute(
new Attribute("title", props.getProperty(propStem + ".title")));
String dsName = props.getProperty(propStem + ".dataSourceName");
Item dataSrc = getDataSrcByName(dsName);
ensemblDataSet.addReference(new Reference("dataSource", dataSrc.getIdentifier()));
ensemblDataSetRef = new Reference("source", ensemblDataSet.getIdentifier());
}
//------------------------------------------------------------------------------------------
/**
* @return An abbreviated string representing the current organism.
*/
String getOrgAbbrev() {
return orgAbbrev;
}
/**
* @return The current Organism Item
*/
Item getOrganism() {
return organism;
}
/**
* @return A reference to the current organism
*/
Reference getOrganismRef() {
return organismRef;
}
/**
* @return Do we want to use any external db ids - i.e. SwissProt/Uniprot etc for Genes?
* */
boolean useXrefDbsForGeneIdentifier() {
return useXrefDbsForGeneIdentifier;
}
/**
* @return Do we want to get the DNA sequences now or later?
* */
boolean doStoreDna() {
return storeDna;
}
/**
* @return The name of the datasource where we want to get any xref dbid's from
* */
String getGeneXrefDbName() {
return geneXrefDbName;
}
/**
* @return Get's the Ensembl Data Source Item
* */
Item getEnsemblDataSrc() {
return ensemblDataSrc;
}
/**
* @return Get's a reference to the Ensembl Data Source Item
* */
Reference getEnsemblDataSrcRef() {
return ensemblDataSrcRef;
}
/**
* @return Gets the current Ensembl Data Set being processed.
* */
Item getEnsemblDataSet() {
return ensemblDataSet;
}
/**
* @return Gets a reference to the current Ensembl Data Set being processed.
* */
Reference getEnsemblDataSetRef() {
return ensemblDataSetRef;
}
/**
* @param xrefDataSourceName a data source name to check
*
* @return have we seen this xref data source name before
* */
boolean containsXrefDataSourceNamed(String xrefDataSourceName) {
return xrefDataSourceNames.contains(xrefDataSourceName);
}
/**
* @param xrefSymbolDataSourceName a data source name that we represents a symbol
*
* @return have we seen this data source name before
* */
boolean containsXrefSymbolDataSourceNamed(String xrefSymbolDataSourceName) {
return xrefSymbolDataSourceNames.contains(xrefSymbolDataSourceName);
}
/**
* @param dataSrcName a data source name to check for
*
* @return have we seen this data source name before
* */
boolean hasDataSourceNamed(String dataSrcName) {
return dataSourceName2ItemMap.containsKey(dataSrcName.toLowerCase());
}
/**
* @param dataSrcName A named data source of interest
*
* @return a data source item
*
* @throws RuntimeException if we can't find the datasource - check the config file
* */
Item getDataSrcByName(String dataSrcName) {
if (hasDataSourceNamed(dataSrcName.toLowerCase())) {
return (Item) dataSourceName2ItemMap.get(dataSrcName.toLowerCase());
}
throw new RuntimeException("Can't find a data source named:" + dataSrcName);
}
/**
* @param dataSrcName name of a data source to look for the reference of
*
* @return a boolean indicating if we have found the reference or not
* */
boolean hasDataSrcRefForDataSrcNamed(String dataSrcName) {
return dataSourceName2RefMap.containsKey(dataSrcName.toLowerCase());
}
/**
* @param dataSrcName name of a data source to look for the reference of
*
* @return A reference to the datasource
*
* @throws RuntimeException if we can't find the reference
* */
Reference getDataSrcRefByDataSrcName(String dataSrcName) throws RuntimeException {
if (hasDataSrcRefForDataSrcNamed(dataSrcName.toLowerCase())) {
return (Reference) dataSourceName2RefMap.get(dataSrcName.toLowerCase());
}
throw new RuntimeException("Can't find a reference for a data source named:"
+ dataSrcName);
}
/**
* @return provides an Iterator of all the known data source items.
* */
Iterator getDataSrcItemIterator() {
return dataSourceName2ItemMap.values().iterator();
}
}
}
| flymine/model/ensembl/src/java/org/flymine/dataconversion/EnsemblDataTranslator.java | package org.flymine.dataconversion;
/*
* Copyright (C) 2002-2005 FlyMine
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. See the LICENSE file for more
* information or http://www.gnu.org/copyleft/lesser.html.
*
*/
import org.intermine.dataconversion.*;
import org.intermine.metadata.Model;
import org.intermine.xml.full.*;
import org.intermine.objectstore.ObjectStoreException;
import org.intermine.InterMineException;
import org.intermine.util.XmlUtil;
//import org.intermine.util.PropertiesUtil;
import org.apache.log4j.Logger;
import java.util.*;
/**
* Convert Ensembl data in fulldata Item format conforming to a source OWL definition
* to fulldata Item format conforming to InterMine OWL definition.
*
* @author Andrew Varley
* @author Mark Woodbridge
* @author Peter McLaren
*/
public class EnsemblDataTranslator extends DataTranslator
{
/**
* USEFULL CONSTANT
* */
public static final String EMPTY_STRING = "";
/**
* USEFULL CONSTANT
* */
public static final String IDENTIFIER = "identifier";
protected static final String PATH_NAME_SPACE = "http://www.flymine.org/model/ensembl#";
protected static final ItemPath TRANSCRIPT_VIA_TRANSLATION =
new ItemPath("(transcript <- translation.transcript)", PATH_NAME_SPACE);
protected static final ItemPath EXON_VIA_EXON_TRANSCRIPT =
new ItemPath("(exon <- exon_transcript.exon)", PATH_NAME_SPACE);
protected static final ItemPath SEQ_REGION_VIA_DNA =
new ItemPath("(seq_region <- dna.seq_region)", PATH_NAME_SPACE);
protected static final ItemPath MARKER_VIA_MARKER_SYNONYM =
new ItemPath("(marker <- marker_synonym.marker)", PATH_NAME_SPACE);
protected static final Logger LOG = Logger.getLogger(EnsemblDataTranslator.class);
private Map seqIdMap = new HashMap();
private Map itemId2SynMap = new HashMap();
private Map markerSynonymMap = new HashMap();
private String srcNs;
//Holds all the information from the Ensembl Config file - i.e. datasources & sets
private EnsemblConfig config;
/**
* @param srcItemReader Our source item provider.
* @param mergeSpec The contents of our mapping spec.
* @param srcModel The data model we are translating items from.
* @param tgtModel The data model we are translating items into.
* @param ensemblProps Properties that are organism specific.
* @param orgAbbrev A suitably short acronym to identify which ogransim to process; 'HS' = Human
*/
public EnsemblDataTranslator(ItemReader srcItemReader,
Properties mergeSpec,
Model srcModel,
Model tgtModel,
Properties ensemblProps,
String orgAbbrev) {
super(srcItemReader, mergeSpec, srcModel, tgtModel);
config = new EnsemblConfig(ensemblProps, orgAbbrev);
}
/**
* @see org.intermine.dataconversion.DataTranslator#translate
*/
public void translate(ItemWriter tgtItemWriter)
throws ObjectStoreException, InterMineException {
super.translate(tgtItemWriter);
tgtItemWriter.store(ItemHelper.convert(config.getOrganism()));
tgtItemWriter.store(ItemHelper.convert(config.getEnsemblDataSet()));
for (Iterator dsIt = config.getDataSrcItemIterator(); dsIt.hasNext(); ) {
tgtItemWriter.store(ItemHelper.convert((Item) dsIt.next()));
}
for (Iterator seqSynIt = itemId2SynMap.values().iterator(); seqSynIt.hasNext();) {
tgtItemWriter.store(ItemHelper.convert((Item) seqSynIt.next()));
}
}
/**
* @see org.intermine.dataconversion.DataTranslator#translateItem
*/
protected Collection translateItem(Item srcItem)
throws ObjectStoreException, InterMineException {
Collection result = new HashSet();
srcNs = XmlUtil.getNamespaceFromURI(srcItem.getClassName());
String srcItemClassName = XmlUtil.getFragmentFromURI(srcItem.getClassName());
Collection translated = super.translateItem(srcItem);
if (translated != null) {
for (Iterator i = translated.iterator(); i.hasNext();) {
boolean storeTgtItem = true;
Item tgtItem = (Item) i.next();
if ("dna".equals(srcItemClassName)) {
if (config.doStoreDna()) {
if (srcItem.hasAttribute("sequence")) {
int seqLen = srcItem.getAttribute("sequence").getValue().length();
tgtItem.setAttribute("length", Integer.toString(seqLen));
} else {
LOG.warn("A DNA item has no sequence! " + srcItem.getIdentifier());
}
} else {
LOG.debug("Skipping a DNA item! " + srcItem.getIdentifier());
storeTgtItem = false;
}
} else if ("karyotype".equals(srcItemClassName)) {
translateKaryotype(srcItem, tgtItem, result);
} else if ("exon".equals(srcItemClassName)) {
//Skip this exon if it points to invalid transcripts!
if (!isExonToBeKept(srcItem, true)) {
LOG.debug("isExonToBeKept false for Exon:" + srcItem.getIdentifier());
return result;
}
tgtItem.addReference(config.getOrganismRef());
Item stableId = getStableId("exon", srcItem.getIdentifier(), srcNs);
// <- exon_stable_id.exon
if (stableId != null) {
moveField(stableId, tgtItem, "stable_id", IDENTIFIER);
}
addReferencedItem(tgtItem, config.getEnsemblDataSet(),
"evidence", true, "", false);
Item location = createLocation(srcItem, tgtItem, true); // seq_region
// seq_region.coord-sys
result.add(location);
} else if ("gene".equals(srcItemClassName)) {
tgtItem.addReference(config.getOrganismRef());
addReferencedItem(tgtItem, config.getEnsemblDataSet(),
"evidence", true, "", false);
Item comment = createComment(srcItem, tgtItem);
if (comment != null) {
result.add(comment);
}
Item location = createLocation(srcItem, tgtItem, true); // seq_region
// seq_region.coord-sys
result.add(location);
Item anaResult = createAnalysisResult(srcItem, tgtItem); // analysis
result.add(anaResult);
// the default gene organismDbId should be its stable id (or identifier if none)
//i.e. for anoph they are the same, but for human they are differant
//note: the organismDbId is effecivly what we choose as a primary accession
// and thus may differ from what we want to assign as the identifier...
if (config.useXrefDbsForGeneIdentifier()) {
result.addAll(doXrefGeneHandling(srcItem, tgtItem, srcNs));
} else {
result.addAll(doDefaultGeneHandling(srcItem, tgtItem, srcNs));
}
} else if ("transcript".equals(srcItemClassName)) {
translateTranscript(srcItem, tgtItem, result, srcNs);
} else if ("translation".equals(srcItemClassName)) {
tgtItem.addReference(config.getOrganismRef());
// if no identifier set the identifier as name (primary key)
if (!tgtItem.hasAttribute(IDENTIFIER)) {
Item stableId = getStableId("translation", srcItem.getIdentifier(), srcNs);
// <- transcript_stable_id.transcript
if (stableId != null) {
moveField(stableId, tgtItem, "stable_id", IDENTIFIER);
} else {
tgtItem.addAttribute(
new Attribute(IDENTIFIER, srcItem.getIdentifier()));
}
}
// stable_ids become syonyms, need ensembl DataSet as evidence
} else if (srcItemClassName.endsWith("_stable_id")) {
//check to see if the exons point to valid transcripts before making a synonym.
if (srcItemClassName.startsWith("exon")) {
//Skip this exon if it points to invalid transcripts!
if (!isExonToBeKept(srcItem, false)) {
return result;
}
}
tgtItem.addToCollection("evidence", config.getEnsemblDataSet());
tgtItem.addReference(config.getEnsemblDataSrcRef());
tgtItem.addAttribute(new Attribute("type", IDENTIFIER));
} else if ("repeat_feature".equals(srcItemClassName)) {
translateRepeatFeature(srcItem, tgtItem, result);
// repeat_consensus
} else if ("marker".equals(srcItemClassName)) {
tgtItem.addReference(config.getOrganismRef());
//is there an identifier set?
if (!srcItem.hasAttribute("identifier")) {
//ok try and look up any related marker_synonym items...
}
addReferencedItem(tgtItem,
config.getEnsemblDataSet(), "evidence", true, "", false);
Set locations = createLocations(srcItem, tgtItem, srcNs);
// <- marker_feature.marker
// (<- marker_feature.marker).seq_region
// (<- marker_feature.marker).seq_region.coord_system
//List locationIds = new ArrayList();
for (Iterator j = locations.iterator(); j.hasNext();) {
Item location = (Item) j.next();
//locationIds.add(location.getIdentifier());
result.add(location);
}
setNameAttribute(srcItem, tgtItem);
// display_marker_synonym
}
if (storeTgtItem) {
result.add(tgtItem);
}
}
} else if ("marker_synonym".equals(srcItemClassName)) {
Item synonym = getMarkerSynonym(srcItem);
if (synonym != null) {
result.add(synonym);
}
// assembly maps to null but want to create location on a supercontig
} else if ("assembly".equals(srcItemClassName)) {
Item location = createAssemblyLocation(result, srcItem);
result.add(location);
// seq_region map to null, become Chromosome, Supercontig, Clone and Contig respectively
} else if ("seq_region".equals(srcItemClassName)) {
Item seq = getSeqItem(srcItem.getIdentifier(), true);
seq.addReference(config.getOrganismRef());
result.add(seq);
//simple_feature map to null, become TRNA/CpGIsland depending on analysis_id(logic_name)
} else if ("simple_feature".equals(srcItemClassName)) {
Item simpleFeature = createSimpleFeature(srcItem);
if (simpleFeature.getIdentifier() != null
&& !simpleFeature.getIdentifier().equals("")) {
result.add(simpleFeature);
result.add(createLocation(srcItem, simpleFeature, true));
result.add(createAnalysisResult(srcItem, simpleFeature));
}
}
return result;
}
private void translateKaryotype(Item srcItem, Item tgtItem, Collection result)
throws ObjectStoreException {
tgtItem.addReference(config.getOrganismRef());
addReferencedItem(tgtItem, config.getEnsemblDataSet(), "evidence", true, "", false);
Item location = createLocation(srcItem, tgtItem, true); // seq_region
// seq_region.coord-sys
location.addAttribute(new Attribute("strand", "0"));
result.add(location);
if (srcItem.hasReference("seq_region")) {
Item seq = getSeqItem(srcItem.getReference("seq_region").getRefId(), true);
tgtItem.addReference(new Reference("chromosome", seq.getIdentifier()));
}
result.add(createSynonym(tgtItem.getIdentifier(), IDENTIFIER,
tgtItem.getAttribute(IDENTIFIER).getValue(), config.getEnsemblDataSrcRef())
);
}
private void translateTranscript(Item srcItem, Item tgtItem, Collection result, String srcNs)
throws ObjectStoreException {
tgtItem.addReference(config.getOrganismRef());
addReferencedItem(tgtItem,
config.getEnsemblDataSet(), "evidence", true, "", false);
// SimpleRelation between Gene and Transcript
result.add(createSimpleRelation(tgtItem.getReference("gene").getRefId(),
tgtItem.getIdentifier()));
// set transcript identifier to be ensembl stable id
if (!tgtItem.hasAttribute(IDENTIFIER)) {
Item stableId = getStableId("transcript", srcItem.getIdentifier(), srcNs);
if (stableId != null) {
moveField(stableId, tgtItem, "stable_id", IDENTIFIER);
} else {
tgtItem.addAttribute(new Attribute(IDENTIFIER,
srcItem.getIdentifier()));
}
}
Item translation = getItemViaItemPath(
srcItem, TRANSCRIPT_VIA_TRANSLATION, srcItemReader);
if (translation != null) {
// need to fetch translation to get identifier for CDS
// create CDS and reference from MRNA
Item cds = createItem(tgtNs + "CDS", "");
Item stableId = getStableId("translation",
translation.getIdentifier(), srcNs);
cds.setAttribute(IDENTIFIER,
stableId.getAttribute("stable_id").getValue() + "_CDS");
cds.addToCollection("polypeptides", translation.getIdentifier());
result.add(createSimpleRelation(cds.getIdentifier(),
translation.getIdentifier()));
Item cdsSyn = createSynonym(
cds.getIdentifier(),
IDENTIFIER,
cds.getAttribute(IDENTIFIER).getValue(),
config.getEnsemblDataSrcRef());
result.add(cdsSyn);
cds.addReference(config.getOrganismRef());
addReferencedItem(cds,
config.getEnsemblDataSet(), "evidence", true, "", false);
tgtItem.addToCollection("CDSs", cds);
result.add(createSimpleRelation(
tgtItem.getIdentifier(), cds.getIdentifier()));
result.add(cds);
} else {
LOG.debug("No Translation found for Transcript:" + tgtItem.getIdentifier());
}
}
private void translateRepeatFeature(Item srcItem, Item tgtItem, Collection result)
throws ObjectStoreException {
tgtItem.addReference(config.getOrganismRef());
addReferencedItem(tgtItem, config.getEnsemblDataSet(), "evidence", true, "", false);
result.add(createAnalysisResult(srcItem, tgtItem));
// analysis
result.add(createLocation(srcItem, tgtItem, true));
// seq_region
// seq_region.coord_system
promoteField(tgtItem, srcItem, "consensus", "repeat_consensus", "repeat_consensus");
// repeat_consensus
promoteField(tgtItem, srcItem, "type", "repeat_consensus", "repeat_class");
// repeat_consensus
promoteField(tgtItem, srcItem, IDENTIFIER, "repeat_consensus", "repeat_name");
//Create a more usable identifier field.
StringBuffer newIdBuff = new StringBuffer();
newIdBuff.append(tgtItem.getAttribute(IDENTIFIER).getValue());
newIdBuff.append("_");
Item seqRegItem = ItemHelper.convert(srcItemReader.getItemById(
srcItem.getReference("seq_region").getRefId()));
newIdBuff.append(seqRegItem.getAttribute("name").getValue());
newIdBuff.append(":");
newIdBuff.append(srcItem.getAttribute("seq_region_start").getValue());
newIdBuff.append("..");
newIdBuff.append(srcItem.getAttribute("seq_region_end").getValue());
tgtItem.removeAttribute(IDENTIFIER);
tgtItem.setAttribute(IDENTIFIER, newIdBuff.toString());
Item rfSyn = createSynonym(tgtItem.getIdentifier(), IDENTIFIER,
tgtItem.getAttribute(IDENTIFIER).getValue(), config.getEnsemblDataSrcRef());
result.add(rfSyn);
}
/**
* @param sourceItem - can be an exon or an exon_stable_id source db item.
* @param srcIsExonNotExonStableId - flag to distinguish between the 2 possible src items.
*
* @return a boolean indicating that the exon will be kept
* - hence we can store it and make a synonym for it
*
* @throws ObjectStoreException if there is a problem finding one of the related items.
* */
private boolean isExonToBeKept(Item sourceItem, boolean srcIsExonNotExonStableId)
throws ObjectStoreException {
int invalidETCount = 0;
int validETCount = 0;
Item srcItem;
if (srcIsExonNotExonStableId) {
srcItem = sourceItem;
} else {
srcItem = ItemHelper.convert(
srcItemReader.getItemById(sourceItem.getReference("exon").getRefId()));
}
List etList = getItemsViaItemPath(srcItem, EXON_VIA_EXON_TRANSCRIPT, srcItemReader);
//Loop over the transcripts for each exon to see if they are valid or not...
for (Iterator etIt = etList.iterator(); etIt.hasNext();) {
Item etNext = (Item) etIt.next();
Item tscrpt = ItemHelper.convert(srcItemReader.getItemById(
etNext.getReference("transcript").getRefId()));
//We only allow protein_coding types in...
String bioType = tscrpt.getAttribute("biotype").getValue();
if (!bioType.equalsIgnoreCase("bacterial_contaminant")) {
validETCount++;
} else {
invalidETCount++;
LOG.debug("Found an invalid biotype:" + bioType);
}
}
//Check to see if any of the exons are pointing to invalid transcripts...
if (validETCount == 0 && invalidETCount == 0) {
LOG.debug("Exon with no transcript found!" + (srcItem.hasAttribute(IDENTIFIER)
? srcItem.getAttribute(IDENTIFIER).getValue() : srcItem.getIdentifier()));
} else if (validETCount >= 1 && invalidETCount == 0) {
return true;
} else if (validETCount == 0 && invalidETCount >= 1) {
LOG.debug("Exon with an invalid transcript found!" + (srcItem.hasAttribute(IDENTIFIER)
? srcItem.getAttribute(IDENTIFIER).getValue() : srcItem.getIdentifier()));
} else if (validETCount >= 1 && invalidETCount >= 1) {
LOG.debug("Exon with valid and invalid transcripts found!"
+ (srcItem.hasAttribute(IDENTIFIER)
? srcItem.getAttribute(IDENTIFIER).getValue() : srcItem.getIdentifier()));
return true; //keep this - but log it
}
return false;
}
private Collection doXrefGeneHandling(Item srcItem, Item tgtItem, String srcNs)
throws ObjectStoreException {
Collection results = new HashSet();
if (srcItem.hasReference("display_xref") && srcItem.getReference("display_xref") != null) {
Item xref = ItemHelper.convert(
srcItemReader.getItemById(srcItem.getReference("display_xref").getRefId()));
Item extDb = ItemHelper.convert(
srcItemReader.getItemById(xref.getReference("external_db").getRefId()));
//If the db xref is ok for setting as the identifier attribute
if (config.getGeneXrefDbName().equalsIgnoreCase(
extDb.getAttribute("db_name").getValue())) {
String xrefDbAc = xref.getAttribute("dbprimary_acc").getValue();
tgtItem.addAttribute(new Attribute("organismDbId", xrefDbAc));
//create the synonym on this xref db id.
//NOTE: we treat it as an identifier not as a db 'accesion' for this purpose.
results.add(createProductSynonym(tgtItem, IDENTIFIER,
xrefDbAc, config.getEnsemblDataSrcRef()));
} else {
//if not - just use the default handling...
doDefaultGeneHandling(srcItem, tgtItem, srcNs);
}
//If this is ever null then there's a problem with the ensembl data!!!
Item stableIdItem = getStableId("gene", srcItem.getIdentifier(), srcNs);
// <- gene_stable_id.gene
String stableId = stableIdItem.getAttribute("stable_id").getValue();
tgtItem.addAttribute(new Attribute(IDENTIFIER, stableId));
//create a synonym based on the enseml stable gene id.
results.add(createProductSynonym(tgtItem, IDENTIFIER,
stableId, config.getEnsemblDataSrcRef()));
//Set up all the optional xref synonyms - if the gene is KNOWN it should
// have an ensembl xref to another db's accesssion for the same gene.
results.addAll(setXrefGeneSynonyms(srcItem, tgtItem));
} else {
LOG.debug("A GENE WITH NO XREF FOUND - RESORTING TO DEFAULT HANDLING FOR THIS ITEM!");
return doDefaultGeneHandling(srcItem, tgtItem, srcNs);
}
return results;
}
private Collection doDefaultGeneHandling(Item srcItem, Item tgtItem, String srcNs)
throws ObjectStoreException {
Collection results = new HashSet();
//If this is ever null then there's a problem with the ensembl data!!!
Item stableIdItem = getStableId("gene", srcItem.getIdentifier(), srcNs);
// <- gene_stable_id.gene
String stableId = stableIdItem.getAttribute("stable_id").getValue();
//Use the default approach of setting both the organismDbId & identifier to
// be the same value - the ensembl stable id.
tgtItem.addAttribute(new Attribute("organismDbId", stableId));
tgtItem.addAttribute(new Attribute(IDENTIFIER, stableId));
//Set up all the optional xref synonyms - if the gene is KNOWN it should
// have an ensembl xref to another db's accesssion for the same gene.
results.addAll(setXrefGeneSynonyms(srcItem, tgtItem));
return results;
}
private Item createSimpleRelation(String objectId, String subjectId) {
Item sr = createItem("SimpleRelation");
sr.setReference("object", objectId);
sr.setReference("subject", subjectId);
return sr;
}
/**
* Translate a "located" Item into an Item and a location
*
* @param srcItem the source Item
* @param tgtItem the target Item (after translation)
* @param srcItemIsChild true if srcItem should be subject of Location
* @return the location item
* @throws org.intermine.objectstore.ObjectStoreException
* when anything goes wrong.
*/
protected Item createLocation(Item srcItem, Item tgtItem,
boolean srcItemIsChild)
throws ObjectStoreException {
Item location = createItem(tgtNs + "Location", "");
if (srcItem.hasAttribute("seq_region_start")) {
moveField(srcItem, location, "seq_region_start", "start");
}
if (srcItem.hasAttribute("seq_region_end")) {
moveField(srcItem, location, "seq_region_end", "end");
}
location.addAttribute(new Attribute("startIsPartial", "false"));
location.addAttribute(new Attribute("endIsPartial", "false"));
if (srcItem.hasAttribute("seq_region_strand")) {
moveField(srcItem, location, "seq_region_strand", "strand");
}
if (srcItem.hasAttribute("phase")) {
moveField(srcItem, location, "phase", "phase");
}
if (srcItem.hasAttribute("end_phase")) {
moveField(srcItem, location, "end_phase", "endPhase");
}
if (srcItem.hasAttribute("ori")) {
moveField(srcItem, location, "ori", "strand");
}
if (srcItem.hasReference("seq_region")) {
LOG.debug("A seq_region was found for:" + srcItem.getClassName()
+ " id:" + srcItem.getIdentifier());
String refId = srcItem.getReference("seq_region").getRefId();
Item seq = getSeqItem(refId, true);
if (srcItemIsChild) {
addReferencedItem(tgtItem, location, "objects", true, "subject", false);
location.addReference(new Reference("object", seq.getIdentifier()));
} else {
addReferencedItem(tgtItem, location, "subjects", true, "object", false);
location.addReference(new Reference("subject", seq.getIdentifier()));
}
} else {
LOG.warn("No seq_region found for:" + srcItem.getClassName()
+ " id:" + srcItem.getIdentifier());
}
return location;
}
/**
* @param srcItem ensembl:marker
* @param tgtItem flymine:Marker
* @param srcNs source namespace
* @return set of locations
* @throws org.intermine.objectstore.ObjectStoreException
* when anything goes wrong.
*/
protected Set createLocations(Item srcItem, Item tgtItem, String srcNs)
throws ObjectStoreException {
Set result = new HashSet();
Set constraints = new HashSet();
String value = srcItem.getIdentifier();
constraints.add(new FieldNameAndValue(ObjectStoreItemPathFollowingImpl.CLASSNAME,
srcNs + "marker_feature", false));
constraints.add(new FieldNameAndValue("marker", value, true));
Item location;
for (Iterator i = srcItemReader.getItemsByDescription(constraints).iterator();
i.hasNext();) {
Item feature = ItemHelper.convert((org.intermine.model.fulldata.Item) i.next());
location = createLocation(feature, tgtItem, true);
location.addAttribute(new Attribute("strand", "0"));
result.add(location);
}
return result;
}
/**
* @param srcItem ensembl:marker
* @param tgtItem flymine:Marker
* @throws org.intermine.objectstore.ObjectStoreException
* when anything goes wrong.
*/
protected void setNameAttribute(Item srcItem, Item tgtItem) throws ObjectStoreException {
if (srcItem.hasReference("display_marker_synonym")) {
String markerSynRefId = srcItem.getReference("display_marker_synonym").getRefId();
org.intermine.model.fulldata.Item markerSyn = srcItemReader.getItemById(markerSynRefId);//prefetch
if (markerSyn != null) {
if (markerSyn.getClassName().equals(srcNs + "marker_synonym")) {
Item synonym = ItemHelper.convert(markerSyn);
if (synonym.hasAttribute("name")) {
String name = synonym.getAttribute("name").getValue();
tgtItem.addAttribute(new Attribute("name", name));
}
} else {
LOG.warn("Found a " + markerSyn.getClassName()
+ " while looking for a marker_synonym");
}
} else {
LOG.warn("setNameAttribute() failed to find marker_synonym:" + markerSynRefId);
}
}
}
/**
* @param results the current collection of items to be stored.
* @param srcItem = assembly
* @return location item which reflects the relations between chromosome and contig,
* supercontig and contig, clone and contig
* @throws org.intermine.objectstore.ObjectStoreException
* when anything goes wrong.
*/
protected Item createAssemblyLocation(Collection results, Item srcItem)
throws ObjectStoreException {
int start, end, asmStart, cmpStart, cmpEnd; //asmEnd,
int contigLength, bioEntityLength, length;
String ori, contigId, bioEntityId;
contigId = srcItem.getReference("cmp_seq_region").getRefId();
bioEntityId = srcItem.getReference("asm_seq_region").getRefId();
Item contig = ItemHelper.convert(srcItemReader.getItemById(contigId));
Item bioEntity = ItemHelper.convert(srcItemReader.getItemById(bioEntityId));
contigLength = Integer.parseInt(contig.getAttribute("length").getValue());
bioEntityLength = Integer.parseInt(bioEntity.getAttribute("length").getValue());
asmStart = Integer.parseInt(srcItem.getAttribute("asm_start").getValue());
cmpStart = Integer.parseInt(srcItem.getAttribute("cmp_start").getValue());
//asmEnd = Integer.parseInt(srcItem.getAttribute("asm_end").getValue());
cmpEnd = Integer.parseInt(srcItem.getAttribute("cmp_end").getValue());
ori = srcItem.getAttribute("ori").getValue();
//some occasions in ensembl, e.g. contig AC087365.3.1.104495 ||AC144832.1.1.45226
//Chromosome, Supercontig have shorter length than contig
//need to truncate the longer part
if (contigLength < bioEntityLength) {
length = contigLength;
} else {
length = bioEntityLength;
}
if (ori.equals("1")) {
start = asmStart - cmpStart + 1;
end = start + length - 1;
} else {
if (cmpEnd == length) {
start = asmStart;
end = start + length - 1;
} else {
start = asmStart - (length - cmpEnd);
end = start + length - 1;
}
}
Item location = createItem(tgtNs + "Location", "");
location.addAttribute(new Attribute("start", Integer.toString(start)));
location.addAttribute(new Attribute("end", Integer.toString(end)));
location.addAttribute(new Attribute("startIsPartial", "false"));
location.addAttribute(new Attribute("endIsPartial", "false"));
location.addAttribute(new Attribute("strand", srcItem.getAttribute("ori").getValue()));
location.addReference(new Reference("subject",
(getSeqItem(contigId, true)).getIdentifier()));
location.addReference(new Reference("object",
(getSeqItem(bioEntityId, true)).getIdentifier()));
return location;
}
/**
* @param refId = refId for the seq_region
* @param createSynonym = indicates that we should create a synonym for this item if we can.
*
* @return seq item it could be chromosome, supercontig, clone or contig
* @throws org.intermine.objectstore.ObjectStoreException
* when anything goes wrong.
*/
protected Item getSeqItem(String refId, boolean createSynonym) throws ObjectStoreException {
Item seq = null;
Item seqRegion = ItemHelper.convert(srcItemReader.getItemById(refId));
if (seqIdMap.containsKey(refId)) {
seq = (Item) seqIdMap.get(refId);
} else {
String property = null;
if (seqRegion.hasReference("coord_system")) {
Item coord = ItemHelper.convert(srcItemReader.getItemById(
seqRegion.getReference("coord_system").getRefId()));
if (coord.hasAttribute("name")) {
property = coord.getAttribute("name").getValue();
}
}
if (property != null && !property.equals("")) {
//Produces the classname/type of the item, i.e. Chromosome, Contig, Chunk etc etc
String s = (property.substring(0, 1)).toUpperCase().concat(property.substring(1));
seq = createItem(tgtNs + s, "");
if (seqRegion.hasAttribute("name")) {
seq.addAttribute(new Attribute(IDENTIFIER,
seqRegion.getAttribute("name").getValue()));
}
if (seqRegion.hasAttribute("length")) {
seq.addAttribute(new Attribute("length",
seqRegion.getAttribute("length").getValue()));
}
addReferencedItem(seq, config.getEnsemblDataSet(), "evidence", true, "", false);
seqIdMap.put(refId, seq);
if (config.doStoreDna()) {
Item dna = getItemViaItemPath(seqRegion, SEQ_REGION_VIA_DNA, srcItemReader);
if (dna != null) {
seq.setReference("sequence", dna);
} else {
LOG.debug("NO DNA ITEM FOUND FOR THIS SEQ ITEM:" + seq.getIdentifier());
}
} else {
LOG.debug("SKIPPING doStoreDna for this org abbrev:" + config.getOrgAbbrev());
}
}
}
//If we need to create a Synonym and one hasn't been made for the seq item yet...
if (createSynonym && !itemId2SynMap.containsKey(
seq != null ? seq.getIdentifier() : "NO_ID_HERE!")) {
if (seq != null && seq.hasAttribute(IDENTIFIER)) {
Item seqSyn = createSynonym(
seq.getIdentifier(),
IDENTIFIER,
seq.getAttribute(IDENTIFIER).getValue(),
config.getEnsemblDataSrcRef());
itemId2SynMap.put(seq.getIdentifier(), seqSyn);
} else {
LOG.debug("Skipped creating a synonym for a seq item with no identifier:"
+ (seq != null ? seq.getClassName() + " id:"
+ seq.getIdentifier() : "seq is null"));
}
}
return seq;
}
/**
* Create an AnalysisResult pointed to by tgtItem evidence reference. Move srcItem
* analysis reference and score to new AnalysisResult.
*
* @param srcItem item in src namespace to move fields from
* @param tgtItem item that will reference AnalysisResult
* @return new AnalysisResult item
* @throws org.intermine.objectstore.ObjectStoreException
* when anything goes wrong.
*/
protected Item createAnalysisResult(Item srcItem, Item tgtItem)
throws ObjectStoreException {
Item result = createItem(tgtNs + "ComputationalResult", "");
if (srcItem.hasReference("analysis")) {
moveField(srcItem, result, "analysis", "analysis");
}
if (srcItem.hasAttribute("score")) {
moveField(srcItem, result, "score", "score");
}
result.addReference(config.getEnsemblDataSetRef());
ReferenceList evidence = new ReferenceList("evidence", Arrays.asList(new Object[]
{result.getIdentifier(), config.getEnsemblDataSet().getIdentifier()}));
tgtItem.addCollection(evidence);
return result;
}
/**
* Create comment class referenced by Gene item if there is a description field
* in gene
*
* @param srcItem gene
* @param tgtItem gene
* @return new comment item
* @throws org.intermine.objectstore.ObjectStoreException
* when anything goes wrong.
*/
protected Item createComment(Item srcItem, Item tgtItem)
throws ObjectStoreException {
Item comment = null;
if (srcItem.hasAttribute("description")) {
comment = createItem(tgtNs + "Comment", "");
moveField(srcItem, comment, "description", "text");
tgtItem.addReference(new Reference("comment", comment.getIdentifier()));
}
return comment;
}
/**
* Create a simpleFeature item depends on the logic_name attribute in analysis
* will become TRNA, or CpGIsland
*
* @param srcItem ensembl: simple_feature
* @return new simpleFeature item
* @throws org.intermine.objectstore.ObjectStoreException
* when anything goes wrong.
*/
protected Item createSimpleFeature(Item srcItem) throws ObjectStoreException {
Item simpleFeature = new Item();
if (srcItem.hasReference("analysis")) {
Item analysis = ItemHelper.convert(
srcItemReader.getItemById(srcItem.getReference("analysis").getRefId()));
if (analysis.hasAttribute("logic_name")) {
String name = analysis.getAttribute("logic_name").getValue();
if (name.equals("tRNAscan")) {
simpleFeature = createItem(tgtNs + "TRNA", "");
} else if (name.equals("CpG")) {
simpleFeature = createItem(tgtNs + "CpGIsland", "");
} else if (name.equals("Eponine")) {
simpleFeature = createItem(tgtNs + "TranscriptionStartSite", "");
//} else if (name.equals("FirstEF")) {
//5 primer exon and promoter including coding and noncoding
}
StringBuffer newIdBuff = new StringBuffer();
newIdBuff.append(name).append("_");
Item seqRegItem = ItemHelper.convert(srcItemReader.getItemById(
srcItem.getReference("seq_region").getRefId()));
newIdBuff.append(seqRegItem.getAttribute("name").getValue()).append(":");
newIdBuff.append(srcItem.getAttribute("seq_region_start").getValue()).append("..");
newIdBuff.append(srcItem.getAttribute("seq_region_end").getValue());
simpleFeature.addReference(config.getOrganismRef());
simpleFeature.addAttribute(new Attribute(IDENTIFIER, newIdBuff.toString()));
addReferencedItem(simpleFeature,
config.getEnsemblDataSet(), "evidence", true, "", false);
Item sfSyn = createSynonym(
simpleFeature.getIdentifier(),
IDENTIFIER,
newIdBuff.toString(),
config.getEnsemblDataSrcRef());
itemId2SynMap.put(simpleFeature.getIdentifier(), sfSyn);
}
}
return simpleFeature;
}
/**
* Finds external database accession numbers & labels in ensembl to set as Synonyms!
*
* Note: that only a small proportion of the genes in Anoph for example have these external
* references - it is usually only for KNOWN genes. Human on the other hand has >30k genes,
* most of which are known, and of them most have a valid Hugo reference.
*
* @param srcItem - it in source format ensembl:gene
* @param tgtItem - translate item flymine:Gene
*
* @return a set of Synonyms
* @throws org.intermine.objectstore.ObjectStoreException if problem retrieving any items
*/
protected Set setXrefGeneSynonyms(Item srcItem, Item tgtItem)
throws ObjectStoreException {
Set synonyms = new HashSet();
if (srcItem.hasReference("display_xref")) {
Item xref = ItemHelper.convert(srcItemReader.getItemById(
srcItem.getReference("display_xref").getRefId()));
//DBNAME
String dbname;
//look for the reference to an xref database - the external_db
if (xref.hasReference("external_db")) {
Reference extDbRef = xref.getReference("external_db");
Item extDb = ItemHelper.convert(srcItemReader.getItemById(extDbRef.getRefId()));
dbname = extDb.getAttribute("db_name").getValue();
} else {
LOG.debug("No external_db ref found for srcItem:" + srcItem.getIdentifier());
//return as we can't create a synonym without a source db xref
return synonyms;
}
//ACCESSION
String accession = null;
//look for a primary accession - if we have one we may be able to create a synonym
if (xref.hasAttribute("dbprimary_acc")) {
accession = xref.getAttribute("dbprimary_acc").getValue();
} else {
LOG.debug("No dbprimary_acc attr found for srcItem:" + srcItem.getIdentifier());
}
//check to see if we have a valid accession & dbname.
if (accession != null && !accession.equals(EMPTY_STRING)
&& dbname != null && !dbname.equals(EMPTY_STRING)) {
//If we have a valid xref for this dsname then we can create the synonym for the
// external database accession.
//NOTE: if the xref is being used as an alternative identifier it will already have
// a synonym with type 'identifier'.
if (config.containsXrefDataSourceNamed(dbname)) {
Reference extDbRef = config.getDataSrcRefByDataSrcName(dbname);
LOG.debug("Creating Synonym for dbname:" + dbname);
synonyms.add(createProductSynonym(tgtItem, "accession", accession, extDbRef));
} else {
LOG.debug("Skipped! Can't create a Synonym for db:" + dbname);
}
} else {
LOG.debug("Skipped! Bad dbprimary_acc:" + accession + " or dbname:" + dbname);
}
//SYMBOL
String symbol = null;
//look for the display label - since we might be able to use it as a symbol synonym.
if (xref.hasAttribute("display_label")) {
symbol = xref.getAttribute("display_label").getValue();
} else {
LOG.debug("No display_label attr found for srcItem:" + srcItem.getIdentifier());
}
//check to see if we have a valid display_lable (synonym) & dbname.
if (symbol != null && !symbol.equals(EMPTY_STRING)
&& dbname != null && !dbname.equals(EMPTY_STRING)) {
//Now check to see if we can create a synonym that represents a synbol as well.
if (config.containsXrefSymbolDataSourceNamed(dbname)) {
Reference extDbRef = config.getDataSrcRefByDataSrcName(dbname);
LOG.debug("Creating Symbol Synonym for dbname:" + dbname);
synonyms.add(createProductSynonym(tgtItem, "symbol", symbol, extDbRef));
} else {
LOG.debug("Skipped creating a Symbol Synonym for db:" + dbname);
}
} else {
LOG.debug("Skipped! Bad display_label:" + accession + " or dbname:" + dbname);
}
} else {
LOG.debug("Skipped! As no display_xref was found for srcItem:" + srcItem.getClassName()
+ " id:" + srcItem.getIdentifier());
}
return synonyms;
}
/**
* Creates a synonym for a gene/protein product.
* <p/>
* This method is for 1-M
*
* @param refItem - the item that the synonym needs to reference.
* @param type - i.e. accession or symbol
* @param value - the value of the type provided
* @param dsRef - which data source is this synonym from
* @see org.intermine.dataconversion.DataTranslator#addReferencedItem
*/
private Item createProductSynonym(Item refItem,
String type,
String value,
Reference dsRef) {
Item synonym = createSynonym(refItem.getIdentifier(), type, value, dsRef);
addReferencedItem(refItem, synonym, "synonyms", true, "subject", false);
return synonym;
}
/**
* Find stable_id for various ensembl type
*
* @param ensemblType could be gene, exon, transcript or translation
* it should be part of name before _stable_id
* @param identifier srcItem identifier, srcItem could be gene, exon, transcript/translation
* @param srcNs namespace of source model
* @return a set of Synonyms
* @throws org.intermine.objectstore.ObjectStoreException
* if problem retrieving items
*/
private Item getStableId(String ensemblType, String identifier, String srcNs) throws
ObjectStoreException {
Set constraints = new HashSet();
constraints.add(new FieldNameAndValue(ObjectStoreItemPathFollowingImpl.CLASSNAME,
srcNs + ensemblType + "_stable_id", false));
constraints.add(new FieldNameAndValue(ensemblType, identifier, true));
Iterator stableIds = srcItemReader.getItemsByDescription(constraints).iterator();
if (stableIds.hasNext()) {
return ItemHelper.convert((org.intermine.model.fulldata.Item) stableIds.next());
} else {
StringBuffer bob = new StringBuffer();
bob.append("getStableId unable to find a stableId for:");
bob.append(ensemblType);
bob.append("__");
bob.append(identifier);
bob.append("__");
bob.append(srcNs);
LOG.debug(bob.toString());
return null;
}
}
/**
* Create synonym item
*
* @param subjectId = synonym reference to subject
* @param type = synonym type
* @param value = synonym value
* @param ref = synonym reference to source
* @return synonym item
*/
private Item createSynonym(String subjectId, String type, String value, Reference ref) {
Item synonym = createItem(tgtNs + "Synonym", "");
synonym.addReference(new Reference("subject", subjectId));
synonym.addAttribute(new Attribute("type", type));
synonym.addAttribute(new Attribute("value", value));
synonym.addReference(ref);
return synonym;
}
/**
* Create synonym item for marker
*
* @param srcItem = marker_synonym
* marker_synonym in ensembl may have same marker_id, source and name
* but with different marker_synonym_id,
* check before create synonym
* @return synonym item
*/
private Item getMarkerSynonym(Item srcItem) {
Item synonym;
String subjectId = srcItem.getReference("marker").getRefId();
Set synonymSet;
synonymSet = (HashSet) markerSynonymMap.get(subjectId);
String value = srcItem.getAttribute("name").getValue();
Reference ref;
//TODO: NO HARDCODING!!!!!
if (srcItem.hasAttribute("source")) {
String source = srcItem.getAttribute("source").getValue();
if (source.equalsIgnoreCase("genbank")) {
ref = config.getDataSrcRefByDataSrcName("genbank");
} else if (source.equalsIgnoreCase("gdb")) {
ref = config.getDataSrcRefByDataSrcName("gdb");
} else if (source.equalsIgnoreCase("unists")) {
ref = config.getDataSrcRefByDataSrcName("unists");
} else {
ref = config.getEnsemblDataSrcRef();
}
} else {
ref = config.getEnsemblDataSrcRef();
}
int createItem = 1;
int flag;
if (synonymSet == null) {
synonym = createSynonym(subjectId, IDENTIFIER, value, ref);
synonymSet = new HashSet(Arrays.asList(new Object[]{synonym}));
markerSynonymMap.put(subjectId, synonymSet);
} else {
Iterator i = synonymSet.iterator();
while (i.hasNext()) {
Item item = (Item) i.next();
if (item.getReference("source").getRefId().equals(ref.getRefId())
&& item.getAttribute("value").getValue().equalsIgnoreCase(value)) {
flag = 0;
} else {
flag = 1;
}
createItem = createItem * flag;
}
if (createItem == 1) {
synonym = createSynonym(subjectId, IDENTIFIER, value, ref);
synonymSet.add(synonym);
markerSynonymMap.put(subjectId, synonymSet);
} else {
synonym = null;
}
}
return synonym;
}
/**
* @see org.flymine.task.DataTranslatorTask#execute
*/
public static Map getPrefetchDescriptors() {
Map paths = new HashMap();
String identifier = ObjectStoreItemPathFollowingImpl.IDENTIFIER;
String classname = ObjectStoreItemPathFollowingImpl.CLASSNAME;
//karyotype
ItemPrefetchDescriptor desc = new ItemPrefetchDescriptor("karyotype.seq_region");
desc.addConstraint(new ItemPrefetchConstraintDynamic("seq_region", identifier));
ItemPrefetchDescriptor desc1
= new ItemPrefetchDescriptor("karyotype.seq_region.coord_system");
desc1.addConstraint(new ItemPrefetchConstraintDynamic("coord_system", identifier));
desc.addPath(desc1);
paths.put("http://www.flymine.org/model/ensembl#karyotype",
Collections.singleton(desc));
//exon
Set descSet = new HashSet();
desc = new ItemPrefetchDescriptor("exon <- exon_transcript.exon");
desc.addConstraint(new ItemPrefetchConstraintDynamic(identifier, "exon"));
desc.addConstraint(new FieldNameAndValue(classname,
"http://www.flymine.org/model/ensembl#exon_transcript", false));
descSet.add(desc);
desc1 = new ItemPrefetchDescriptor("(<- exon_transcript.exon).transcript");
desc1.addConstraint(new ItemPrefetchConstraintDynamic("transcript", identifier));
desc.addPath(desc1);
descSet.add(desc);
desc = new ItemPrefetchDescriptor("exon <- exon_stable_id.exon");
desc.addConstraint(new ItemPrefetchConstraintDynamic(identifier, "exon"));
desc.addConstraint(new FieldNameAndValue(classname,
"http://www.flymine.org/model/ensembl#exon_stable_id", false));
descSet.add(desc);
desc = new ItemPrefetchDescriptor("exon.seq_region");
desc.addConstraint(new ItemPrefetchConstraintDynamic("seq_region", identifier));
desc1 = new ItemPrefetchDescriptor("exon.seq_region.coord_system");
desc1.addConstraint(new ItemPrefetchConstraintDynamic("coord_system", identifier));
desc.addPath(desc1);
descSet.add(desc);
paths.put("http://www.flymine.org/model/ensembl#exon", descSet);
//exon_stable_id
desc = new ItemPrefetchDescriptor("exon_stable_id.exon");
desc.addConstraint(new ItemPrefetchConstraintDynamic("exon", identifier));
paths.put("http://www.flymine.org/model/ensembl#exon_stable_id",
Collections.singleton(desc));
//gene
descSet = new HashSet();
desc = new ItemPrefetchDescriptor("gene <- gene_stable_id.gene");
desc.addConstraint(new ItemPrefetchConstraintDynamic(identifier, "gene"));
desc.addConstraint(new FieldNameAndValue(classname,
"http://www.flymine.org/model/ensembl#gene_stable_id", false));
descSet.add(desc);
desc = new ItemPrefetchDescriptor("gene.analysis");
desc.addConstraint(new ItemPrefetchConstraintDynamic("analysis", identifier));
descSet.add(desc);
desc = new ItemPrefetchDescriptor("gene.seq_region");
desc.addConstraint(new ItemPrefetchConstraintDynamic("seq_region", identifier));
desc1 = new ItemPrefetchDescriptor("gene.seq_region.coord_system");
desc1.addConstraint(new ItemPrefetchConstraintDynamic("coord_system", identifier));
desc.addPath(desc1);
descSet.add(desc);
desc = new ItemPrefetchDescriptor("gene.display_xref");
desc.addConstraint(new ItemPrefetchConstraintDynamic("display_xref", identifier));
desc1 = new ItemPrefetchDescriptor("gene.display_xref.external_db");
desc1.addConstraint(new ItemPrefetchConstraintDynamic("external_db", identifier));
desc.addPath(desc1);
descSet.add(desc);
paths.put("http://www.flymine.org/model/ensembl#gene", descSet);
//gene_stable_id
desc = new ItemPrefetchDescriptor("gene_stable_id.gene");
desc.addConstraint(new ItemPrefetchConstraintDynamic("gene", identifier));
paths.put("http://www.flymine.org/model/ensembl#gene_stable_id",
Collections.singleton(desc));
//transcript
descSet = new HashSet();
desc = new ItemPrefetchDescriptor("transcript <- translation.transcript");
desc.addConstraint(new ItemPrefetchConstraintDynamic(identifier, "transcript"));
desc.addConstraint(new FieldNameAndValue(classname,
"http://www.flymine.org/model/ensembl#translation", false));
descSet.add(desc);
desc = new ItemPrefetchDescriptor("transcript <- transcript_stable_id.transcript");
desc.addConstraint(new ItemPrefetchConstraintDynamic(identifier, "transcript"));
desc.addConstraint(new FieldNameAndValue(classname,
"http://www.flymine.org/model/ensembl#transcript_stable_id", false));
descSet.add(desc);
desc = new ItemPrefetchDescriptor("transcript.gene");
desc.addConstraint(new ItemPrefetchConstraintDynamic("gene", identifier));
descSet.add(desc);
desc = new ItemPrefetchDescriptor("transcript.seq_region");
desc.addConstraint(new ItemPrefetchConstraintDynamic("seq_region", identifier));
desc1 = new ItemPrefetchDescriptor("transcript.seq_region.coord_system");
desc1.addConstraint(new ItemPrefetchConstraintDynamic("coord_system", identifier));
desc.addPath(desc1);
descSet.add(desc);
paths.put("http://www.flymine.org/model/ensembl#transcript", descSet);
//transcript_stable_id
desc = new ItemPrefetchDescriptor("transcript_stable_id.transcript");
desc.addConstraint(new ItemPrefetchConstraintDynamic("transcript", identifier));
paths.put("http://www.flymine.org/model/ensembl#transcript_stable_id",
Collections.singleton(desc));
//translation
descSet = new HashSet();
desc = new ItemPrefetchDescriptor("translation <- translation_stable_id.translation");
desc.addConstraint(new ItemPrefetchConstraintDynamic(identifier, "translation"));
desc.addConstraint(new FieldNameAndValue(classname,
"http://www.flymine.org/model/ensembl#translation_stable_id", false));
descSet.add(desc);
desc = new ItemPrefetchDescriptor("translation.transcript");
desc.addConstraint(new ItemPrefetchConstraintDynamic("transcript", identifier));
descSet.add(desc);
desc1 = new ItemPrefetchDescriptor("translation.transcript.display_xref");
desc1.addConstraint(new ItemPrefetchConstraintDynamic("display_xref", identifier));
ItemPrefetchDescriptor desc2 =
new ItemPrefetchDescriptor("translation.transcript.display_xref.external_db");
desc2.addConstraint(new ItemPrefetchConstraintDynamic("external_db", identifier));
desc1.addPath(desc2);
desc.addPath(desc1);
descSet.add(desc);
paths.put("http://www.flymine.org/model/ensembl#translation", descSet);
//translation_stable_id
desc = new ItemPrefetchDescriptor("translation_stable_id.translation");
desc.addConstraint(new ItemPrefetchConstraintDynamic("translation", identifier));
paths.put("http://www.flymine.org/model/ensembl#translation_stable_id",
Collections.singleton(desc));
//repeat_feature
descSet = new HashSet();
desc = new ItemPrefetchDescriptor("repeat_feature.analysis");
desc.addConstraint(new ItemPrefetchConstraintDynamic("analysis", identifier));
descSet.add(desc);
desc = new ItemPrefetchDescriptor("repeat_feature.repeat_consensus");
desc.addConstraint(new ItemPrefetchConstraintDynamic("repeat_consensus", identifier));
descSet.add(desc);
desc = new ItemPrefetchDescriptor("repeat_feature.seq_region");
desc.addConstraint(new ItemPrefetchConstraintDynamic("seq_region", identifier));
desc1 = new ItemPrefetchDescriptor("repeat_feature.seq_region.coord_system");
desc1.addConstraint(new ItemPrefetchConstraintDynamic("coord_system", identifier));
desc.addPath(desc1);
descSet.add(desc);
paths.put("http://www.flymine.org/model/ensembl#repeat_feature", descSet);
//marker
descSet = new HashSet();
desc = new ItemPrefetchDescriptor("marker.display_marker_synonym");
desc.addConstraint(new ItemPrefetchConstraintDynamic("display_marker_synonym", identifier));
descSet.add(desc);
desc = new ItemPrefetchDescriptor("marker <- marker_synonym.marker");
desc.addConstraint(new ItemPrefetchConstraintDynamic(identifier, "marker"));
desc.addConstraint(new FieldNameAndValue(classname,
"http://www.flymine.org/model/ensembl#marker_synonym", false));
descSet.add(desc);
desc = new ItemPrefetchDescriptor("marker <- marker_feature.marker");
desc.addConstraint(new ItemPrefetchConstraintDynamic(identifier, "marker"));
desc.addConstraint(new FieldNameAndValue(classname,
"http://www.flymine.org/model/ensembl#marker_feature", false));
desc1 = new ItemPrefetchDescriptor("(<- marker_feature.marker).seq_region");
desc1.addConstraint(new ItemPrefetchConstraintDynamic("seq_region", identifier));
desc2 = new ItemPrefetchDescriptor("(<- marker_feature.marker).seq_region.coord_system");
desc2.addConstraint(new ItemPrefetchConstraintDynamic("coord_system", identifier));
desc1.addPath(desc2);
desc.addPath(desc1);
descSet.add(desc);
paths.put("http://www.flymine.org/model/ensembl#marker",
Collections.singleton(desc));
//assembly
descSet = new HashSet();
desc = new ItemPrefetchDescriptor("assembly.asm_seq_region");
desc.addConstraint(new ItemPrefetchConstraintDynamic("asm_seq_region", identifier));
desc2 = new ItemPrefetchDescriptor("assembly.asm_seq_region.coord_system");
desc2.addConstraint(new ItemPrefetchConstraintDynamic("coord_system", identifier));
desc.addPath(desc2);
descSet.add(desc);
desc = new ItemPrefetchDescriptor("assembly.cmp_seq_region");
desc.addConstraint(new ItemPrefetchConstraintDynamic("cmp_seq_region", identifier));
desc2 = new ItemPrefetchDescriptor("assembly.cmp_seq_region.coord_system");
desc2.addConstraint(new ItemPrefetchConstraintDynamic("coord_system", identifier));
desc.addPath(desc2);
descSet.add(desc);
paths.put("http://www.flymine.org/model/ensembl#assembly", descSet);
//seq_region
desc = new ItemPrefetchDescriptor("seq_region.coord_system");
desc.addConstraint(new ItemPrefetchConstraintDynamic("coord_system", identifier));
paths.put("http://www.flymine.org/model/ensembl#seq_region",
Collections.singleton(desc));
//simple_feature
descSet = new HashSet();
desc = new ItemPrefetchDescriptor("simple_feature.analysis");
desc.addConstraint(new ItemPrefetchConstraintDynamic("analysis", identifier));
descSet.add(desc);
desc = new ItemPrefetchDescriptor("simple_feature.seq_region");
desc.addConstraint(new ItemPrefetchConstraintDynamic("seq_region", identifier));
desc1 = new ItemPrefetchDescriptor("simple_feature.seq_region.coord_system");
desc1.addConstraint(new ItemPrefetchConstraintDynamic("coord_system", identifier));
desc.addPath(desc1);
descSet.add(desc);
paths.put("http://www.flymine.org/model/ensembl#simple_feature", descSet);
return paths;
}
/**
* Utility class to keep the contents of the ensembl_config file in for reference while the
* translator is running...
* */
class EnsemblConfig
{
private String orgAbbrev;
private Item organism = null;
private Reference organismRef = null;
private boolean useXrefDbsForGeneIdentifier;
private boolean storeDna;
private EnsemblPropsUtil propsUtil;
private Map dataSourceName2ItemMap;
private Map dataSourceName2RefMap;
private Item ensemblDataSrc;
private Reference ensemblDataSrcRef;
private Item ensemblDataSet;
private Reference ensemblDataSetRef;
private Set xrefDataSourceNames;
private String geneXrefDbName = null;
private Set xrefSymbolDataSourceNames;
/**
* Constructor.
*
* @param ensemblProps a represesntation of the ensembl_config file's contents.
* @param orgAbbrev A suitably short acronym to identify which ogransim to process.
* */
EnsemblConfig(Properties ensemblProps, String orgAbbrev) {
if (orgAbbrev == null || "".equals(orgAbbrev)) {
throw new RuntimeException(
"EnsemblConfig: must have the organism abbreviation set!");
}
this.orgAbbrev = orgAbbrev;
if (ensemblProps == null) {
throw new RuntimeException(
"EnsemblConfig: can't find any ensembl_config.properties!");
}
propsUtil = new EnsemblPropsUtil(ensemblProps);
Properties organismProps = propsUtil.stripStart(orgAbbrev, ensemblProps);
organism = createItem(tgtNs + "Organism", "");
organism.addAttribute(new Attribute("abbreviation", orgAbbrev));
organism.addAttribute(new Attribute("name",
organismProps.getProperty("organism.name")));
organism.addAttribute(new Attribute("taxonId",
organismProps.getProperty("organism.taxonId")));
organismRef = new Reference("organism", organism.getIdentifier());
//This boolean indicates that we want to use configurable identifier fields...
useXrefDbsForGeneIdentifier = Boolean.valueOf(
organismProps.getProperty("flag.useXrefDbsForGeneIdentifier")).booleanValue();
storeDna = Boolean.valueOf(
organismProps.getProperty("flag.storeDna")).booleanValue();
//Load up all the data source names that we will allow xref synonyms to be set for.
xrefDataSourceNames = new HashSet(propsUtil.getPropertiesStartingWith(
orgAbbrev + ".datasource.xref.synonym").values());
dataSourceName2ItemMap = new HashMap();
dataSourceName2RefMap = new HashMap();
initDataSourceAndDataSourceRefMaps();
initEnsemblDataSrc();
initEnsemblDataSet();
//try and load the props if we need to use custom gene identifiers - i.e. Hugo for Human
if (useXrefDbsForGeneIdentifier) {
geneXrefDbName = organismProps.getProperty("gene.identifier.xref.dataSourceName");
//if it aint set - complain!
if (geneXrefDbName == null) {
throw new RuntimeException(
"EnsemblConfig: gene.identifier.xref.dataSourceName property not set!");
}
if (!dataSourceName2ItemMap.containsKey(geneXrefDbName.toLowerCase())) {
throw new RuntimeException(
"EnsemblConfig(1): gene.identifier.xref.dataSourceName:"
+ geneXrefDbName + " has no matching common.datasource");
}
}
//Load up all the data source names that we will allow xref synonyms to be set for.
xrefSymbolDataSourceNames = new HashSet(propsUtil.getPropertiesStartingWith(
orgAbbrev + ".datasource.xref.synonym.symbol").values());
//Better check there's a matching data source for each of these!
for (Iterator symbolIt = xrefSymbolDataSourceNames.iterator(); symbolIt.hasNext(); ) {
Object nextSymbol = symbolIt.next();
if (!dataSourceName2ItemMap.containsKey(nextSymbol.toString().toLowerCase())) {
throw new RuntimeException(
"EnsemblConfig(2): datasource.xref.synonym.symbol:"
+ nextSymbol.toString() + " has no matching common.datasource");
}
}
}
private void initDataSourceAndDataSourceRefMaps() {
//Get the names of all the available datasources
Properties dsNames = propsUtil.getPropertiesStartingWith("common.datasource.name");
for (Iterator dsnIt = dsNames.values().iterator(); dsnIt.hasNext(); ) {
String dsName = dsnIt.next().toString().toLowerCase();
Properties dsnNextProps = propsUtil.getPropertiesStartingWith(
"common.datasource." + dsName);
Item nextDataSource = createItem(tgtNs + "DataSource", "");
nextDataSource.addAttribute(new Attribute("name", dsName));
nextDataSource.addAttribute(new Attribute("url",
dsnNextProps.getProperty("common.datasource."
+ dsName.toLowerCase() + ".url")));
nextDataSource.addAttribute(new Attribute("description",
dsnNextProps.getProperty("common.datasource."
+ dsName.toLowerCase() + ".description")));
dataSourceName2ItemMap.put(dsName.toLowerCase(), nextDataSource);
dataSourceName2RefMap.put(dsName.toLowerCase(),
new Reference("source", nextDataSource.getIdentifier()));
}
}
private void initEnsemblDataSrc() {
String ensembl = "ensembl";
if (hasDataSourceNamed(ensembl)) {
ensemblDataSrc = getDataSrcByName(ensembl);
ensemblDataSrcRef = getDataSrcRefByDataSrcName(ensembl);
} else {
throw new RuntimeException("!!! Ensembl DataSrc Not Found !!!");
}
}
private void initEnsemblDataSet() {
String propStem = orgAbbrev + ".ensembl.dataset";
Properties props = propsUtil.getPropertiesStartingWith(propStem);
ensemblDataSet = createItem(tgtNs + "DataSet", "");
ensemblDataSet.addAttribute(
new Attribute("title", props.getProperty(propStem + ".title")));
String dsName = props.getProperty(propStem + ".dataSourceName");
Item dataSrc = getDataSrcByName(dsName);
ensemblDataSet.addReference(new Reference("dataSource", dataSrc.getIdentifier()));
ensemblDataSetRef = new Reference("source", ensemblDataSet.getIdentifier());
}
//------------------------------------------------------------------------------------------
/**
* @return An abbreviated string representing the current organism.
*/
String getOrgAbbrev() {
return orgAbbrev;
}
/**
* @return The current Organism Item
*/
Item getOrganism() {
return organism;
}
/**
* @return A reference to the current organism
*/
Reference getOrganismRef() {
return organismRef;
}
/**
* @return Do we want to use any external db ids - i.e. SwissProt/Uniprot etc for Genes?
* */
boolean useXrefDbsForGeneIdentifier() {
return useXrefDbsForGeneIdentifier;
}
/**
* @return Do we want to get the DNA sequences now or later?
* */
boolean doStoreDna() {
return storeDna;
}
/**
* @return The name of the datasource where we want to get any xref dbid's from
* */
String getGeneXrefDbName() {
return geneXrefDbName;
}
/**
* @return Get's the Ensembl Data Source Item
* */
Item getEnsemblDataSrc() {
return ensemblDataSrc;
}
/**
* @return Get's a reference to the Ensembl Data Source Item
* */
Reference getEnsemblDataSrcRef() {
return ensemblDataSrcRef;
}
/**
* @return Gets the current Ensembl Data Set being processed.
* */
Item getEnsemblDataSet() {
return ensemblDataSet;
}
/**
* @return Gets a reference to the current Ensembl Data Set being processed.
* */
Reference getEnsemblDataSetRef() {
return ensemblDataSetRef;
}
/**
* @param xrefDataSourceName a data source name to check
*
* @return have we seen this xref data source name before
* */
boolean containsXrefDataSourceNamed(String xrefDataSourceName) {
return xrefDataSourceNames.contains(xrefDataSourceName);
}
/**
* @param xrefSymbolDataSourceName a data source name that we represents a symbol
*
* @return have we seen this data source name before
* */
boolean containsXrefSymbolDataSourceNamed(String xrefSymbolDataSourceName) {
return xrefSymbolDataSourceNames.contains(xrefSymbolDataSourceName);
}
/**
* @param dataSrcName a data source name to check for
*
* @return have we seen this data source name before
* */
boolean hasDataSourceNamed(String dataSrcName) {
return dataSourceName2ItemMap.containsKey(dataSrcName.toLowerCase());
}
/**
* @param dataSrcName A named data source of interest
*
* @return a data source item
*
* @throws RuntimeException if we can't find the datasource - check the config file
* */
Item getDataSrcByName(String dataSrcName) {
if (hasDataSourceNamed(dataSrcName.toLowerCase())) {
return (Item) dataSourceName2ItemMap.get(dataSrcName.toLowerCase());
}
throw new RuntimeException("Can't find a data source named:" + dataSrcName);
}
/**
* @param dataSrcName name of a data source to look for the reference of
*
* @return a boolean indicating if we have found the reference or not
* */
boolean hasDataSrcRefForDataSrcNamed(String dataSrcName) {
return dataSourceName2RefMap.containsKey(dataSrcName.toLowerCase());
}
/**
* @param dataSrcName name of a data source to look for the reference of
*
* @return A reference to the datasource
*
* @throws RuntimeException if we can't find the reference
* */
Reference getDataSrcRefByDataSrcName(String dataSrcName) throws RuntimeException {
if (hasDataSrcRefForDataSrcNamed(dataSrcName.toLowerCase())) {
return (Reference) dataSourceName2RefMap.get(dataSrcName.toLowerCase());
}
throw new RuntimeException("Can't find a reference for a data source named:"
+ dataSrcName);
}
/**
* @return provides an Iterator of all the known data source items.
* */
Iterator getDataSrcItemIterator() {
return dataSourceName2ItemMap.values().iterator();
}
}
}
| fixed checkstyle
| flymine/model/ensembl/src/java/org/flymine/dataconversion/EnsemblDataTranslator.java | fixed checkstyle | <ide><path>lymine/model/ensembl/src/java/org/flymine/dataconversion/EnsemblDataTranslator.java
<ide>
<ide> String markerSynRefId = srcItem.getReference("display_marker_synonym").getRefId();
<ide>
<del> org.intermine.model.fulldata.Item markerSyn = srcItemReader.getItemById(markerSynRefId);//prefetch
<add> org.intermine.model.fulldata.Item markerSyn = srcItemReader.getItemById(markerSynRefId);
<add> //prefetch
<ide>
<ide> if (markerSyn != null) {
<ide> |
|
Java | mpl-2.0 | faec313c53d1651e18839434a517d9d59eedde27 | 0 | JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core | /*************************************************************************
*
* $RCSfile: _ErrorMessageDialog.java,v $
*
* $Revision: 1.3 $
*
* last change:$Date: 2004-11-02 11:55:47 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* 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
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
package ifc.sdb;
import lib.MultiPropertyTest;
/**
* Testing <code>com.sun.star.sdb.ErrorMessageDialog</code>
* service properties :
* <ul>
* <li><code> Title</code></li>
* <li><code> ParentWindow</code></li>
* <li><code> SQLException</code></li>
* </ul> <p>
* This test needs the following object relations :
* <ul>
* <li> <code>'ERR1', 'ERR2'</code>
* (of type <code>com.sun.star.sdbc.SQLException</code>):
* two objects which are used for changing 'SQLException'
* property. </li>
* <ul> <p>
* Properties testing is automated by <code>lib.MultiPropertyTest</code>.
* @see com.sun.star.sdb.ErrorMessageDialog
*/
public class _ErrorMessageDialog extends MultiPropertyTest {
/**
* <code>SQLException</code> instances must be used as property
* value.
*/
public void _SQLException() {
log.println("Testing with custom Property tester") ;
testProperty("SQLException", tEnv.getObjRelation("ERR1"),
tEnv.getObjRelation("ERR2")) ;
}
public void _ParentWindow(){
log.println("Testing with custom Property tester");
testProperty("ParentWindow", tEnv.getObjRelation("ERR_XWindow"), null);
}
} // finish class _ErrorMessageDialog
| qadevOOo/tests/java/ifc/sdb/_ErrorMessageDialog.java | /*************************************************************************
*
* $RCSfile: _ErrorMessageDialog.java,v $
*
* $Revision: 1.2 $
*
* last change:$Date: 2003-09-08 10:51:05 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* 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
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
package ifc.sdb;
import lib.MultiPropertyTest;
/**
* Testing <code>com.sun.star.sdb.ErrorMessageDialog</code>
* service properties :
* <ul>
* <li><code> Title</code></li>
* <li><code> ParentWindow</code></li>
* <li><code> SQLException</code></li>
* </ul> <p>
* This test needs the following object relations :
* <ul>
* <li> <code>'ERR1', 'ERR2'</code>
* (of type <code>com.sun.star.sdbc.SQLException</code>):
* two objects which are used for changing 'SQLException'
* property. </li>
* <ul> <p>
* Properties testing is automated by <code>lib.MultiPropertyTest</code>.
* @see com.sun.star.sdb.ErrorMessageDialog
*/
public class _ErrorMessageDialog extends MultiPropertyTest {
/**
* <code>SQLException</code> instances must be used as property
* value.
*/
public void _SQLException() {
log.println("Testing with custom Property tester") ;
testProperty("SQLException", tEnv.getObjRelation("ERR1"),
tEnv.getObjRelation("ERR2")) ;
}
} // finish class _ErrorMessageDialog
| INTEGRATION: CWS qadev19 (1.2.86); FILE MERGED
2004/08/18 19:51:23 cn 1.2.86.1: #i31186# special property test for ParentWindow()
| qadevOOo/tests/java/ifc/sdb/_ErrorMessageDialog.java | INTEGRATION: CWS qadev19 (1.2.86); FILE MERGED 2004/08/18 19:51:23 cn 1.2.86.1: #i31186# special property test for ParentWindow() | <ide><path>adevOOo/tests/java/ifc/sdb/_ErrorMessageDialog.java
<ide> *
<ide> * $RCSfile: _ErrorMessageDialog.java,v $
<ide> *
<del> * $Revision: 1.2 $
<add> * $Revision: 1.3 $
<ide> *
<del> * last change:$Date: 2003-09-08 10:51:05 $
<add> * last change:$Date: 2004-11-02 11:55:47 $
<ide> *
<ide> * The Contents of this file are made available subject to the terms of
<ide> * either of the following licenses
<ide> tEnv.getObjRelation("ERR2")) ;
<ide> }
<ide>
<add> public void _ParentWindow(){
<add> log.println("Testing with custom Property tester");
<add> testProperty("ParentWindow", tEnv.getObjRelation("ERR_XWindow"), null);
<add> }
<add>
<ide> } // finish class _ErrorMessageDialog
<ide>
<ide> |
|
Java | mit | a151b689c5ab1a779cb330819dd7aca4d4ce6a33 | 0 | ngageoint/geopackage-core-java | package mil.nga.geopackage.features;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import mil.nga.geopackage.GeoPackageCore;
import mil.nga.geopackage.GeoPackageException;
import mil.nga.geopackage.db.DateConverter;
import mil.nga.geopackage.features.columns.GeometryColumns;
import mil.nga.geopackage.io.GeoPackageIOUtils;
import mil.nga.oapi.features.json.Collection;
import mil.nga.oapi.features.json.Crs;
import mil.nga.oapi.features.json.FeatureCollection;
import mil.nga.oapi.features.json.FeaturesConverter;
import mil.nga.oapi.features.json.Link;
import mil.nga.sf.Geometry;
import mil.nga.sf.geojson.Feature;
import mil.nga.sf.proj.Projection;
import mil.nga.sf.proj.ProjectionConstants;
import mil.nga.sf.proj.ProjectionFactory;
/**
* OGC API Features Generator
*
* @author osbornb
*/
public abstract class OAPIFeatureCoreGenerator extends FeatureCoreGenerator {
/**
* Logger
*/
private static final Logger LOGGER = Logger
.getLogger(OAPIFeatureCoreGenerator.class.getName());
/**
* Limit pattern
*/
protected static final Pattern LIMIT_PATTERN = Pattern
.compile("limit=\\d+");
/**
* Base server url
*/
protected final String server;
/**
* Identifier (name) of a specific collection
*/
protected final String name;
/**
* The optional limit parameter limits the number of items that are
* presented in the response document.
*/
protected Integer limit = null;
/**
* Either a date-time or a period string that adheres to RFC 3339
*/
protected String time = null;
/**
* Time period string that adheres to RFC 3339
*/
protected String period = null;
/**
* Total limit of number of items to request
*/
protected Integer totalLimit = null;
/**
* Download attempts per tile
*/
protected int downloadAttempts = 1;
/**
* Number of rows to save in a single transaction
*/
protected int transactionLimit = 1000;
/**
* Table Geometry Columns
*/
protected GeometryColumns geometryColumns;
/**
* Constructor
*
* @param geoPackage
* GeoPackage
* @param tableName
* table name
* @param server
* server url
* @param name
* collection identifier
*/
public OAPIFeatureCoreGenerator(GeoPackageCore geoPackage, String tableName,
String server, String name) {
super(geoPackage, tableName);
this.server = server;
this.name = name;
}
/**
* Get the server
*
* @return server
*/
public String getServer() {
return server;
}
/**
* Get the name
*
* @return name
*/
public String getName() {
return name;
}
/**
* Get the limit
*
* @return limit
*/
public Integer getLimit() {
return limit;
}
/**
* Set the limit
*
* @param limit
* limit
*/
public void setLimit(Integer limit) {
this.limit = limit;
}
/**
* Get the time
*
* @return time
*/
public String getTime() {
return time;
}
/**
* Set the time
*
* @param time
* time
*/
public void setTime(String time) {
this.time = time;
}
/**
* Set the time
*
* @param time
* time
*/
public void setTime(Date time) {
if (time != null) {
DateConverter dateConverter = DateConverter
.dateConverter(DateConverter.DATETIME_FORMAT2);
this.time = dateConverter.stringValue(time);
} else {
this.time = null;
}
}
/**
* Get the time period
*
* @return period
*/
public String getPeriod() {
return period;
}
/**
* Set the time period
*
* @param period
* period
*/
public void setPeriod(String period) {
this.period = period;
}
/**
* Set the time period
*
* @param period
* period
*/
public void setPeriod(Date period) {
if (period != null) {
DateConverter dateConverter = DateConverter
.dateConverter(DateConverter.DATETIME_FORMAT2);
this.period = dateConverter.stringValue(period);
} else {
this.period = null;
}
}
/**
* Get the total limit
*
* @return total limit
*/
public Integer getTotalLimit() {
return totalLimit;
}
/**
* Set the total limit
*
* @param totalLimit
* total limit
*/
public void setTotalLimit(Integer totalLimit) {
this.totalLimit = totalLimit;
}
/**
* Get the number of download attempts
*
* @return download attempts
*/
public int getDownloadAttempts() {
return downloadAttempts;
}
/**
* Set the number of download attempts
*
* @param downloadAttempts
* download attempts
*/
public void setDownloadAttempts(int downloadAttempts) {
this.downloadAttempts = downloadAttempts;
}
/**
* Get the single transaction limit
*
* @return transaction limit
*/
public int getTransactionLimit() {
return transactionLimit;
}
/**
* Set the single transaction limit
*
* @param transactionLimit
* transaction limit
*/
public void setTransactionLimit(int transactionLimit) {
this.transactionLimit = transactionLimit;
}
/**
* Create the feature
*
* @param feature
* feature
* @throws SQLException
* upon error
*/
protected void createFeature(Feature feature) throws SQLException {
createFeature(feature.getSimpleGeometry(), feature.getProperties());
}
/**
* Create the feature
*
* @param geometry
* geometry
* @param properties
* properties
* @throws SQLException
* upon error
*/
protected void createFeature(Geometry geometry,
Map<String, Object> properties) throws SQLException {
if (srs == null) {
createSrs();
}
if (geometryColumns == null) {
geoPackage.endTransaction();
geometryColumns = createTable(properties);
initializeTable();
geoPackage.beginTransaction();
}
Map<String, Object> values = new HashMap<>();
for (Entry<String, Object> property : properties.entrySet()) {
String column = property.getKey();
Object value = getValue(column, property.getValue());
values.put(column, value);
}
saveFeature(geometry, values);
}
/**
* Initialize after the feature table is created
*/
protected abstract void initializeTable();
/**
* Save the feature
*
* @param geometry
* geometry
* @param values
* column to value mapping
*/
protected abstract void saveFeature(Geometry geometry,
Map<String, Object> values);
/**
* {@inheritDoc}
*/
@Override
public int generateFeatures() throws SQLException {
String url = buildCollectionRequestUrl();
Map<String, Map<String, Projection>> projections = getProjections(url);
if (getProjection(projections, projection) == null) {
LOGGER.log(Level.WARNING,
"The projection is not advertised by the server. Authority: "
+ projection.getAuthority() + ", Code: "
+ projection.getCode());
}
StringBuilder urlBuilder = new StringBuilder(url);
urlBuilder.append("/items");
boolean params = false;
if (time != null) {
if (params) {
urlBuilder.append("&");
} else {
urlBuilder.append("?");
params = true;
}
urlBuilder.append("time=");
urlBuilder.append(time);
if (period != null) {
urlBuilder.append("/");
urlBuilder.append(period);
}
}
if (boundingBox != null) {
if (params) {
urlBuilder.append("&");
} else {
urlBuilder.append("?");
params = true;
}
urlBuilder.append("bbox=");
urlBuilder.append(boundingBox.getMinLongitude());
urlBuilder.append(",");
urlBuilder.append(boundingBox.getMinLatitude());
urlBuilder.append(",");
urlBuilder.append(boundingBox.getMaxLongitude());
urlBuilder.append(",");
urlBuilder.append(boundingBox.getMaxLatitude());
}
String urlValue = urlBuilder.toString();
return generateFeatures(urlValue, 0);
}
/**
* Build the collection request URL
*
* @return url
*/
protected String buildCollectionRequestUrl() {
StringBuilder urlBuilder = new StringBuilder(server);
if (!server.endsWith("/")) {
urlBuilder.append("/");
}
urlBuilder.append("collections/");
urlBuilder.append(name);
return urlBuilder.toString();
}
/**
* Get the supported projections
*
* @return map of orgs and projections
*/
public Map<String, Map<String, Projection>> getProjections() {
return getProjections(buildCollectionRequestUrl());
}
/**
* Get the supported projections
*
* @param url
* URL
* @return map of orgs and projections
*/
public Map<String, Map<String, Projection>> getProjections(String url) {
return getProjections(collectionRequest(url));
}
/**
* Get the supported projections
*
* @param collection
* collection
* @return map of orgs and projections
*/
public Map<String, Map<String, Projection>> getProjections(
Collection collection) {
Map<String, Map<String, Projection>> projections = new HashMap<>();
if (collection != null) {
for (String crs : collection.getCrs()) {
Crs crsValue = new Crs(crs);
if (crsValue.isValid()) {
addProjection(projections, crsValue.getAuthority(),
crsValue.getCode());
}
}
}
if (projections.isEmpty()) {
addProjection(projections, ProjectionConstants.AUTHORITY_OGC,
ProjectionConstants.OGC_CRS84);
addProjection(projections, ProjectionConstants.AUTHORITY_EPSG,
String.valueOf(
ProjectionConstants.EPSG_WORLD_GEODETIC_SYSTEM));
} else if (getProjection(projections, ProjectionConstants.AUTHORITY_OGC,
ProjectionConstants.OGC_CRS84) != null) {
addProjection(projections, ProjectionConstants.AUTHORITY_EPSG,
String.valueOf(
ProjectionConstants.EPSG_WORLD_GEODETIC_SYSTEM));
}
return projections;
}
/**
* Get the projection
*
* @param projections
* projections map
* @param projection
* projection
* @return projection or null
*/
public Projection getProjection(
Map<String, Map<String, Projection>> projections,
Projection projection) {
return getProjection(projections, projection.getAuthority(),
projection.getCode());
}
/**
* Get the projection
*
* @param projections
* projections map
* @param authority
* authority
* @param code
* code
* @return projection or null
*/
public Projection getProjection(
Map<String, Map<String, Projection>> projections, String authority,
String code) {
Projection projection = null;
Map<String, Projection> authorityProjections = projections
.get(authority);
if (authorityProjections != null) {
projection = authorityProjections.get(code);
}
return projection;
}
/**
* Add a projection
*
* @param projections
* projections map
* @param authority
* authority
* @param code
* code
*/
protected void addProjection(
Map<String, Map<String, Projection>> projections, String authority,
String code) {
Map<String, Projection> authorityProjections = projections
.get(authority);
if (authorityProjections == null) {
authorityProjections = new HashMap<>();
projections.put(authority, authorityProjections);
}
try {
Projection projection = ProjectionFactory.getProjection(authority,
code);
authorityProjections.put(code, projection);
} catch (Exception e) {
LOGGER.log(Level.WARNING, "Unable to create projection. Authority: "
+ authority + ", Code: " + code);
}
}
/**
* Collection request
*
* @return collection
*/
public Collection collectionRequest() {
return collectionRequest(buildCollectionRequestUrl());
}
/**
* Collection request for the provided URL
*
* @param url
* url value
* @return collection
*/
protected Collection collectionRequest(String url) {
Collection collection = null;
String collectionValue = null;
try {
collectionValue = urlRequest(url);
} catch (Exception e) {
LOGGER.log(Level.WARNING,
"Failed to request the collection. url: " + url, e);
}
if (collectionValue != null) {
try {
collection = FeaturesConverter.toCollection(collectionValue);
} catch (Exception e) {
LOGGER.log(Level.WARNING,
"Failed to translate collection. url: " + url, e);
}
}
return collection;
}
/**
* Generate features
*
* @param urlString
* URL
* @param currentCount
* current count
* @return current result count
* @throws SQLException
* upon failure
*/
public int generateFeatures(String urlString, int currentCount)
throws SQLException {
StringBuilder urlBuilder = new StringBuilder(urlString);
int paramIndex = urlString.lastIndexOf("?");
boolean params = paramIndex >= 0 && paramIndex + 1 < urlString.length();
Integer requestLimit = limit;
if (totalLimit != null && totalLimit
- currentCount < (requestLimit != null ? requestLimit
: FeatureCollection.LIMIT_DEFAULT)) {
requestLimit = totalLimit - currentCount;
}
if (requestLimit != null) {
Matcher matcher = LIMIT_PATTERN.matcher(urlBuilder.toString());
if (matcher.find()) {
urlBuilder = new StringBuilder(
matcher.replaceFirst("limit=" + requestLimit));
} else {
if (params) {
urlBuilder.append("&");
} else {
urlBuilder.append("?");
params = true;
}
urlBuilder.append("limit=");
urlBuilder.append(requestLimit);
}
}
String features = urlRequest(urlBuilder.toString());
if (features != null) {
FeatureCollection featureCollection = createFeatures(features);
Integer numberReturned = featureCollection.getNumberReturned();
if (numberReturned != null) {
currentCount += numberReturned;
}
List<Link> nextLinks = featureCollection.getRelationLinks()
.get(FeatureCollection.LINK_RELATION_NEXT);
if (nextLinks != null) {
for (Link nextLink : nextLinks) {
if (totalLimit != null && totalLimit <= currentCount) {
break;
}
currentCount = generateFeatures(nextLink.getHref(),
currentCount);
}
}
}
return currentCount;
}
/**
* URL request
*
* @param urlValue
* URL value
* @return response string
*/
protected String urlRequest(String urlValue) {
String response = null;
URL url;
try {
url = new URL(urlValue);
} catch (MalformedURLException e) {
throw new GeoPackageException("Failed request. URL: " + urlValue,
e);
}
int attempt = 1;
while (true) {
try {
response = urlRequest(urlValue, url);
break;
} catch (Exception e) {
if (attempt < downloadAttempts) {
LOGGER.log(Level.WARNING,
"Failed to download features after attempt "
+ attempt + " of " + downloadAttempts
+ ". URL: " + urlValue,
e);
attempt++;
} else {
throw new GeoPackageException(
"Failed to download features after "
+ downloadAttempts + " attempts. URL: "
+ urlValue,
e);
}
}
}
return response;
}
/**
* Perform a URL request
*
* @param urlValue
* URL string value
* @param url
* URL
* @return features response
*/
protected String urlRequest(String urlValue, URL url) {
String response = null;
HttpURLConnection connection = null;
try {
LOGGER.log(Level.INFO, urlValue);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Accept",
"application/json,application/geo+json");
connection.connect();
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_MOVED_PERM
|| responseCode == HttpURLConnection.HTTP_MOVED_TEMP
|| responseCode == HttpURLConnection.HTTP_SEE_OTHER) {
String redirect = connection.getHeaderField("Location");
connection.disconnect();
url = new URL(redirect);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
}
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new GeoPackageException("Failed request. URL: " + urlValue
+ ", Response Code: " + connection.getResponseCode()
+ ", Response Message: "
+ connection.getResponseMessage());
}
InputStream responseStream = connection.getInputStream();
response = GeoPackageIOUtils.streamString(responseStream);
} catch (IOException e) {
throw new GeoPackageException("Failed request. URL: " + urlValue,
e);
} finally {
if (connection != null) {
connection.disconnect();
}
}
return response;
}
/**
* Create features in the feature DAO from the features value
*
* @param features
* features json
* @return feature collection
* @throws SQLException
* upon error
*/
protected FeatureCollection createFeatures(String features)
throws SQLException {
FeatureCollection featureCollection = FeaturesConverter
.toFeatureCollection(features);
createFeatures(featureCollection);
return featureCollection;
}
/**
* Create features from the feature collection
*
* @param featureCollection
* feature collection
*/
protected void createFeatures(FeatureCollection featureCollection) {
int count = 0;
geoPackage.beginTransaction();
try {
for (Feature feature : featureCollection.getFeatureCollection()
.getFeatures()) {
try {
createFeature(feature);
count++;
} catch (Exception e) {
LOGGER.log(Level.WARNING,
"Failed to create feature: " + feature.getId(), e);
}
if (count > 0 && count % transactionLimit == 0) {
geoPackage.commit();
}
}
} catch (Exception e) {
LOGGER.log(Level.WARNING, "Failed to create features", e);
geoPackage.failTransaction();
} finally {
geoPackage.endTransaction();
}
}
}
| src/main/java/mil/nga/geopackage/features/OAPIFeatureCoreGenerator.java | package mil.nga.geopackage.features;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import mil.nga.geopackage.GeoPackageCore;
import mil.nga.geopackage.GeoPackageException;
import mil.nga.geopackage.db.DateConverter;
import mil.nga.geopackage.io.GeoPackageIOUtils;
import mil.nga.oapi.features.json.Collection;
import mil.nga.oapi.features.json.Crs;
import mil.nga.oapi.features.json.FeatureCollection;
import mil.nga.oapi.features.json.FeaturesConverter;
import mil.nga.oapi.features.json.Link;
import mil.nga.sf.Geometry;
import mil.nga.sf.geojson.Feature;
import mil.nga.sf.proj.Projection;
import mil.nga.sf.proj.ProjectionConstants;
import mil.nga.sf.proj.ProjectionFactory;
/**
* OGC API Features Generator
*
* @author osbornb
*/
public abstract class OAPIFeatureCoreGenerator extends FeatureCoreGenerator {
/**
* Logger
*/
private static final Logger LOGGER = Logger
.getLogger(OAPIFeatureCoreGenerator.class.getName());
/**
* Limit pattern
*/
private static final Pattern LIMIT_PATTERN = Pattern.compile("limit=\\d+");
/**
* Base server url
*/
private final String server;
/**
* Identifier (name) of a specific collection
*/
private final String name;
/**
* The optional limit parameter limits the number of items that are
* presented in the response document.
*/
private Integer limit = null;
/**
* Either a date-time or a period string that adheres to RFC 3339
*/
private String time = null;
/**
* Time period string that adheres to RFC 3339
*/
private String period = null;
/**
* Total limit of number of items to request
*/
private Integer totalLimit = null;
/**
* Download attempts per tile
*/
private int downloadAttempts = 1;
/**
* Constructor
*
* @param geoPackage
* GeoPackage
* @param tableName
* table name
* @param server
* server url
* @param name
* collection identifier
*/
public OAPIFeatureCoreGenerator(GeoPackageCore geoPackage, String tableName,
String server, String name) {
super(geoPackage, tableName);
this.server = server;
this.name = name;
}
/**
* Get the server
*
* @return server
*/
public String getServer() {
return server;
}
/**
* Get the name
*
* @return name
*/
public String getName() {
return name;
}
/**
* Get the limit
*
* @return limit
*/
public Integer getLimit() {
return limit;
}
/**
* Set the limit
*
* @param limit
* limit
*/
public void setLimit(Integer limit) {
this.limit = limit;
}
/**
* Get the time
*
* @return time
*/
public String getTime() {
return time;
}
/**
* Set the time
*
* @param time
* time
*/
public void setTime(String time) {
this.time = time;
}
/**
* Set the time
*
* @param time
* time
*/
public void setTime(Date time) {
if (time != null) {
DateConverter dateConverter = DateConverter
.dateConverter(DateConverter.DATETIME_FORMAT2);
this.time = dateConverter.stringValue(time);
} else {
this.time = null;
}
}
/**
* Get the time period
*
* @return period
*/
public String getPeriod() {
return period;
}
/**
* Set the time period
*
* @param period
* period
*/
public void setPeriod(String period) {
this.period = period;
}
/**
* Set the time period
*
* @param period
* period
*/
public void setPeriod(Date period) {
if (period != null) {
DateConverter dateConverter = DateConverter
.dateConverter(DateConverter.DATETIME_FORMAT2);
this.period = dateConverter.stringValue(period);
} else {
this.period = null;
}
}
/**
* Get the total limit
*
* @return total limit
*/
public Integer getTotalLimit() {
return totalLimit;
}
/**
* Set the total limit
*
* @param totalLimit
* total limit
*/
public void setTotalLimit(Integer totalLimit) {
this.totalLimit = totalLimit;
}
/**
* Get the number of download attempts
*
* @return download attempts
*/
public int getDownloadAttempts() {
return downloadAttempts;
}
/**
* Set the number of download attempts
*
* @param downloadAttempts
* download attempts
*/
public void setDownloadAttempts(int downloadAttempts) {
this.downloadAttempts = downloadAttempts;
}
/**
* Create the feature
*
* @param feature
* feature
* @throws SQLException
* upon error
*/
protected void createFeature(Feature feature) throws SQLException {
createFeature(feature.getSimpleGeometry(), feature.getProperties());
}
/**
* Create the feature
*
* @param geometry
* geometry
* @param properties
* properties
* @throws SQLException
* upon error
*/
protected abstract void createFeature(Geometry geometry,
Map<String, Object> properties) throws SQLException;
/**
* {@inheritDoc}
*/
@Override
public int generateFeatures() throws SQLException {
String url = buildCollectionRequestUrl();
Map<String, Map<String, Projection>> projections = getProjections(url);
if (getProjection(projections, projection) == null) {
LOGGER.log(Level.WARNING,
"The projection is not advertised by the server. Authority: "
+ projection.getAuthority() + ", Code: "
+ projection.getCode());
}
StringBuilder urlBuilder = new StringBuilder(url);
urlBuilder.append("/items");
boolean params = false;
if (time != null) {
if (params) {
urlBuilder.append("&");
} else {
urlBuilder.append("?");
params = true;
}
urlBuilder.append("time=");
urlBuilder.append(time);
if (period != null) {
urlBuilder.append("/");
urlBuilder.append(period);
}
}
if (boundingBox != null) {
if (params) {
urlBuilder.append("&");
} else {
urlBuilder.append("?");
params = true;
}
urlBuilder.append("bbox=");
urlBuilder.append(boundingBox.getMinLongitude());
urlBuilder.append(",");
urlBuilder.append(boundingBox.getMinLatitude());
urlBuilder.append(",");
urlBuilder.append(boundingBox.getMaxLongitude());
urlBuilder.append(",");
urlBuilder.append(boundingBox.getMaxLatitude());
}
String urlValue = urlBuilder.toString();
return generateFeatures(urlValue, 0);
}
/**
* Build the collection request URL
*
* @return url
*/
protected String buildCollectionRequestUrl() {
StringBuilder urlBuilder = new StringBuilder(server);
if (!server.endsWith("/")) {
urlBuilder.append("/");
}
urlBuilder.append("collections/");
urlBuilder.append(name);
return urlBuilder.toString();
}
/**
* Get the supported projections
*
* @return map of orgs and projections
*/
public Map<String, Map<String, Projection>> getProjections() {
return getProjections(buildCollectionRequestUrl());
}
/**
* Get the supported projections
*
* @param url
* URL
* @return map of orgs and projections
*/
public Map<String, Map<String, Projection>> getProjections(String url) {
return getProjections(collectionRequest(url));
}
/**
* Get the supported projections
*
* @param collection
* collection
* @return map of orgs and projections
*/
public Map<String, Map<String, Projection>> getProjections(
Collection collection) {
Map<String, Map<String, Projection>> projections = new HashMap<>();
if (collection != null) {
for (String crs : collection.getCrs()) {
Crs crsValue = new Crs(crs);
if (crsValue.isValid()) {
addProjection(projections, crsValue.getAuthority(),
crsValue.getCode());
}
}
}
if (projections.isEmpty()) {
addProjection(projections, ProjectionConstants.AUTHORITY_OGC,
ProjectionConstants.OGC_CRS84);
addProjection(projections, ProjectionConstants.AUTHORITY_EPSG,
String.valueOf(
ProjectionConstants.EPSG_WORLD_GEODETIC_SYSTEM));
} else if (getProjection(projections, ProjectionConstants.AUTHORITY_OGC,
ProjectionConstants.OGC_CRS84) != null) {
addProjection(projections, ProjectionConstants.AUTHORITY_EPSG,
String.valueOf(
ProjectionConstants.EPSG_WORLD_GEODETIC_SYSTEM));
}
return projections;
}
/**
* Get the projection
*
* @param projections
* projections map
* @param projection
* projection
* @return projection or null
*/
public Projection getProjection(
Map<String, Map<String, Projection>> projections,
Projection projection) {
return getProjection(projections, projection.getAuthority(),
projection.getCode());
}
/**
* Get the projection
*
* @param projections
* projections map
* @param authority
* authority
* @param code
* code
* @return projection or null
*/
public Projection getProjection(
Map<String, Map<String, Projection>> projections, String authority,
String code) {
Projection projection = null;
Map<String, Projection> authorityProjections = projections
.get(authority);
if (authorityProjections != null) {
projection = authorityProjections.get(code);
}
return projection;
}
/**
* Add a projection
*
* @param projections
* projections map
* @param authority
* authority
* @param code
* code
*/
protected void addProjection(
Map<String, Map<String, Projection>> projections, String authority,
String code) {
Map<String, Projection> authorityProjections = projections
.get(authority);
if (authorityProjections == null) {
authorityProjections = new HashMap<>();
projections.put(authority, authorityProjections);
}
try {
Projection projection = ProjectionFactory.getProjection(authority,
code);
authorityProjections.put(code, projection);
} catch (Exception e) {
LOGGER.log(Level.WARNING, "Unable to create projection. Authority: "
+ authority + ", Code: " + code);
}
}
/**
* Collection request
*
* @return collection
*/
public Collection collectionRequest() {
return collectionRequest(buildCollectionRequestUrl());
}
/**
* Collection request for the provided URL
*
* @param url
* url value
* @return collection
*/
protected Collection collectionRequest(String url) {
Collection collection = null;
String collectionValue = null;
try {
collectionValue = urlRequest(url);
} catch (Exception e) {
LOGGER.log(Level.WARNING,
"Failed to request the collection. url: " + url, e);
}
if (collectionValue != null) {
try {
collection = FeaturesConverter.toCollection(collectionValue);
} catch (Exception e) {
LOGGER.log(Level.WARNING,
"Failed to translate collection. url: " + url, e);
}
}
return collection;
}
/**
* Generate features
*
* @param urlString
* URL
* @param currentCount
* current count
* @return current result count
* @throws SQLException
* upon failure
*/
public int generateFeatures(String urlString, int currentCount)
throws SQLException {
StringBuilder urlBuilder = new StringBuilder(urlString);
int paramIndex = urlString.lastIndexOf("?");
boolean params = paramIndex >= 0 && paramIndex + 1 < urlString.length();
Integer requestLimit = limit;
if (totalLimit != null && totalLimit
- currentCount < (requestLimit != null ? requestLimit
: FeatureCollection.LIMIT_DEFAULT)) {
requestLimit = totalLimit - currentCount;
}
if (requestLimit != null) {
Matcher matcher = LIMIT_PATTERN.matcher(urlBuilder.toString());
if (matcher.find()) {
urlBuilder = new StringBuilder(
matcher.replaceFirst("limit=" + requestLimit));
} else {
if (params) {
urlBuilder.append("&");
} else {
urlBuilder.append("?");
params = true;
}
urlBuilder.append("limit=");
urlBuilder.append(requestLimit);
}
}
String features = urlRequest(urlBuilder.toString());
if (features != null) {
FeatureCollection featureCollection = createFeatures(features);
Integer numberReturned = featureCollection.getNumberReturned();
if (numberReturned != null) {
currentCount += numberReturned;
}
List<Link> nextLinks = featureCollection.getRelationLinks()
.get(FeatureCollection.LINK_RELATION_NEXT);
if (nextLinks != null) {
for (Link nextLink : nextLinks) {
if (totalLimit != null && totalLimit <= currentCount) {
break;
}
currentCount = generateFeatures(nextLink.getHref(),
currentCount);
}
}
}
return currentCount;
}
/**
* URL request
*
* @param urlValue
* URL value
* @return response string
*/
protected String urlRequest(String urlValue) {
String response = null;
URL url;
try {
url = new URL(urlValue);
} catch (MalformedURLException e) {
throw new GeoPackageException("Failed request. URL: " + urlValue,
e);
}
int attempt = 1;
while (true) {
try {
response = urlRequest(urlValue, url);
break;
} catch (Exception e) {
if (attempt < downloadAttempts) {
LOGGER.log(Level.WARNING,
"Failed to download features after attempt "
+ attempt + " of " + downloadAttempts
+ ". URL: " + urlValue,
e);
attempt++;
} else {
throw new GeoPackageException(
"Failed to download features after "
+ downloadAttempts + " attempts. URL: "
+ urlValue,
e);
}
}
}
return response;
}
/**
* Perform a URL request
*
* @param urlValue
* URL string value
* @param url
* URL
* @return features response
*/
protected String urlRequest(String urlValue, URL url) {
String response = null;
HttpURLConnection connection = null;
try {
LOGGER.log(Level.INFO, urlValue);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Accept",
"application/json,application/geo+json");
connection.connect();
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_MOVED_PERM
|| responseCode == HttpURLConnection.HTTP_MOVED_TEMP
|| responseCode == HttpURLConnection.HTTP_SEE_OTHER) {
String redirect = connection.getHeaderField("Location");
connection.disconnect();
url = new URL(redirect);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
}
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new GeoPackageException("Failed request. URL: " + urlValue
+ ", Response Code: " + connection.getResponseCode()
+ ", Response Message: "
+ connection.getResponseMessage());
}
InputStream responseStream = connection.getInputStream();
response = GeoPackageIOUtils.streamString(responseStream);
} catch (IOException e) {
throw new GeoPackageException("Failed request. URL: " + urlValue,
e);
} finally {
if (connection != null) {
connection.disconnect();
}
}
return response;
}
/**
* Create features in the feature DAO from the features value
*
* @param features
* features json
* @return next links
* @throws SQLException
* upon error
*/
protected FeatureCollection createFeatures(String features)
throws SQLException {
FeatureCollection featureCollection = FeaturesConverter
.toFeatureCollection(features);
for (Feature feature : featureCollection.getFeatureCollection()
.getFeatures()) {
try {
createFeature(feature);
} catch (Exception e) {
LOGGER.log(Level.WARNING,
"Failed to create feature: " + feature.getId(), e);
}
}
return featureCollection;
}
}
| common OGC API feature generator functionality including transactions
| src/main/java/mil/nga/geopackage/features/OAPIFeatureCoreGenerator.java | common OGC API feature generator functionality including transactions | <ide><path>rc/main/java/mil/nga/geopackage/features/OAPIFeatureCoreGenerator.java
<ide> import java.util.HashMap;
<ide> import java.util.List;
<ide> import java.util.Map;
<add>import java.util.Map.Entry;
<ide> import java.util.logging.Level;
<ide> import java.util.logging.Logger;
<ide> import java.util.regex.Matcher;
<ide> import mil.nga.geopackage.GeoPackageCore;
<ide> import mil.nga.geopackage.GeoPackageException;
<ide> import mil.nga.geopackage.db.DateConverter;
<add>import mil.nga.geopackage.features.columns.GeometryColumns;
<ide> import mil.nga.geopackage.io.GeoPackageIOUtils;
<ide> import mil.nga.oapi.features.json.Collection;
<ide> import mil.nga.oapi.features.json.Crs;
<ide> /**
<ide> * Limit pattern
<ide> */
<del> private static final Pattern LIMIT_PATTERN = Pattern.compile("limit=\\d+");
<add> protected static final Pattern LIMIT_PATTERN = Pattern
<add> .compile("limit=\\d+");
<ide>
<ide> /**
<ide> * Base server url
<ide> */
<del> private final String server;
<add> protected final String server;
<ide>
<ide> /**
<ide> * Identifier (name) of a specific collection
<ide> */
<del> private final String name;
<add> protected final String name;
<ide>
<ide> /**
<ide> * The optional limit parameter limits the number of items that are
<ide> * presented in the response document.
<ide> */
<del> private Integer limit = null;
<add> protected Integer limit = null;
<ide>
<ide> /**
<ide> * Either a date-time or a period string that adheres to RFC 3339
<ide> */
<del> private String time = null;
<add> protected String time = null;
<ide>
<ide> /**
<ide> * Time period string that adheres to RFC 3339
<ide> */
<del> private String period = null;
<add> protected String period = null;
<ide>
<ide> /**
<ide> * Total limit of number of items to request
<ide> */
<del> private Integer totalLimit = null;
<add> protected Integer totalLimit = null;
<ide>
<ide> /**
<ide> * Download attempts per tile
<ide> */
<del> private int downloadAttempts = 1;
<add> protected int downloadAttempts = 1;
<add>
<add> /**
<add> * Number of rows to save in a single transaction
<add> */
<add> protected int transactionLimit = 1000;
<add>
<add> /**
<add> * Table Geometry Columns
<add> */
<add> protected GeometryColumns geometryColumns;
<ide>
<ide> /**
<ide> * Constructor
<ide> }
<ide>
<ide> /**
<add> * Get the single transaction limit
<add> *
<add> * @return transaction limit
<add> */
<add> public int getTransactionLimit() {
<add> return transactionLimit;
<add> }
<add>
<add> /**
<add> * Set the single transaction limit
<add> *
<add> * @param transactionLimit
<add> * transaction limit
<add> */
<add> public void setTransactionLimit(int transactionLimit) {
<add> this.transactionLimit = transactionLimit;
<add> }
<add>
<add> /**
<ide> * Create the feature
<ide> *
<ide> * @param feature
<ide> * @throws SQLException
<ide> * upon error
<ide> */
<del> protected abstract void createFeature(Geometry geometry,
<del> Map<String, Object> properties) throws SQLException;
<add> protected void createFeature(Geometry geometry,
<add> Map<String, Object> properties) throws SQLException {
<add>
<add> if (srs == null) {
<add> createSrs();
<add> }
<add>
<add> if (geometryColumns == null) {
<add> geoPackage.endTransaction();
<add> geometryColumns = createTable(properties);
<add> initializeTable();
<add> geoPackage.beginTransaction();
<add> }
<add>
<add> Map<String, Object> values = new HashMap<>();
<add>
<add> for (Entry<String, Object> property : properties.entrySet()) {
<add> String column = property.getKey();
<add> Object value = getValue(column, property.getValue());
<add> values.put(column, value);
<add> }
<add>
<add> saveFeature(geometry, values);
<add>
<add> }
<add>
<add> /**
<add> * Initialize after the feature table is created
<add> */
<add> protected abstract void initializeTable();
<add>
<add> /**
<add> * Save the feature
<add> *
<add> * @param geometry
<add> * geometry
<add> * @param values
<add> * column to value mapping
<add> */
<add> protected abstract void saveFeature(Geometry geometry,
<add> Map<String, Object> values);
<ide>
<ide> /**
<ide> * {@inheritDoc}
<ide> *
<ide> * @param features
<ide> * features json
<del> * @return next links
<add> * @return feature collection
<ide> * @throws SQLException
<ide> * upon error
<ide> */
<ide>
<ide> FeatureCollection featureCollection = FeaturesConverter
<ide> .toFeatureCollection(features);
<del> for (Feature feature : featureCollection.getFeatureCollection()
<del> .getFeatures()) {
<del> try {
<del> createFeature(feature);
<del> } catch (Exception e) {
<del> LOGGER.log(Level.WARNING,
<del> "Failed to create feature: " + feature.getId(), e);
<del> }
<del> }
<add>
<add> createFeatures(featureCollection);
<ide>
<ide> return featureCollection;
<ide> }
<ide>
<add> /**
<add> * Create features from the feature collection
<add> *
<add> * @param featureCollection
<add> * feature collection
<add> */
<add> protected void createFeatures(FeatureCollection featureCollection) {
<add>
<add> int count = 0;
<add>
<add> geoPackage.beginTransaction();
<add> try {
<add>
<add> for (Feature feature : featureCollection.getFeatureCollection()
<add> .getFeatures()) {
<add> try {
<add> createFeature(feature);
<add> count++;
<add> } catch (Exception e) {
<add> LOGGER.log(Level.WARNING,
<add> "Failed to create feature: " + feature.getId(), e);
<add> }
<add>
<add> if (count > 0 && count % transactionLimit == 0) {
<add> geoPackage.commit();
<add> }
<add>
<add> }
<add>
<add> } catch (Exception e) {
<add> LOGGER.log(Level.WARNING, "Failed to create features", e);
<add> geoPackage.failTransaction();
<add> } finally {
<add> geoPackage.endTransaction();
<add> }
<add>
<add> }
<add>
<ide> } |
|
Java | apache-2.0 | 82ba138392a063b8c6a70b9d1fe29a805e4371ff | 0 | eFaps/eFaps-Kernel-Install,eFaps/eFaps-Kernel-Install | /*
* Copyright 2003 - 2013 The eFaps Team
*
* 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.
*
* Revision: $Rev$
* Last Changed: $Date$
* Last Changed By: $Author$
*/
package org.efaps.esjp.admin.user;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.efaps.admin.datamodel.ui.FieldValue;
import org.efaps.admin.event.Parameter;
import org.efaps.admin.event.Parameter.ParameterValues;
import org.efaps.admin.event.Return;
import org.efaps.admin.event.Return.ReturnValues;
import org.efaps.admin.program.esjp.EFapsRevision;
import org.efaps.admin.program.esjp.EFapsUUID;
import org.efaps.ci.CIAdminUser;
import org.efaps.db.Context;
import org.efaps.db.InstanceQuery;
import org.efaps.db.QueryBuilder;
import org.efaps.esjp.common.uiform.Field;
import org.efaps.esjp.common.uiform.Field_Base.DropDownPosition;
import org.efaps.util.EFapsException;
/**
* TODO comment!
*
* @author The eFaps Team
* @version $Id: Association_Base.java 9233 2013-04-22 15:16:22Z [email protected]
* $
*/
@EFapsUUID("30482e5e-08df-47bc-b683-9993636643b3")
@EFapsRevision("$Rev$")
public abstract class Group_Base
{
/**
* @param _parameter Parameter as passed by the eFaps API
* @return Return containing snipplet
* @throws EFapsException on error
*/
public Return getFieldValue(final Parameter _parameter)
throws EFapsException
{
final Return ret = new Return();
final FieldValue fieldValue = (FieldValue) _parameter.get(ParameterValues.UIOBJECT);
final Object value = fieldValue.getValue();
final List<DropDownPosition> dropDownList = new ArrayList<DropDownPosition>();
for (final Long groupId : Context.getThreadContext().getPerson().getGroups()) {
final org.efaps.admin.user.Group group = org.efaps.admin.user.Group.get(groupId);
final DropDownPosition ddPos = new DropDownPosition(groupId, group.getName(), group.getName());
ddPos.setSelected(value != null && ((org.efaps.admin.user.Group) value).equals(group));
dropDownList.add(ddPos);
}
if (dropDownList.isEmpty()) {
final QueryBuilder queryBldr = new QueryBuilder(CIAdminUser.Group);
final InstanceQuery query = queryBldr.getQuery();
query.executeWithoutAccessCheck();
while (query.next()) {
final org.efaps.admin.user.Group group = org.efaps.admin.user.Group
.get(query.getCurrentValue().getId());
final DropDownPosition ddPos = new DropDownPosition(group.getId(), group.getName(), group.getName());
ddPos.setSelected(value != null && ((org.efaps.admin.user.Group) value).equals(group));
dropDownList.add(ddPos);
}
}
Collections.sort(dropDownList, new Comparator<DropDownPosition>()
{
@SuppressWarnings("unchecked")
@Override
public int compare(final DropDownPosition _o1,
final DropDownPosition _o2)
{
return _o1.getOrderValue().compareTo(_o2.getOrderValue());
}
});
ret.put(ReturnValues.SNIPLETT, new Field().getDropDownField(_parameter, dropDownList).toString());
return ret;
}
/**
* @param _parameter Parameter as passed by the eFaps API
* @return Return containing true if no Group assigned or more than one
* @throws EFapsException on error
*/
public Return checkAccess4MoreThanOne(final Parameter _parameter)
throws EFapsException
{
final Return ret = new Return();
if (Context.getThreadContext().getPerson().getGroups().isEmpty()
|| Context.getThreadContext().getPerson().getGroups().size() > 1) {
ret.put(ReturnValues.TRUE, true);
}
return ret;
}
}
| src/main/efaps/ESJP/org/efaps/esjp/admin/user/Group_Base.java | /*
* Copyright 2003 - 2013 The eFaps Team
*
* 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.
*
* Revision: $Rev$
* Last Changed: $Date$
* Last Changed By: $Author$
*/
package org.efaps.esjp.admin.user;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.efaps.admin.event.Parameter;
import org.efaps.admin.event.Return;
import org.efaps.admin.event.Return.ReturnValues;
import org.efaps.admin.program.esjp.EFapsRevision;
import org.efaps.admin.program.esjp.EFapsUUID;
import org.efaps.ci.CIAdminUser;
import org.efaps.db.Context;
import org.efaps.db.InstanceQuery;
import org.efaps.db.QueryBuilder;
import org.efaps.esjp.common.uiform.Field;
import org.efaps.esjp.common.uiform.Field_Base.DropDownPosition;
import org.efaps.util.EFapsException;
/**
* TODO comment!
*
* @author The eFaps Team
* @version $Id: Association_Base.java 9233 2013-04-22 15:16:22Z [email protected]
* $
*/
@EFapsUUID("30482e5e-08df-47bc-b683-9993636643b3")
@EFapsRevision("$Rev$")
public abstract class Group_Base
{
/**
* @param _parameter Parameter as passed by the eFaps API
* @return Return containing snipplet
* @throws EFapsException on error
*/
public Return getFieldValue(final Parameter _parameter)
throws EFapsException
{
final Return ret = new Return();
final List<DropDownPosition> dropDownList = new ArrayList<DropDownPosition>();
for (final Long groupId : Context.getThreadContext().getPerson().getGroups()) {
final org.efaps.admin.user.Group group = org.efaps.admin.user.Group.get(groupId);
dropDownList.add(new DropDownPosition(groupId, group.getName(), group.getName()));
}
if (dropDownList.isEmpty()) {
final QueryBuilder queryBldr = new QueryBuilder(CIAdminUser.Group);
final InstanceQuery query = queryBldr.getQuery();
query.executeWithoutAccessCheck();
while (query.next()) {
final org.efaps.admin.user.Group group = org.efaps.admin.user.Group
.get(query.getCurrentValue().getId());
dropDownList.add(new DropDownPosition(group.getId(), group.getName(), group.getName()));
}
}
Collections.sort(dropDownList, new Comparator<DropDownPosition>()
{
@SuppressWarnings("unchecked")
@Override
public int compare(final DropDownPosition _o1,
final DropDownPosition _o2)
{
return _o1.getOrderValue().compareTo(_o2.getOrderValue());
}
});
ret.put(ReturnValues.SNIPLETT, new Field().getDropDownField(_parameter, dropDownList).toString());
return ret;
}
/**
* @param _parameter Parameter as passed by the eFaps API
* @return Return containing true if no Group assigned or more than one
* @throws EFapsException on error
*/
public Return checkAccess4MoreThanOne(final Parameter _parameter)
throws EFapsException
{
final Return ret = new Return();
if (Context.getThreadContext().getPerson().getGroups().isEmpty()
|| Context.getThreadContext().getPerson().getGroups().size() > 1) {
ret.put(ReturnValues.TRUE, true);
}
return ret;
}
}
| - kenel-install: update of basd esjp for Groups
git-svn-id: 4afd028e37a0ecb7b60cc6a38eb25d9930f4ee19@9381 fee104cc-1dfa-8c0f-632d-d3b7e6b59fb0
| src/main/efaps/ESJP/org/efaps/esjp/admin/user/Group_Base.java | - kenel-install: update of basd esjp for Groups | <ide><path>rc/main/efaps/ESJP/org/efaps/esjp/admin/user/Group_Base.java
<ide> import java.util.Comparator;
<ide> import java.util.List;
<ide>
<add>import org.efaps.admin.datamodel.ui.FieldValue;
<ide> import org.efaps.admin.event.Parameter;
<add>import org.efaps.admin.event.Parameter.ParameterValues;
<ide> import org.efaps.admin.event.Return;
<ide> import org.efaps.admin.event.Return.ReturnValues;
<ide> import org.efaps.admin.program.esjp.EFapsRevision;
<ide> throws EFapsException
<ide> {
<ide> final Return ret = new Return();
<add> final FieldValue fieldValue = (FieldValue) _parameter.get(ParameterValues.UIOBJECT);
<add> final Object value = fieldValue.getValue();
<add>
<ide> final List<DropDownPosition> dropDownList = new ArrayList<DropDownPosition>();
<ide> for (final Long groupId : Context.getThreadContext().getPerson().getGroups()) {
<ide> final org.efaps.admin.user.Group group = org.efaps.admin.user.Group.get(groupId);
<del> dropDownList.add(new DropDownPosition(groupId, group.getName(), group.getName()));
<add> final DropDownPosition ddPos = new DropDownPosition(groupId, group.getName(), group.getName());
<add> ddPos.setSelected(value != null && ((org.efaps.admin.user.Group) value).equals(group));
<add> dropDownList.add(ddPos);
<ide> }
<ide> if (dropDownList.isEmpty()) {
<ide> final QueryBuilder queryBldr = new QueryBuilder(CIAdminUser.Group);
<ide> while (query.next()) {
<ide> final org.efaps.admin.user.Group group = org.efaps.admin.user.Group
<ide> .get(query.getCurrentValue().getId());
<del> dropDownList.add(new DropDownPosition(group.getId(), group.getName(), group.getName()));
<add> final DropDownPosition ddPos = new DropDownPosition(group.getId(), group.getName(), group.getName());
<add> ddPos.setSelected(value != null && ((org.efaps.admin.user.Group) value).equals(group));
<add> dropDownList.add(ddPos);
<ide> }
<ide> }
<add>
<ide> Collections.sort(dropDownList, new Comparator<DropDownPosition>()
<ide> {
<del>
<ide> @SuppressWarnings("unchecked")
<ide> @Override
<ide> public int compare(final DropDownPosition _o1, |
|
Java | mit | c3e55c9f13af2e169466707b8a3a6f2acd179e3f | 0 | osiam/connector4java | /*
* Copyright (C) 2013 tarent AG
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.osiam.client;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.google.common.base.Strings;
import org.glassfish.jersey.client.ClientProperties;
import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
import org.osiam.client.exception.BadCredentialsException;
import org.osiam.client.exception.BadRequestException;
import org.osiam.client.exception.ClientAlreadyExistsException;
import org.osiam.client.exception.ClientNotFoundException;
import org.osiam.client.exception.ConflictException;
import org.osiam.client.exception.ConnectionInitializationException;
import org.osiam.client.exception.ForbiddenException;
import org.osiam.client.exception.OAuthErrorMessage;
import org.osiam.client.exception.OsiamClientException;
import org.osiam.client.exception.UnauthorizedException;
import org.osiam.client.oauth.AccessToken;
import org.osiam.client.oauth.Client;
import org.osiam.client.oauth.GrantType;
import org.osiam.client.oauth.Scope;
import javax.ws.rs.ProcessingException;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Form;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.Response.StatusType;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.UriBuilderException;
import java.io.IOException;
import java.net.URI;
import java.util.List;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static org.osiam.client.OsiamConnector.objectMapper;
/**
* The AuthService provides access to the OAuth2 service used to authorize requests. Please use the
* {@link AuthService.Builder} to construct one.
*/
class AuthService {
private static final String AUTHORIZATION_HEADER = "Authorization";
private static final String BEARER = "Bearer ";
private static final String TOKEN_ENDPOINT = "/oauth/token";
private static final String TOKEN_REVOCATION_ENDPOINT = "/token/revocation";
private static final String TOKEN_VALIDATION_ENDPOINT = "/token/validation";
private static final String CLIENT_ENDPOINT = "/Client";
private final String endpoint;
private final String clientId;
private final String clientSecret;
private final String clientRedirectUri;
private final int connectionTimeout;
private final int readTimeout;
private final WebTarget targetEndpoint;
private AuthService(Builder builder) {
endpoint = builder.endpoint;
clientId = builder.clientId;
clientSecret = builder.clientSecret;
clientRedirectUri = builder.clientRedirectUri;
connectionTimeout = builder.connectTimeout;
readTimeout = builder.readTimeout;
targetEndpoint = OsiamConnector.getClient().target(endpoint);
}
public AccessToken retrieveAccessToken(Scope... scopes) {
ensureClientCredentialsAreSet();
String formattedScopes = getScopesAsString(scopes);
Form form = new Form();
form.param("scope", formattedScopes);
form.param("grant_type", GrantType.CLIENT_CREDENTIALS.getUrlParam());
StatusType status;
String content;
try {
Response response = targetEndpoint.path(TOKEN_ENDPOINT)
.request(MediaType.APPLICATION_JSON)
.property(HttpAuthenticationFeature.HTTP_AUTHENTICATION_USERNAME, clientId)
.property(HttpAuthenticationFeature.HTTP_AUTHENTICATION_PASSWORD, clientSecret)
.property(ClientProperties.CONNECT_TIMEOUT, connectionTimeout)
.property(ClientProperties.READ_TIMEOUT, readTimeout)
.post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE));
status = response.getStatusInfo();
content = response.readEntity(String.class);
} catch (ProcessingException e) {
throw createGeneralConnectionInitializationException(e);
}
checkAndHandleResponse(content, status, new AccessToken.Builder("n/a").build());
return getAccessToken(content);
}
public AccessToken retrieveAccessToken(String userName, String password, Scope... scopes) {
ensureClientCredentialsAreSet();
String formattedScopes = getScopesAsString(scopes);
Form form = new Form();
form.param("scope", formattedScopes);
form.param("grant_type", GrantType.RESOURCE_OWNER_PASSWORD_CREDENTIALS.getUrlParam());
form.param("username", userName);
form.param("password", password);
StatusType status;
String content;
try {
Response response = targetEndpoint.path(TOKEN_ENDPOINT)
.request(MediaType.APPLICATION_JSON)
.property(HttpAuthenticationFeature.HTTP_AUTHENTICATION_USERNAME, clientId)
.property(HttpAuthenticationFeature.HTTP_AUTHENTICATION_PASSWORD, clientSecret)
.property(ClientProperties.CONNECT_TIMEOUT, connectionTimeout)
.property(ClientProperties.READ_TIMEOUT, readTimeout)
.post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE));
status = response.getStatusInfo();
content = response.readEntity(String.class);
} catch (ProcessingException e) {
throw createGeneralConnectionInitializationException(e);
}
checkAndHandleResponse(content, status, new AccessToken.Builder("n/a").build());
return getAccessToken(content);
}
public AccessToken retrieveAccessToken(String authCode) {
checkArgument(!Strings.isNullOrEmpty(authCode), "The given authentication code can't be null.");
ensureClientCredentialsAreSet();
Form form = new Form();
form.param("code", authCode);
form.param("grant_type", "authorization_code");
form.param("redirect_uri", clientRedirectUri);
StatusType status;
String content;
try {
Response response = targetEndpoint.path(TOKEN_ENDPOINT)
.request(MediaType.APPLICATION_JSON)
.property(HttpAuthenticationFeature.HTTP_AUTHENTICATION_USERNAME, clientId)
.property(HttpAuthenticationFeature.HTTP_AUTHENTICATION_PASSWORD, clientSecret)
.property(ClientProperties.CONNECT_TIMEOUT, connectionTimeout)
.property(ClientProperties.READ_TIMEOUT, readTimeout)
.post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE));
status = response.getStatusInfo();
content = response.readEntity(String.class);
} catch (ProcessingException e) {
throw createGeneralConnectionInitializationException(e);
}
if (status.getStatusCode() == Status.BAD_REQUEST.getStatusCode()) {
String errorMessage = extractErrorMessage(content, status);
throw new ConflictException(errorMessage);
}
checkAndHandleResponse(content, status, new AccessToken.Builder("n/a").build());
return getAccessToken(content);
}
private String getScopesAsString(Scope... scopes) {
StringBuilder scopeBuilder = new StringBuilder();
for (Scope scope : scopes) {
scopeBuilder.append(scope.toString()).append(" ");
}
return scopeBuilder.toString().trim();
}
public AccessToken refreshAccessToken(AccessToken accessToken, Scope... scopes) {
checkArgument(accessToken != null, "The given accessToken code can't be null.");
checkArgument(accessToken.getRefreshToken() != null,
"Unable to perform a refresh_token_grant request without refresh token.");
ensureClientCredentialsAreSet();
String formattedScopes = getScopesAsString(scopes);
Form form = new Form();
form.param("scope", formattedScopes);
form.param("grant_type", GrantType.REFRESH_TOKEN.getUrlParam());
form.param("refresh_token", accessToken.getRefreshToken());
StatusType status;
String content;
try {
Response response = targetEndpoint.path(TOKEN_ENDPOINT)
.request(MediaType.APPLICATION_JSON)
.property(HttpAuthenticationFeature.HTTP_AUTHENTICATION_USERNAME, clientId)
.property(HttpAuthenticationFeature.HTTP_AUTHENTICATION_PASSWORD, clientSecret)
.property(ClientProperties.CONNECT_TIMEOUT, connectionTimeout)
.property(ClientProperties.READ_TIMEOUT, readTimeout)
.post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE));
status = response.getStatusInfo();
content = response.readEntity(String.class);
} catch (ProcessingException e) {
throw createGeneralConnectionInitializationException(e);
}
// need to override default behavior of checkAndHandleResponse
if (status.getStatusCode() == Status.BAD_REQUEST.getStatusCode()) {
throw new ConflictException(extractErrorMessage(content, status));
}
checkAndHandleResponse(content, status, accessToken);
return getAccessToken(content);
}
public URI getAuthorizationUri(Scope... scopes) {
checkState(!Strings.isNullOrEmpty(clientRedirectUri), "Can't create the login uri: redirect URI was not set.");
try {
String formattedScopes = getScopesAsString(scopes);
return UriBuilder.fromUri(endpoint).path("/oauth/authorize")
.queryParam("client_id", clientId)
.queryParam("response_type", "code")
.queryParam("redirect_uri", clientRedirectUri)
.queryParam("scope", formattedScopes)
.build();
} catch (UriBuilderException | IllegalArgumentException e) {
throw new OsiamClientException("Unable to create redirect URI", e);
}
}
/**
* @see OsiamConnector#validateAccessToken(AccessToken)
*/
public AccessToken validateAccessToken(AccessToken tokenToValidate) {
checkNotNull(tokenToValidate, "The tokenToValidate must not be null.");
StatusType status;
String content;
try {
Response response = targetEndpoint.path(TOKEN_VALIDATION_ENDPOINT)
.request(MediaType.APPLICATION_JSON)
.property(HttpAuthenticationFeature.HTTP_AUTHENTICATION_USERNAME, clientId)
.property(HttpAuthenticationFeature.HTTP_AUTHENTICATION_PASSWORD, clientSecret)
.property(ClientProperties.CONNECT_TIMEOUT, connectionTimeout)
.property(ClientProperties.READ_TIMEOUT, readTimeout)
.header(AUTHORIZATION_HEADER, BEARER + tokenToValidate.getToken())
.post(null);
status = response.getStatusInfo();
content = response.readEntity(String.class);
} catch (ProcessingException e) {
throw createGeneralConnectionInitializationException(e);
}
checkAndHandleResponse(content, status, tokenToValidate);
return getAccessToken(content);
}
public void revokeAccessToken(AccessToken tokenToRevoke) {
StatusType status;
String content;
try {
Response response = targetEndpoint.path(TOKEN_REVOCATION_ENDPOINT)
.request(MediaType.APPLICATION_JSON)
.property(HttpAuthenticationFeature.HTTP_AUTHENTICATION_USERNAME, clientId)
.property(HttpAuthenticationFeature.HTTP_AUTHENTICATION_PASSWORD, clientSecret)
.property(ClientProperties.CONNECT_TIMEOUT, connectionTimeout)
.property(ClientProperties.READ_TIMEOUT, readTimeout)
.header(AUTHORIZATION_HEADER, BEARER + tokenToRevoke.getToken())
.post(null);
status = response.getStatusInfo();
content = response.readEntity(String.class);
} catch (ProcessingException e) {
throw createGeneralConnectionInitializationException(e);
}
checkAndHandleResponse(content, status, tokenToRevoke);
}
public void revokeAllAccessTokens(String id, AccessToken accessToken) {
StatusType status;
String content;
try {
Response response = targetEndpoint.path(TOKEN_REVOCATION_ENDPOINT).path(id)
.request(MediaType.APPLICATION_JSON)
.property(HttpAuthenticationFeature.HTTP_AUTHENTICATION_USERNAME, clientId)
.property(HttpAuthenticationFeature.HTTP_AUTHENTICATION_PASSWORD, clientSecret)
.property(ClientProperties.CONNECT_TIMEOUT, connectionTimeout)
.property(ClientProperties.READ_TIMEOUT, readTimeout)
.header(AUTHORIZATION_HEADER, BEARER + accessToken.getToken())
.post(null);
status = response.getStatusInfo();
content = response.readEntity(String.class);
} catch (ProcessingException e) {
throw createGeneralConnectionInitializationException(e);
}
checkAndHandleResponse(content, status, accessToken);
}
public Client createClient(Client client, AccessToken accessToken) {
StatusType status;
String createdClient;
String clientAsString;
try {
clientAsString = objectMapper.writeValueAsString(client);
} catch (JsonProcessingException e) {
throw new OsiamClientException(String.format("Unable to parse Client: %s", client), e);
}
try {
Response response = targetEndpoint.path(CLIENT_ENDPOINT)
.request(MediaType.APPLICATION_JSON)
.property(HttpAuthenticationFeature.HTTP_AUTHENTICATION_USERNAME, clientId)
.property(HttpAuthenticationFeature.HTTP_AUTHENTICATION_PASSWORD, clientSecret)
.property(ClientProperties.CONNECT_TIMEOUT, connectionTimeout)
.property(ClientProperties.READ_TIMEOUT, readTimeout)
.header(AUTHORIZATION_HEADER, BEARER + accessToken.getToken())
.post(Entity.entity(clientAsString, MediaType.APPLICATION_JSON));
status = response.getStatusInfo();
createdClient = response.readEntity(String.class);
} catch (ProcessingException e) {
throw createGeneralConnectionInitializationException(e);
}
// need to override default behavior of checkAndHandleResponse
if (status.getStatusCode() == Status.CONFLICT.getStatusCode()) {
throw new ClientAlreadyExistsException(extractErrorMessage(createdClient, status));
}
checkAndHandleResponse(createdClient, status, accessToken);
try {
return objectMapper.readValue(createdClient, Client.class);
} catch (IOException e) {
throw new OsiamClientException(String.format("Unable to parse Client: %s", createdClient), e);
}
}
public Client getClient(String getClientId, AccessToken accessToken) {
StatusType status;
String client;
try {
Response response = targetEndpoint.path(CLIENT_ENDPOINT).path(getClientId)
.request(MediaType.APPLICATION_JSON)
.property(HttpAuthenticationFeature.HTTP_AUTHENTICATION_USERNAME, clientId)
.property(HttpAuthenticationFeature.HTTP_AUTHENTICATION_PASSWORD, clientSecret)
.property(ClientProperties.CONNECT_TIMEOUT, connectionTimeout)
.property(ClientProperties.READ_TIMEOUT, readTimeout)
.header(AUTHORIZATION_HEADER, BEARER + accessToken.getToken())
.get();
status = response.getStatusInfo();
client = response.readEntity(String.class);
} catch (ProcessingException e) {
throw createGeneralConnectionInitializationException(e);
}
checkAndHandleResponse(client, status, accessToken);
try {
return objectMapper.readValue(client, Client.class);
} catch (IOException e) {
throw new OsiamClientException(String.format("Unable to parse Client: %s", client), e);
}
}
public List<Client> getClients(AccessToken accessToken) {
StatusType status;
String clients;
try {
Response response = targetEndpoint.path(CLIENT_ENDPOINT)
.request(MediaType.APPLICATION_JSON)
.property(HttpAuthenticationFeature.HTTP_AUTHENTICATION_USERNAME, clientId)
.property(HttpAuthenticationFeature.HTTP_AUTHENTICATION_PASSWORD, clientSecret)
.property(ClientProperties.CONNECT_TIMEOUT, connectionTimeout)
.property(ClientProperties.READ_TIMEOUT, readTimeout)
.header(AUTHORIZATION_HEADER, BEARER + accessToken.getToken())
.get();
status = response.getStatusInfo();
clients = response.readEntity(String.class);
} catch (ProcessingException e) {
throw createGeneralConnectionInitializationException(e);
}
checkAndHandleResponse(clients, status, accessToken);
try {
return objectMapper.readValue(clients, new TypeReference<List<Client>>() {
});
} catch (IOException e) {
throw new OsiamClientException(String.format("Unable to parse list of Clients: %s", clients), e);
}
}
public void deleteClient(String deleteClientId, AccessToken accessToken) {
StatusType status;
String content;
try {
Response response = targetEndpoint.path(CLIENT_ENDPOINT).path(deleteClientId)
.request(MediaType.APPLICATION_JSON)
.property(HttpAuthenticationFeature.HTTP_AUTHENTICATION_USERNAME, clientId)
.property(HttpAuthenticationFeature.HTTP_AUTHENTICATION_PASSWORD, clientSecret)
.property(ClientProperties.CONNECT_TIMEOUT, connectionTimeout)
.property(ClientProperties.READ_TIMEOUT, readTimeout)
.header(AUTHORIZATION_HEADER, BEARER + accessToken.getToken())
.delete();
status = response.getStatusInfo();
content = response.readEntity(String.class);
} catch (ProcessingException e) {
throw createGeneralConnectionInitializationException(e);
}
checkAndHandleResponse(content, status, accessToken);
}
public Client updateClient(String updateClientId, Client client, AccessToken accessToken) {
StatusType status;
String clientResponse;
String clientAsString;
try {
clientAsString = objectMapper.writeValueAsString(client);
} catch (JsonProcessingException e) {
throw new OsiamClientException(String.format("Unable to parse Client: %s", client), e);
}
try {
Response response = targetEndpoint.path(CLIENT_ENDPOINT).path(updateClientId)
.request(MediaType.APPLICATION_JSON)
.property(HttpAuthenticationFeature.HTTP_AUTHENTICATION_USERNAME, clientId)
.property(HttpAuthenticationFeature.HTTP_AUTHENTICATION_PASSWORD, clientSecret)
.property(ClientProperties.CONNECT_TIMEOUT, connectionTimeout)
.property(ClientProperties.READ_TIMEOUT, readTimeout)
.header(AUTHORIZATION_HEADER, BEARER + accessToken.getToken())
.put(Entity.entity(clientAsString, MediaType.APPLICATION_JSON));
status = response.getStatusInfo();
clientResponse = response.readEntity(String.class);
} catch (ProcessingException e) {
throw createGeneralConnectionInitializationException(e);
}
checkAndHandleResponse(clientResponse, status, accessToken);
try {
return objectMapper.readValue(clientResponse, Client.class);
} catch (IOException e) {
throw new OsiamClientException(String.format("Unable to parse Client: %s", clientResponse), e);
}
}
private void checkAndHandleResponse(String content, StatusType status, AccessToken accessToken) {
if (status.getFamily() == Status.Family.SUCCESSFUL) {
return;
}
if (status.getStatusCode() == Status.BAD_REQUEST.getStatusCode()) {
String errorMessage = extractErrorMessage(content, status);
if (errorMessage.equals("Bad credentials")) {
throw new BadCredentialsException(errorMessage);
} else {
throw new BadRequestException(errorMessage);
}
} else if (status.getStatusCode() == Status.UNAUTHORIZED.getStatusCode()) {
String errorMessage = extractErrorMessage(content, status);
throw new UnauthorizedException(errorMessage);
} else if (status.getStatusCode() == Status.FORBIDDEN.getStatusCode()) {
String errorMessage = extractErrorMessageForbidden(accessToken);
throw new ForbiddenException(errorMessage);
} else if (status.getStatusCode() == Status.NOT_FOUND.getStatusCode()) {
String errorMessage = extractErrorMessage(content, status);
throw new ClientNotFoundException(errorMessage);
} else if (status.getStatusCode() == Status.CONFLICT.getStatusCode()) {
String errorMessage = extractErrorMessage(content, status);
throw new ConflictException(errorMessage);
} else {
String errorMessage = extractErrorMessage(content, status);
throw new ConnectionInitializationException(errorMessage);
}
}
private String extractErrorMessage(String content, StatusType status) {
try {
OAuthErrorMessage error = objectMapper.readValue(content, OAuthErrorMessage.class);
return error.getDescription();
} catch (IOException e) {
String errorMessage = String.format("Could not deserialize the error response for the HTTP status '%s'.",
status.getReasonPhrase());
if (content != null) {
errorMessage += String.format(" Original response: %s", content);
}
return errorMessage;
}
}
protected String extractErrorMessageForbidden(AccessToken accessToken) {
return "Insufficient scopes: " + accessToken.getScopes();
}
private AccessToken getAccessToken(String content) {
try {
return objectMapper.readValue(content, AccessToken.class);
} catch (IOException e) {
throw new OsiamClientException(String.format("Unable to parse access token: %s", content), e);
}
}
private void ensureClientCredentialsAreSet() {
checkState(!Strings.isNullOrEmpty(clientId), "The client id can't be null or empty.");
checkState(!Strings.isNullOrEmpty(clientSecret), "The client secret can't be null or empty.");
}
private ConnectionInitializationException createGeneralConnectionInitializationException(Throwable e) {
return new ConnectionInitializationException("Unable to retrieve access token.", e);
}
/**
* The Builder class is used to construct instances of the {@link AuthService}.
*/
public static class Builder {
private String clientId;
private String clientSecret;
private String endpoint;
private String clientRedirectUri;
private int connectTimeout = OsiamConnector.DEFAULT_CONNECT_TIMEOUT;
private int readTimeout = OsiamConnector.DEFAULT_READ_TIMEOUT;
/**
* Set up the Builder for the construction of an {@link AuthService} instance for the OAuth2 service at the
* given endpoint
*
* @param endpoint The URL at which the OAuth2 service lives.
*/
public Builder(String endpoint) {
this.endpoint = endpoint;
}
/**
* Add a ClientId to the OAuth2 request
*
* @param clientId The client-Id
* @return The builder itself
*/
public Builder setClientId(String clientId) {
this.clientId = clientId;
return this;
}
/**
* Add a Client redirect URI to the OAuth2 request
*
* @param clientRedirectUri the clientRedirectUri which is known to the OSIAM server
* @return The builder itself
*/
public Builder setClientRedirectUri(String clientRedirectUri) {
this.clientRedirectUri = clientRedirectUri;
return this;
}
/**
* Add a clientSecret to the OAuth2 request
*
* @param clientSecret The client secret
* @return The builder itself
*/
public Builder setClientSecret(String clientSecret) {
this.clientSecret = clientSecret;
return this;
}
/**
* Set the connect timeout per connector, in milliseconds.
* <p/>
* <p>
* A value of zero (0) is equivalent to an interval of infinity. Default: 0
* </p>
*
* @param connectTimeout the connect timeout per connector, in milliseconds.
* @return The builder itself
*/
public Builder withConnectTimeout(int connectTimeout) {
this.connectTimeout = connectTimeout;
return this;
}
/**
* Set the read timeout per connector, in milliseconds.
* <p/>
* <p>
* A value of zero (0) is equivalent to an interval of infinity. Default: 0
* </p>
*
* @param readTimeout the read timeout per connector, in milliseconds.
* @return The builder itself
*/
public Builder withReadTimeout(int readTimeout) {
this.readTimeout = readTimeout;
return this;
}
/**
* Construct the {@link AuthService} with the parameters passed to this builder.
*
* @return An {@link AuthService} configured accordingly.
*/
public AuthService build() {
return new AuthService(this);
}
}
}
| src/main/java/org/osiam/client/AuthService.java | /*
* Copyright (C) 2013 tarent AG
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.osiam.client;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.google.common.base.Strings;
import org.glassfish.jersey.client.ClientProperties;
import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
import org.osiam.client.exception.BadCredentialsException;
import org.osiam.client.exception.BadRequestException;
import org.osiam.client.exception.ClientAlreadyExistsException;
import org.osiam.client.exception.ClientNotFoundException;
import org.osiam.client.exception.ConflictException;
import org.osiam.client.exception.ConnectionInitializationException;
import org.osiam.client.exception.ForbiddenException;
import org.osiam.client.exception.OAuthErrorMessage;
import org.osiam.client.exception.OsiamClientException;
import org.osiam.client.exception.UnauthorizedException;
import org.osiam.client.oauth.AccessToken;
import org.osiam.client.oauth.Client;
import org.osiam.client.oauth.GrantType;
import org.osiam.client.oauth.Scope;
import javax.ws.rs.ProcessingException;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Form;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.Response.StatusType;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.UriBuilderException;
import java.io.IOException;
import java.net.URI;
import java.util.List;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static org.osiam.client.OsiamConnector.objectMapper;
/**
* The AuthService provides access to the OAuth2 service used to authorize requests. Please use the
* {@link AuthService.Builder} to construct one.
*/
class AuthService {
private static final String AUTHORIZATION_HEADER = "Authorization";
private static final String BEARER = "Bearer ";
private static final String TOKEN_ENDPOINT = "/oauth/token";
private static final String TOKEN_REVOCATION_ENDPOINT = "/token/revocation";
private static final String TOKEN_VALIDATION_ENDPOINT = "/token/validation";
private static final String CLIENT_ENDPOINT = "/Client";
private final String endpoint;
private final String clientId;
private final String clientSecret;
private final String clientRedirectUri;
private final int connectionTimeout;
private final int readTimeout;
private final WebTarget targetEndpoint;
private AuthService(Builder builder) {
endpoint = builder.endpoint;
clientId = builder.clientId;
clientSecret = builder.clientSecret;
clientRedirectUri = builder.clientRedirectUri;
connectionTimeout = builder.connectTimeout;
readTimeout = builder.readTimeout;
targetEndpoint = OsiamConnector.getClient().target(endpoint);
}
public AccessToken retrieveAccessToken(Scope... scopes) {
ensureClientCredentialsAreSet();
String formattedScopes = getScopesAsString(scopes);
Form form = new Form();
form.param("scope", formattedScopes);
form.param("grant_type", GrantType.CLIENT_CREDENTIALS.getUrlParam());
StatusType status;
String content;
try {
Response response = targetEndpoint.path(TOKEN_ENDPOINT)
.request(MediaType.APPLICATION_JSON)
.property(HttpAuthenticationFeature.HTTP_AUTHENTICATION_USERNAME, clientId)
.property(HttpAuthenticationFeature.HTTP_AUTHENTICATION_PASSWORD, clientSecret)
.property(ClientProperties.CONNECT_TIMEOUT, connectionTimeout)
.property(ClientProperties.READ_TIMEOUT, readTimeout)
.post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE));
status = response.getStatusInfo();
content = response.readEntity(String.class);
} catch (ProcessingException e) {
throw createGeneralConnectionInitializationException(e);
}
checkAndHandleResponse(content, status, new AccessToken.Builder("n/a").build());
return getAccessToken(content);
}
public AccessToken retrieveAccessToken(String userName, String password, Scope... scopes) {
ensureClientCredentialsAreSet();
String formattedScopes = getScopesAsString(scopes);
Form form = new Form();
form.param("scope", formattedScopes);
form.param("grant_type", GrantType.RESOURCE_OWNER_PASSWORD_CREDENTIALS.getUrlParam());
form.param("username", userName);
form.param("password", password);
StatusType status;
String content;
try {
Response response = targetEndpoint.path(TOKEN_ENDPOINT)
.request(MediaType.APPLICATION_JSON)
.property(HttpAuthenticationFeature.HTTP_AUTHENTICATION_USERNAME, clientId)
.property(HttpAuthenticationFeature.HTTP_AUTHENTICATION_PASSWORD, clientSecret)
.property(ClientProperties.CONNECT_TIMEOUT, connectionTimeout)
.property(ClientProperties.READ_TIMEOUT, readTimeout)
.post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE));
status = response.getStatusInfo();
content = response.readEntity(String.class);
} catch (ProcessingException e) {
throw createGeneralConnectionInitializationException(e);
}
checkAndHandleResponse(content, status, new AccessToken.Builder("n/a").build());
return getAccessToken(content);
}
public AccessToken retrieveAccessToken(String authCode) {
checkArgument(!Strings.isNullOrEmpty(authCode), "The given authentication code can't be null.");
ensureClientCredentialsAreSet();
Form form = new Form();
form.param("code", authCode);
form.param("grant_type", "authorization_code");
form.param("redirect_uri", clientRedirectUri);
StatusType status;
String content;
try {
Response response = targetEndpoint.path(TOKEN_ENDPOINT)
.request(MediaType.APPLICATION_JSON)
.property(HttpAuthenticationFeature.HTTP_AUTHENTICATION_USERNAME, clientId)
.property(HttpAuthenticationFeature.HTTP_AUTHENTICATION_PASSWORD, clientSecret)
.property(ClientProperties.CONNECT_TIMEOUT, connectionTimeout)
.property(ClientProperties.READ_TIMEOUT, readTimeout)
.post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE));
status = response.getStatusInfo();
content = response.readEntity(String.class);
} catch (ProcessingException e) {
throw createGeneralConnectionInitializationException(e);
}
if (status.getStatusCode() == Status.BAD_REQUEST.getStatusCode()) {
String errorMessage = extractErrorMessage(content, status);
throw new ConflictException(errorMessage);
}
checkAndHandleResponse(content, status, new AccessToken.Builder("n/a").build());
return getAccessToken(content);
}
private String getScopesAsString(Scope... scopes) {
StringBuilder scopeBuilder = new StringBuilder();
for (Scope scope : scopes) {
scopeBuilder.append(scope.toString()).append(" ");
}
return scopeBuilder.toString().trim();
}
public AccessToken refreshAccessToken(AccessToken accessToken, Scope... scopes) {
checkArgument(accessToken != null, "The given accessToken code can't be null.");
checkArgument(accessToken.getRefreshToken() != null,
"Unable to perform a refresh_token_grant request without refresh token.");
ensureClientCredentialsAreSet();
String formattedScopes = getScopesAsString(scopes);
Form form = new Form();
form.param("scope", formattedScopes);
form.param("grant_type", GrantType.REFRESH_TOKEN.getUrlParam());
form.param("refresh_token", accessToken.getRefreshToken());
StatusType status;
String content;
try {
Response response = targetEndpoint.path(TOKEN_ENDPOINT)
.request(MediaType.APPLICATION_JSON)
.property(HttpAuthenticationFeature.HTTP_AUTHENTICATION_USERNAME, clientId)
.property(HttpAuthenticationFeature.HTTP_AUTHENTICATION_PASSWORD, clientSecret)
.property(ClientProperties.CONNECT_TIMEOUT, connectionTimeout)
.property(ClientProperties.READ_TIMEOUT, readTimeout)
.post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE));
status = response.getStatusInfo();
content = response.readEntity(String.class);
} catch (ProcessingException e) {
throw createGeneralConnectionInitializationException(e);
}
// need to override default behavior of checkAndHandleResponse
if (status.getStatusCode() == Status.BAD_REQUEST.getStatusCode()) {
throw new ConflictException(extractErrorMessage(content, status));
}
checkAndHandleResponse(content, status, accessToken);
return getAccessToken(content);
}
public URI getAuthorizationUri(Scope... scopes) {
checkState(!Strings.isNullOrEmpty(clientRedirectUri), "Can't create the login uri: redirect URI was not set.");
try {
String formattedScopes = getScopesAsString(scopes);
return UriBuilder.fromUri(endpoint).path("/oauth/authorize")
.queryParam("client_id", clientId)
.queryParam("response_type", "code")
.queryParam("redirect_uri", clientRedirectUri)
.queryParam("scope", formattedScopes)
.build();
} catch (UriBuilderException | IllegalArgumentException e) {
throw new OsiamClientException("Unable to create redirect URI", e);
}
}
/**
* @see OsiamConnector#validateAccessToken(AccessToken)
*/
public AccessToken validateAccessToken(AccessToken tokenToValidate) {
checkNotNull(tokenToValidate, "The tokenToValidate must not be null.");
StatusType status;
String content;
try {
Response response = targetEndpoint.path(TOKEN_VALIDATION_ENDPOINT)
.request(MediaType.APPLICATION_JSON)
.property(HttpAuthenticationFeature.HTTP_AUTHENTICATION_USERNAME, clientId)
.property(HttpAuthenticationFeature.HTTP_AUTHENTICATION_PASSWORD, clientSecret)
.property(ClientProperties.CONNECT_TIMEOUT, connectionTimeout)
.property(ClientProperties.READ_TIMEOUT, readTimeout)
.header(AUTHORIZATION_HEADER, BEARER + tokenToValidate.getToken())
.post(null);
status = response.getStatusInfo();
content = response.readEntity(String.class);
} catch (ProcessingException e) {
throw createGeneralConnectionInitializationException(e);
}
checkAndHandleResponse(content, status, tokenToValidate);
return getAccessToken(content);
}
public void revokeAccessToken(AccessToken tokenToRevoke) {
StatusType status;
String content;
try {
Response response = targetEndpoint.path(TOKEN_REVOCATION_ENDPOINT)
.request(MediaType.APPLICATION_JSON)
.property(HttpAuthenticationFeature.HTTP_AUTHENTICATION_USERNAME, clientId)
.property(HttpAuthenticationFeature.HTTP_AUTHENTICATION_PASSWORD, clientSecret)
.property(ClientProperties.CONNECT_TIMEOUT, connectionTimeout)
.property(ClientProperties.READ_TIMEOUT, readTimeout)
.header(AUTHORIZATION_HEADER, BEARER + tokenToRevoke.getToken())
.post(null);
status = response.getStatusInfo();
content = response.readEntity(String.class);
} catch (ProcessingException e) {
throw createGeneralConnectionInitializationException(e);
}
checkAndHandleResponse(content, status, tokenToRevoke);
}
public void revokeAllAccessTokens(String id, AccessToken accessToken) {
StatusType status;
String content;
try {
Response response = targetEndpoint.path(TOKEN_REVOCATION_ENDPOINT).path(id)
.request(MediaType.APPLICATION_JSON)
.property(HttpAuthenticationFeature.HTTP_AUTHENTICATION_USERNAME, clientId)
.property(HttpAuthenticationFeature.HTTP_AUTHENTICATION_PASSWORD, clientSecret)
.property(ClientProperties.CONNECT_TIMEOUT, connectionTimeout)
.property(ClientProperties.READ_TIMEOUT, readTimeout)
.header(AUTHORIZATION_HEADER, BEARER + accessToken.getToken())
.post(null);
status = response.getStatusInfo();
content = response.readEntity(String.class);
} catch (ProcessingException e) {
throw createGeneralConnectionInitializationException(e);
}
checkAndHandleResponse(content, status, accessToken);
}
public Client createClient(Client client, AccessToken accessToken) {
StatusType status;
String createdClient;
String clientAsString;
try {
clientAsString = objectMapper.writeValueAsString(client);
} catch (JsonProcessingException e) {
throw new OsiamClientException(String.format("Unable to parse Client: %s", client), e);
}
try {
Response response = targetEndpoint.path(CLIENT_ENDPOINT)
.request(MediaType.APPLICATION_JSON)
.property(HttpAuthenticationFeature.HTTP_AUTHENTICATION_USERNAME, clientId)
.property(HttpAuthenticationFeature.HTTP_AUTHENTICATION_PASSWORD, clientSecret)
.property(ClientProperties.CONNECT_TIMEOUT, connectionTimeout)
.property(ClientProperties.READ_TIMEOUT, readTimeout)
.header(AUTHORIZATION_HEADER, BEARER + accessToken.getToken())
.post(Entity.entity(clientAsString, MediaType.APPLICATION_JSON));
status = response.getStatusInfo();
createdClient = response.readEntity(String.class);
} catch (ProcessingException e) {
throw createGeneralConnectionInitializationException(e);
}
// need to override default behavior of checkAndHandleResponse
if (status.getStatusCode() == Status.CONFLICT.getStatusCode()) {
throw new ClientAlreadyExistsException(extractErrorMessage(createdClient, status));
}
checkAndHandleResponse(createdClient, status, accessToken);
try {
return objectMapper.readValue(createdClient, Client.class);
} catch (IOException e) {
throw new OsiamClientException(String.format("Unable to parse Client: %s", createdClient), e);
}
}
public Client getClient(String getClientId, AccessToken accessToken) {
StatusType status;
String client;
try {
Response response = targetEndpoint.path(CLIENT_ENDPOINT).path(getClientId)
.request(MediaType.APPLICATION_JSON)
.property(HttpAuthenticationFeature.HTTP_AUTHENTICATION_USERNAME, clientId)
.property(HttpAuthenticationFeature.HTTP_AUTHENTICATION_PASSWORD, clientSecret)
.property(ClientProperties.CONNECT_TIMEOUT, connectionTimeout)
.property(ClientProperties.READ_TIMEOUT, readTimeout)
.header(AUTHORIZATION_HEADER, BEARER + accessToken.getToken())
.get();
status = response.getStatusInfo();
client = response.readEntity(String.class);
} catch (ProcessingException e) {
throw createGeneralConnectionInitializationException(e);
}
checkAndHandleResponse(client, status, accessToken);
try {
return objectMapper.readValue(client, Client.class);
} catch (IOException e) {
throw new OsiamClientException(String.format("Unable to parse Client: %s", client), e);
}
}
public List<Client> getClients(AccessToken accessToken) {
StatusType status;
String clients;
try {
Response response = targetEndpoint.path(CLIENT_ENDPOINT)
.request(MediaType.APPLICATION_JSON)
.property(HttpAuthenticationFeature.HTTP_AUTHENTICATION_USERNAME, clientId)
.property(HttpAuthenticationFeature.HTTP_AUTHENTICATION_PASSWORD, clientSecret)
.property(ClientProperties.CONNECT_TIMEOUT, connectionTimeout)
.property(ClientProperties.READ_TIMEOUT, readTimeout)
.header(AUTHORIZATION_HEADER, BEARER + accessToken.getToken())
.get();
status = response.getStatusInfo();
clients = response.readEntity(String.class);
} catch (ProcessingException e) {
throw createGeneralConnectionInitializationException(e);
}
checkAndHandleResponse(clients, status, accessToken);
try {
return objectMapper.readValue(clients, new TypeReference<List<Client>>() {
});
} catch (IOException e) {
throw new OsiamClientException(String.format("Unable to parse list of Clients: %s", clients), e);
}
}
public void deleteClient(String deleteClientId, AccessToken accessToken) {
StatusType status;
String content;
try {
Response response = targetEndpoint.path(CLIENT_ENDPOINT).path(deleteClientId)
.request(MediaType.APPLICATION_JSON)
.property(HttpAuthenticationFeature.HTTP_AUTHENTICATION_USERNAME, clientId)
.property(HttpAuthenticationFeature.HTTP_AUTHENTICATION_PASSWORD, clientSecret)
.property(ClientProperties.CONNECT_TIMEOUT, connectionTimeout)
.property(ClientProperties.READ_TIMEOUT, readTimeout)
.header(AUTHORIZATION_HEADER, BEARER + accessToken.getToken())
.delete();
status = response.getStatusInfo();
content = response.readEntity(String.class);
} catch (ProcessingException e) {
throw createGeneralConnectionInitializationException(e);
}
checkAndHandleResponse(content, status, accessToken);
}
public Client updateClient(String updateClientId, Client client, AccessToken accessToken) {
StatusType status;
String clientResponse;
String clientAsString;
try {
clientAsString = objectMapper.writeValueAsString(client);
} catch (JsonProcessingException e) {
throw new OsiamClientException(String.format("Unable to parse Client: %s", client), e);
}
try {
Response response = targetEndpoint.path(CLIENT_ENDPOINT).path(updateClientId)
.request(MediaType.APPLICATION_JSON)
.property(HttpAuthenticationFeature.HTTP_AUTHENTICATION_USERNAME, clientId)
.property(HttpAuthenticationFeature.HTTP_AUTHENTICATION_PASSWORD, clientSecret)
.property(ClientProperties.CONNECT_TIMEOUT, connectionTimeout)
.property(ClientProperties.READ_TIMEOUT, readTimeout)
.header(AUTHORIZATION_HEADER, BEARER + accessToken.getToken())
.put(Entity.entity(clientAsString, MediaType.APPLICATION_JSON));
status = response.getStatusInfo();
clientResponse = response.readEntity(String.class);
} catch (ProcessingException e) {
throw createGeneralConnectionInitializationException(e);
}
checkAndHandleResponse(clientResponse, status, accessToken);
try {
return objectMapper.readValue(clientResponse, Client.class);
} catch (IOException e) {
throw new OsiamClientException(String.format("Unable to parse Client: %s", clientResponse), e);
}
}
private void checkAndHandleResponse(String content, StatusType status, AccessToken accessToken) {
if (status.getFamily() == Status.Family.SUCCESSFUL) {
return;
}
if (status.getStatusCode() == Status.BAD_REQUEST.getStatusCode()) {
String errorMessage = extractErrorMessage(content, status);
if (errorMessage.equals("Bad credentials")) {
throw new BadCredentialsException(content);
} else {
throw new BadRequestException(errorMessage);
}
} else if (status.getStatusCode() == Status.UNAUTHORIZED.getStatusCode()) {
String errorMessage = extractErrorMessage(content, status);
throw new UnauthorizedException(errorMessage);
} else if (status.getStatusCode() == Status.FORBIDDEN.getStatusCode()) {
String errorMessage = extractErrorMessageForbidden(accessToken);
throw new ForbiddenException(errorMessage);
} else if (status.getStatusCode() == Status.NOT_FOUND.getStatusCode()) {
String errorMessage = extractErrorMessage(content, status);
throw new ClientNotFoundException(errorMessage);
} else if (status.getStatusCode() == Status.CONFLICT.getStatusCode()) {
String errorMessage = extractErrorMessage(content, status);
throw new ConflictException(errorMessage);
} else {
String errorMessage = extractErrorMessage(content, status);
throw new ConnectionInitializationException(errorMessage);
}
}
private String extractErrorMessage(String content, StatusType status) {
try {
OAuthErrorMessage error = objectMapper.readValue(content, OAuthErrorMessage.class);
return error.getDescription();
} catch (IOException e) {
String errorMessage = String.format("Could not deserialize the error response for the HTTP status '%s'.",
status.getReasonPhrase());
if (content != null) {
errorMessage += String.format(" Original response: %s", content);
}
return errorMessage;
}
}
protected String extractErrorMessageForbidden(AccessToken accessToken) {
return "Insufficient scopes: " + accessToken.getScopes();
}
private AccessToken getAccessToken(String content) {
try {
return objectMapper.readValue(content, AccessToken.class);
} catch (IOException e) {
throw new OsiamClientException(String.format("Unable to parse access token: %s", content), e);
}
}
private void ensureClientCredentialsAreSet() {
checkState(!Strings.isNullOrEmpty(clientId), "The client id can't be null or empty.");
checkState(!Strings.isNullOrEmpty(clientSecret), "The client secret can't be null or empty.");
}
private ConnectionInitializationException createGeneralConnectionInitializationException(Throwable e) {
return new ConnectionInitializationException("Unable to retrieve access token.", e);
}
/**
* The Builder class is used to construct instances of the {@link AuthService}.
*/
public static class Builder {
private String clientId;
private String clientSecret;
private String endpoint;
private String clientRedirectUri;
private int connectTimeout = OsiamConnector.DEFAULT_CONNECT_TIMEOUT;
private int readTimeout = OsiamConnector.DEFAULT_READ_TIMEOUT;
/**
* Set up the Builder for the construction of an {@link AuthService} instance for the OAuth2 service at the
* given endpoint
*
* @param endpoint The URL at which the OAuth2 service lives.
*/
public Builder(String endpoint) {
this.endpoint = endpoint;
}
/**
* Add a ClientId to the OAuth2 request
*
* @param clientId The client-Id
* @return The builder itself
*/
public Builder setClientId(String clientId) {
this.clientId = clientId;
return this;
}
/**
* Add a Client redirect URI to the OAuth2 request
*
* @param clientRedirectUri the clientRedirectUri which is known to the OSIAM server
* @return The builder itself
*/
public Builder setClientRedirectUri(String clientRedirectUri) {
this.clientRedirectUri = clientRedirectUri;
return this;
}
/**
* Add a clientSecret to the OAuth2 request
*
* @param clientSecret The client secret
* @return The builder itself
*/
public Builder setClientSecret(String clientSecret) {
this.clientSecret = clientSecret;
return this;
}
/**
* Set the connect timeout per connector, in milliseconds.
* <p/>
* <p>
* A value of zero (0) is equivalent to an interval of infinity. Default: 0
* </p>
*
* @param connectTimeout the connect timeout per connector, in milliseconds.
* @return The builder itself
*/
public Builder withConnectTimeout(int connectTimeout) {
this.connectTimeout = connectTimeout;
return this;
}
/**
* Set the read timeout per connector, in milliseconds.
* <p/>
* <p>
* A value of zero (0) is equivalent to an interval of infinity. Default: 0
* </p>
*
* @param readTimeout the read timeout per connector, in milliseconds.
* @return The builder itself
*/
public Builder withReadTimeout(int readTimeout) {
this.readTimeout = readTimeout;
return this;
}
/**
* Construct the {@link AuthService} with the parameters passed to this builder.
*
* @return An {@link AuthService} configured accordingly.
*/
public AuthService build() {
return new AuthService(this);
}
}
}
| Fix BadCredentialsException message
| src/main/java/org/osiam/client/AuthService.java | Fix BadCredentialsException message | <ide><path>rc/main/java/org/osiam/client/AuthService.java
<ide> if (status.getStatusCode() == Status.BAD_REQUEST.getStatusCode()) {
<ide> String errorMessage = extractErrorMessage(content, status);
<ide> if (errorMessage.equals("Bad credentials")) {
<del> throw new BadCredentialsException(content);
<add> throw new BadCredentialsException(errorMessage);
<ide> } else {
<ide> throw new BadRequestException(errorMessage);
<ide> } |
|
Java | apache-2.0 | 5817f645195111ff99f376e1eae056b5bba988b4 | 0 | noear/Weed3,noear/Weed3 | package org.noear.weed;
import org.noear.weed.annotation.DbTable;
import org.noear.weed.annotation.PrimaryKey;
import java.lang.reflect.Field;
class BaseTableEntity {
public Class<?> entityType;
public String tableName;
public String pkName;
public BaseTableEntity(BaseMapper baseMapper) {
entityType = (Class<?>) baseMapper.entityType();
if(entityType == Object.class){
throw new RuntimeException("请为BaseMapper申明实体类型");
}
DbTable ann = entityType.getAnnotation(DbTable.class);
if (ann != null) {
tableName = ann.value();
}
if (tableName == null) {
tableName = entityType.getSimpleName();
}
for (Field f1 : entityType.getFields()) {
if (f1.getAnnotation(PrimaryKey.class) != null) {
pkName = f1.getName();
break;
}
}
if(pkName == null){
throw new RuntimeException("没申明主键");
}
}
}
| weed3/src/main/java/org/noear/weed/BaseTableEntity.java | package org.noear.weed;
import org.noear.weed.annotation.DbTable;
import org.noear.weed.annotation.PrimaryKey;
import java.lang.reflect.Field;
class BaseTableEntity {
public Class<?> entityType;
public String tableName;
public String pkName;
public BaseTableEntity(BaseMapper baseMapper) {
entityType = (Class<?>) baseMapper.entityType();
DbTable ann = entityType.getAnnotation(DbTable.class);
if (ann != null) {
tableName = ann.value();
}
if (tableName == null) {
tableName = entityType.getSimpleName();
}
for (Field f1 : entityType.getFields()) {
if (f1.getAnnotation(PrimaryKey.class) != null) {
pkName = f1.getName();
break;
}
}
if(pkName == null){
throw new RuntimeException("没申明主键");
}
}
}
| 3.2.3.10
| weed3/src/main/java/org/noear/weed/BaseTableEntity.java | 3.2.3.10 | <ide><path>eed3/src/main/java/org/noear/weed/BaseTableEntity.java
<ide>
<ide> public BaseTableEntity(BaseMapper baseMapper) {
<ide> entityType = (Class<?>) baseMapper.entityType();
<add>
<add> if(entityType == Object.class){
<add> throw new RuntimeException("请为BaseMapper申明实体类型");
<add> }
<ide>
<ide> DbTable ann = entityType.getAnnotation(DbTable.class);
<ide> if (ann != null) { |
|
Java | lgpl-2.1 | 75ba7b2be55129a8b5d8088e7d99cd3e74093cc5 | 0 | vaibhav345/lenskit,binweiwu/lenskit,kluver/lenskit,tajinder-txstate/lenskit,tajinder-txstate/lenskit,kluver/lenskit,tajinder-txstate/lenskit,amaliujia/lenskit,aglne/lenskit,tajinder-txstate/lenskit,kluver/lenskit,linjunleo/lenskit,aglne/lenskit,amaliujia/lenskit,kluver/lenskit,vaibhav345/lenskit,blankazucenalg/lenskit,linjunleo/lenskit,binweiwu/lenskit,chrysalag/lenskit,vijayvani/Lenskit,martinlaz/lenskit,blankazucenalg/lenskit,vaibhav345/lenskit,vijayvani/Lenskit,vaibhav345/lenskit,chrysalag/lenskit,kluver/lenskit,martinlaz/lenskit | /*
* LensKit, an open source recommender systems toolkit.
* Copyright 2010-2013 Regents of the University of Minnesota and contributors
* Work on LensKit has been funded by the National Science Foundation under
* grants IIS 05-34939, 08-08692, 08-12148, and 10-17697.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General 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.
*/
package org.grouplens.lenskit.eval.metrics.topn;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import it.unimi.dsi.fastutil.longs.Long2IntMap;
import it.unimi.dsi.fastutil.longs.Long2IntOpenHashMap;
import org.grouplens.lenskit.eval.Attributed;
import org.grouplens.lenskit.eval.data.traintest.TTDataSet;
import org.grouplens.lenskit.eval.metrics.AbstractTestUserMetric;
import org.grouplens.lenskit.eval.metrics.TestUserMetricAccumulator;
import org.grouplens.lenskit.eval.traintest.TestUser;
import org.grouplens.lenskit.scored.ScoredId;
import javax.annotation.Nonnull;
import java.util.Collections;
import java.util.List;
/**
*
* @author <a href="http://www.grouplens.org">GroupLens Research</a>
*/
public class TopNEntropyMetric extends AbstractTestUserMetric {
private final int listSize;
private final ItemSelector candidates;
private final ItemSelector exclude;
private final ImmutableList<String> columns;
public TopNEntropyMetric(String lbl, int listSize, ItemSelector candidates, ItemSelector exclude) {
this.listSize = listSize;
this.candidates = candidates;
this.exclude = exclude;
columns = ImmutableList.of(lbl);
}
@Override
public Accum makeAccumulator(Attributed algo, TTDataSet ds) {
return new Accum();
}
@Override
public List<String> getColumnLabels() {
return columns;
}
@Override
public List<String> getUserColumnLabels() {
return Collections.emptyList();
}
class Accum implements TestUserMetricAccumulator {
Long2IntMap counts = new Long2IntOpenHashMap();
int n = 0;
@Nonnull
@Override
public List<Object> evaluate(TestUser user) {
List<ScoredId> recs;
recs = user.getRecommendations(listSize, candidates, exclude);
if (recs == null) {
return userRow();
}
for (ScoredId s: recs) {
counts.put(s.getId(), counts.get(s.getId()) +1);
n +=1;
}
return userRow();
}
@Nonnull
@Override
public List<Object> finalResults() {
if (n>0) {
double entropy = 0;
for (Long2IntMap.Entry e : counts.long2IntEntrySet()) {
double p = (double) e.getIntValue()/n;
entropy -= p*Math.log(p)/Math.log(2);
}
return finalRow(entropy);
} else {
return finalRow();
}
}
}
/**
* Build a Top-N length metric to measure Top-N lists.
* @author <a href="http://www.grouplens.org">GroupLens Research</a>
*/
public static class Builder extends TopNMetricBuilder<Builder, TopNEntropyMetric> {
private String label = "TopN.pop.entropy";
/**
* Get the column label for this metric.
* @return The column label.
*/
public String getLabel() {
return label;
}
/**
* Set the column label for this metric.
* @param l The column label
* @return The builder (for chaining).
*/
public Builder setLabel(String l) {
Preconditions.checkNotNull(l, "label cannot be null");
label = l;
return this;
}
@Override
public TopNEntropyMetric build() {
return new TopNEntropyMetric(label, listSize, candidates, exclude);
}
}
}
| lenskit-eval/src/main/java/org/grouplens/lenskit/eval/metrics/topn/TopNEntropyMetric.java | /*
* LensKit, an open source recommender systems toolkit.
* Copyright 2010-2013 Regents of the University of Minnesota and contributors
* Work on LensKit has been funded by the National Science Foundation under
* grants IIS 05-34939, 08-08692, 08-12148, and 10-17697.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General 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.
*/
package org.grouplens.lenskit.eval.metrics.topn;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import it.unimi.dsi.fastutil.longs.Long2IntMap;
import it.unimi.dsi.fastutil.longs.Long2IntOpenHashMap;
import org.grouplens.lenskit.eval.Attributed;
import org.grouplens.lenskit.eval.data.traintest.TTDataSet;
import org.grouplens.lenskit.eval.metrics.AbstractTestUserMetric;
import org.grouplens.lenskit.eval.metrics.TestUserMetricAccumulator;
import org.grouplens.lenskit.eval.traintest.TestUser;
import org.grouplens.lenskit.scored.ScoredId;
import javax.annotation.Nonnull;
import java.util.Collections;
import java.util.List;
/**
*
* @author <a href="http://www.grouplens.org">GroupLens Research</a>
*/
public class TopNEntropyMetric extends AbstractTestUserMetric {
private final int listSize;
private final ItemSelector candidates;
private final ItemSelector exclude;
private final ImmutableList<String> columns;
public TopNEntropyMetric(String lbl, int listSize, ItemSelector candidates, ItemSelector exclude) {
this.listSize = listSize;
this.candidates = candidates;
this.exclude = exclude;
columns = ImmutableList.of(lbl);
}
@Override
public Accum makeAccumulator(Attributed algo, TTDataSet ds) {
return new Accum();
}
@Override
public List<String> getColumnLabels() {
return columns;
}
@Override
public List<String> getUserColumnLabels() {
return Collections.emptyList();
}
class Accum implements TestUserMetricAccumulator {
Long2IntMap counts = new Long2IntOpenHashMap();
int n = 0;
@Nonnull
@Override
public List<Object> evaluate(TestUser user) {
List<ScoredId> recs;
recs = user.getRecommendations(listSize, candidates, exclude);
if (recs == null) {
return userRow();
}
for (ScoredId s: recs) {
counts.put(s.getId(), counts.get(s.getId()) +1);
n +=1;
}
return userRow();
}
@Nonnull
@Override
public List<Object> finalResults() {
if (n>0) {
double entropy = 0;
for (Long2IntMap.Entry e : counts.long2IntEntrySet()) {
double p = (double) e.getIntValue()/n;
entropy -= p*Math.log(p)/Math.log(2);
}
return finalRow(entropy);
} else {
return finalRow(null);
}
}
}
/**
* Build a Top-N length metric to measure Top-N lists.
* @author <a href="http://www.grouplens.org">GroupLens Research</a>
*/
public static class Builder extends TopNMetricBuilder<Builder, TopNEntropyMetric> {
private String label = "TopN.pop.entropy";
/**
* Get the column label for this metric.
* @return The column label.
*/
public String getLabel() {
return label;
}
/**
* Set the column label for this metric.
* @param l The column label
* @return The builder (for chaining).
*/
public Builder setLabel(String l) {
Preconditions.checkNotNull(l, "label cannot be null");
label = l;
return this;
}
@Override
public TopNEntropyMetric build() {
return new TopNEntropyMetric(label, listSize, candidates, exclude);
}
}
}
| fixed a null that was causing NPE durring code evaulation.
| lenskit-eval/src/main/java/org/grouplens/lenskit/eval/metrics/topn/TopNEntropyMetric.java | fixed a null that was causing NPE durring code evaulation. | <ide><path>enskit-eval/src/main/java/org/grouplens/lenskit/eval/metrics/topn/TopNEntropyMetric.java
<ide> }
<ide> return finalRow(entropy);
<ide> } else {
<del> return finalRow(null);
<add> return finalRow();
<ide> }
<ide> }
<ide> } |
|
JavaScript | mit | 9dc6de8833cf078025c98ac7ce4196f39f8fb4ab | 0 | Sora-League/Sora,Sora-League/Sora,Sora-League/Sora | function seen (user) {
user = toId(user);
if (Users.get(user) && Users.get(user).connected) return '';
return '<b>Last Seen:</b> ' + Core.getLastSeen(user).split(', ')[0] + ' ago';
}
function getBadges (user) {
var badgeList = JSON.parse(require('fs').readFileSync('storage-files/badges.json'));
user = toId(user);
if (!badgeList[user] || Object.keys(badgeList[user]).length < 3) return '';
var total = '<details><summary><b>Badges:</b> (Click here to open)</summary>';
for (var i in badgeList[user]) {
total += badgeList[user][i];
};
return total + '</details>';
}
exports.commands = {
staff: 'leaguemembers',
attendance: 'leaguemembers',
leaguemembers: function (target, room, user) {
if (!this.canBroadcast()) return;
var total = '<table><tr><th>User</th><th>Last Seen</th></tr>';
var list = ['∆Champiön Nöah∆', '∆Chаmpion Bart∆', '∆FrontierHead Risu∆', 'OnyxEagle', 'Blazing360', '∆Coach Abadon∆', 'Bamdee', '∆Frontier Jerattata∆', '∆Frontier Neith∆'];
for (var i = 0; i < list.length; i++) {
var Seen = Users.get(list[i]) && Users.get(list[i]).connected ? '<font color = "green">Online</font>' : seen(list[i]).substr(18);
if (Seen === 'never') Seen = '<font color = "red">Never</font>';
total += '<tr><td>' + list[i] + '</td><td><center>' + Seen + '</center></td>';
}
this.sendReplyBox('<center><b>Admin Team</b><br />' + total + '</table></center>');
var total = '<table><tr><th>User</th><th>Last Seen</th></tr>';
var list = ['∆E4 Edge∆', '∆E4 Terror∆', '∆E4 Alcor∆', '∆E4 Silvy∆', '∆Frontier Asch∆', '∆Frontier∆ Srewop', '∆Frontier Meows∆'];
for (var i = 0; i < list.length; i++) {
var Seen = Users.get(list[i]) && Users.get(list[i]).connected ? '<font color = "green">Online</font>' : seen(list[i]).substr(18);
if (Seen === 'never') Seen = '<font color = "red">Never</font>';
total += '<tr><td>' + list[i] + '</td><td><center>' + Seen + '</center></td>';
}
this.sendReplyBox('<details><summary><b>Elite 4\'s and Frontiers</b></summary><center>' + total + '</table></details></center>');
var total = '<table><tr><th>User</th><th>Last Seen</th></tr>';
var list = ['∆Gym Ldr Lou∆', '∆Gym Ldr Connor∆', '∆Gym Ldr Float∆',
'∆Gym Ldr Mark∆', '∆Gym Ldr Core∆', '∆Gym Ldr Waffles∆', '∆Gym Ldr Angel9∆', '∆Gym Ldr SolarWolf∆',
'∆Gym Ldr Mitsuka∆', '∆Gym Ldr TSwiv∆', '∆Gym Ldr BK∆', '∆Gym Ldr Flamespell∆', '∆Gym Ldr Bigo∆', '∆Gym Ldr. Elodin∆', '∆Gym Ldr. Mewtwo∆'
];
for (var i = 0; i < list.length; i++) {
var Seen = Users.get(list[i]) && Users.get(list[i]).connected ? '<font color = "green">Online</font>' : seen(list[i]).substr(18);
if (Seen === 'never') Seen = '<font color = "red">Never</font>';
total += '<tr><td>' + list[i] + '</td><td><center>' + Seen + '</center></td>';
}
this.sendReplyBox('<details><summary><b>Gym Leaders</b></summary><center>' + total + '</table></details></center>');
},
/////////////////////
//Admin Team
////////////////////
bart: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<a><font size= 4><center><b><font color = 07e1ed>∆Champion Bart∆</font></b></center></a><br />' +
'<center><i>"Sometimes I look at the bright blue sky and say to myself \'I FUCKED UP, I FUCKED UP\' "</i></center> <br />' +
'<b>Ace:</b> Weavile<br />' +
'<b>Battle Rules:</b> <br/>' +
'-Ubers Battle <br/>' +
'-At least 2 must be tiered lower than OU <br/>' +
'-No Lowering opponents stats (Unless caused by attack) <br/>' +
'-No Pokemon with a base stat over 130<br />' +
'<center><img src="http://sprites.pokecheck.org/i/461.gif"> <img src="http://i1280.photobucket.com/albums/a482/Skarmory11/Misc%20sprites/Bart_zps03ad3a7d.png"><img src="http://play.pokemonshowdown.com/sprites/xyani/torterra.gif"></center>' +
'<center><img src="http://oi62.tinypic.com/14cfyh0.jpg"></center> <br />');
},
noah: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<a><font size= 4><center><b><font color = 430747>∆Champion Noah∆</font></b></center></a><br />' +
'<center><i>"Need a Champion? I Noah guy."</i></center> <br />' +
'<center><img src="http://sprites.pokecheck.org/i/134.gif"><img src="http://i.imgur.com/iu4Njdf.png"></center><br />' +
'<b>Ace:</b> All <br />' +
'<b>Battle Rules:</b> <br/>' +
'-Ubers <br/>' +
'<center><img src="http://oi62.tinypic.com/14cfyh0.jpg"></center> <br />');
},
onyx: 'onyxeagle',
onyxeagle: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<a><font face = forte><font color = b27300><font size= 5><center>∆OnyxEagle∆</center></font></a><br />' +
'<center><i>"Heads or Tails? Heads, I Win; Tails, you Lose"</i></center> <br />' +
'<b>Skilled in:</b> Rock types/ Ubers, Random Battle and OU to a certain degree.<br />' +
'<b>History:</b> 2nd Champion of New Sora. One of the 2 people who resurrected Sora from the rubbles. <br/>' +
'<b>Notes:</b> Resident coder of Sora, still conducts tests and registrations, offers advice. <br/>' +
'<img src="http://play.pokemonshowdown.com/sprites/xyani/kabutops.gif"> <img src="http://play.pokemonshowdown.com/sprites/xyani/landorus.gif"> <img src="http://play.pokemonshowdown.com/sprites/xyani/heracross-mega.gif"> <img src="http://play.pokemonshowdown.com/sprites/xyani/tyranitar.gif"> <img src="http://play.pokemonshowdown.com/sprites/xyani/tyrantrum.gif">' +
'<center><img src="http://oi62.tinypic.com/14cfyh0.jpg"></center> <br />');
},
risu: 'ninjarisu',
ninjarisu: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<a><font size= 4><center><b>∆Frontierhead Ninjarisu∆</b></center></a><br />' +
'<i>"I will show you the power of the best of the worst"</i> <br />' +
'<b>Ace:</b> Pachirisu<br />' +
'<b>Symbol:</b> Puny Symbol<br />' +
'<b>Rules:</b> <a href="http://www.smogon.com/forums/threads/oras-fu-winner-of-omotm-machoke-sticky-web-banned.3519286/">FU</a> <br />' +
'<details><summary><b>Badges: (Click here to open)</b></summary><br />' +
'<a href="http://soraleague.weebly.com/badges.html#ldr"><img src="http://i.imgur.com/ELFPzW8.png" title="Achieved Gym Leader Status"></a><a href="http://soraleague.weebly.com/badges.html#frontier"><img src="http://i.imgur.com/7jbhEJC.png" title="Achieved Frontier Status"></a><a href="http://soraleague.weebly.com/badges.html#e4"><img src="http://i.imgur.com/QtECCD9.png" title="Achieved Elite 4 Status"></a><a href="http://soraleague.weebly.com/badges.html#starly"><img src="http://i.imgur.com/zaLhq1k.png" title="Starly Badge: One Year on Sora"></a><a href="http://soraleague.weebly.com/badges.html#staravia"><img src="http://i.imgur.com/2UmjiLt.png" title="Staravia Badge: Two Years on Sora"></a><a href="http://soraleague.weebly.com/badges.html#smeargle"><img src="http://i.imgur.com/A8h3FJN.png" title="Smeargle the Creator: Helped develop Champion\'s Challenge and Inclement Weather Metagames"></a></details><br />' +
'<img src="http://play.pokemonshowdown.com/sprites/xyani/pachirisu.gif"><img src="http://www.pkparaiso.com/imagenes/xy/sprites/animados/unown-romeo.gif"><img src="http://www.pkparaiso.com/imagenes/xy/sprites/animados/unown-india.gif"><img src="http://www.pkparaiso.com/imagenes/xy/sprites/animados/unown-sierra.gif"><img src="http://www.pkparaiso.com/imagenes/xy/sprites/animados/unown-uniform.gif"><img src="http://play.pokemonshowdown.com/sprites/xyani/pachirisu.gif">' +
'<center><img src="http://oi62.tinypic.com/14cfyh0.jpg"></center><br />');
},
//////////////
//Elite Four
//////////////
silvy: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('∆E4 <b>Silvy</b>∆<br />' +
'<i>"Silvy-Chan at your service, here to steel the kill. My body is regi. So come at me, if you will~ ;)"</i> <br />' +
'<b>Type: <font color = 5e6664>Steel</font></b><br />' +
'<b>Ace:</b> None <br />' +
'<b>Battle Rules:</b> <br/>' +
'- None<br />' +
seen('e4silvy') +
getBadges('siiilver'));
},
edge: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('∆E4 <b>Edge</b>∆<br />' +
'<i>"How can you face your problem when your problem is your face?"</i> <br />' +
'<b>Type: <font color = ff00b6>Psychic</font></b><br />' +
'<b>Ace:</b> Victini<br />' +
'<b>Battle Rules:</b><br />' +
'-No Hazards<br />' +
seen('e4edge') +
getBadges('e4edge'));
},
alcor: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('∆E4 <b>Alcor</b>∆<br />' +
'<i>"The pattern repeats, will your flaws too?"</i> <br />' +
'<b>Type: <font color = 7ab6ff>Flying</font></b><br />' +
'<b>Ace:</b> Togekiss<br />' +
'<b>Battle Rules:</b><br />' +
'-No Status Healing Moves<br />' +
seen('e4alcor') +
'<audio src="https://dl.pushbulletusercontent.com/nfP9iY95TAbBnLzJf1cAbLG7qegceAan/Last%20Decision%20%28%20Remastered%20And%20Extended%20%29.mp3" controls="" style="width: 100% ; border: 2px solid #700000 ; background-color: #000000" target="_blank"></audio>' +
getBadges('e4alcor'));
},
terror: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('∆E4 <b>Terror</b>∆<br />' +
'<i>"Better get out of the water because the waves are coming for you."</i> <br />' +
'<b>Type: <font color = 0745ff>Water</font></b><br />' +
'<b>Ace:</b> Mega Sharpedo<br />' +
'<b>Battle Rules:</b><br />' +
'-Item Clause (Only one of the same item may be used)<br />' +
seen('e4terror') +
getBadges('e4terror'));
},
/*sube4: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center>Sub E4 Position: <b><font color = FF0000>Offline</font></b></center><br />'+
'Sub E4 <b>???</b> <br />'+
'<b>Type:</b> <b><font color = 006b0a>???</font></b><br />'+
'<b>Battle Rules:</b> <br />'+
'-??? <br />'+
'-??? <br />');
},*/
/////////////
//Frontiers
/////////////
abadon: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><font size = 3><b>∆Coach Abadon∆<b></font><br>' +
'<i>"SWIGGITY SWOOTY I\'M COMING FOR THAT BOOTY"</i><br><br>' +
'<b>Achievements:</b>' +
'<li>Sora\'s best ground E4' +
'<li>Sora\'s coach' +
'<li>All round top bloke<br>' +
'<img style = "margin: 5px" src = "http://128.199.160.98:8000/avatars/' + Config.customavatars.coachabadon + '">' +
'<div style = "display: inline-block; width: 100px; height: 100px; background: url(http://www.pkparaiso.com/imagenes/xy/sprites/animados/gengar-3.gif) no-repeat -50px -70px"></div><br>' +
'<audio controls src = "https://dl.pushbulletusercontent.com/W9wf3ZGqXSIHvgVbdUtbl9PrWnPTl9SQ/deep.mp3" style = "color: black; width: 100%; border-radius: 0px;"></audio>'
+ getBadges('coachabadon') +'<br><img src="http://oi62.tinypic.com/14cfyh0.jpg"></center>');
},
asch: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('∆Elite Frontier <b>Asch</b>∆<br />' +
'<i>"Chief Akkie, head of the meme police, serving for 38 years; no meme slips through her cracks."</i> <br />' +
'<b>Symbol:</b> White Knight Symbol<br />' +
'<b>Ace:</b> Crawdaunt <br />' +
'<b>Battle Rules:</b> <br/>' +
'-Only BL, BL2, BL3 and BL4 Pokemon may be used.<br/>' +
'-No Mega Evolution<br />' +
seen('frontierasch') + '<br/>' +
'<img src="http://www.pkparaiso.com/imagenes/xy/sprites/animados/bulbasaur-3.gif"><img src="http://www.pkparaiso.com/imagenes/xy/sprites/animados/bulbasaur-3.gif">' +getBadges('frontierasch'));
},
blade: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<details><summary>This Frontier is currently on leave, Please contact the Frontierhead for the subsitute. P.s click me I have a sexy card</summary><a><center><img src="http://sprites.pokecheck.org/i/494.gif"><b><font color = FF0000 size= 4>∆Fröntier∆Blade☯</font></b><img src="http://sprites.pokecheck.org/i/080.gif"></center></a><br />' +
'<center><i>"Be Stronger Than Your Strongest Excuse"</i></center> <br />' +
'<b>Symbol:</b> Yin and Yang <br />' +
'<b>Ace:</b> Mybro (Slowbro) <br />' +
'<b>Battle Rules:</b> <br />' +
'-Ability Shift Tier<br />' +
'-No Johns<br />' +
'<a href="http://www.smogon.com/forums/threads/ability-shift.3503100/">How Ability Shift works</a> <br />' +
'<a href="http://www.psypokes.com/lab/abilities.php">Pokemon Ability List</a> <br />' +
'<details><summary><b>Champion\'s Challenge Rules:</b></summary> <br />' +
'-NU Monotype<br />' +
'-R U Too Strong?</details><br />' +
'<details><summary><b>Badges: (Click here to open)</b></summary><br />' +
'<a href="http://soraleague.weebly.com/badges.html#ldr"><img src="http://i.imgur.com/ELFPzW8.png" title="Achieved Gym Leader Status"></a><a href="http://soraleague.weebly.com/badges.html#frontier"><img src="http://i.imgur.com/7jbhEJC.png" title="Achieved Frontier Status"></a><a href="http://soraleague.weebly.com/badges.html#efrontier"><img src="http://i.imgur.com/2iZp7Mi.png" title="Achieved Elite Frontier Status"></a><a href="http://soraleague.weebly.com/badges.html#starly"><img src="http://i.imgur.com/zaLhq1k.png" title="Starly Badge: One Year on Sora"></a><a href="http://soraleague.weebly.com/badges.html#porygon"><img src="http://i.imgur.com/bJrRxB8.png" title="Broke the server while trying to repair and implement new features, good job mate, now go fix it"></a><a href="http://soraleague.weebly.com/badges.html#smeargle"><img src="http://i.imgur.com/A8h3FJN.png" title="Smeargle the Creator: Creator of the Badge System"></a></details> <br />' +
'<details><summary><font color = 009900><center><b>Torkoal Shrine</b></center></font></summary><center><img src="http://play.pokemonshowdown.com/sprites/xyani-shiny/torkoal.gif"></center>' +
'<center><b>R.I.P. War Turtle</b></center> <br />' +
'<center>1st Apostle of the All Mighty Lord Parasect</center></details><br />' +
'<center><img src="http://oi62.tinypic.com/14cfyh0.jpg"></center> <br /></details>');
},
meows: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('∆Frontier <b>Meows</b>∆<br />' +
'<i>"Abs=Win"</i> <br />' +
'<b>Symbol: </b>Patience <br />' +
'<b>Ace:</b> Quagsire<br />' +
'<b>Battle rules:</b> <br />' +
'-OU<br />' +
'-No Trick/Switcheroo <br />' + seen('frontiermeows') + getBadges('frontiermeows'));
},
srewop: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('∆Elite Frontier <b>Srewop</b>∆<br />' +
'<i>"You came to the wong place if you wanted a win."</i> <br />' +
'<b>Symbol:</b> SumTingWong<br />' +
'<b>Ace:</b> Golbat <br />' +
'<b>Battle Rules:</b> <br/>' +
'-RU Monotype <br/>' +
'-No Hazards <br/>' +
'-No Knock off<br />' +
'-No Megas<br />' +
seen('frontiersrewop') + '<br/>' +
'<center><img src="http://play.pokemonshowdown.com/sprites/xyani/zubat.gif"><img src="http://play.pokemonshowdown.com/sprites/xyani/golbat.gif"><img src="http://play.pokemonshowdown.com/sprites/xyani/zubat.gif"><img src="http://play.pokemonshowdown.com/sprites/xyani/gengar.gif"></center> <br />');
},
jerattata: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('∆Frontier <b>Jerattata</b>∆<br />' +
'<i>"Decide which of the two options is harder, and do the other. You might enjoy the battle."</i> <br />' +
'<b>Symbol:</b> Foresight <br />' +
'<b>Ace:</b> All<br />' +
'<b>Battle rules:</b> <br />' +
'-Challenger picks either a Tier/Meta <b>or</b> Battle Rule (within reason) <br />' +
'-Jeratt picks either a Tier/Meta or Battle Rule depending on which the challenger picks. <br />'+
'-Both the Tier/Meta and Battle rule that are decided upon are combined and are used for the battle.<br />'+
'-Monotype battles are banned. <br />' + seen('frontierjerattata'));
},
zachary: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('∆Frontier <b>Zachary</b>∆<br/>' +
'<i>"Can you do a few things at the same time?"</i><br/>' +
'<b>Symbol:</b> Multitasking<br/>' +
'<b>Ace:</b> All<br/>' +
'<b>Battle Rules:</b><br/>' +
'-Smogon Doubles<br />' +
'-No hazards<br />' +
'<details><summary><b>Champion\'s Challenge Rules:</b></summary> <br />' +
'-Pikachu Tournamentchu <br />' +
'-No CAP Pokemon</details> <br />' + seen('frontierzachary') + getBadges('frontierzachary'));
},
/*subfrontier: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center>Sub Frontier Position: <b><font color = FF0000>Offline</font></b></center><br />'+
'Sub Frontier <b>???</b> <br />'+
'<b>Symbol:</b> ???<br />'+
'<b>Battle Rules:</b> <br />');
},*/
//////////////
//Gym Leaders
//////////////
bug: 'flamespell',
flamespell: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('∆Gym Ldr <b>Flamespell</b>∆<br />'+
'<i>"Fear is the ultimate weapon, Fear my swarm."</i> <br />'+
'<b>Type: <font color = 65b510>Bug</font></b><br />'+
'<b>Ace:</b> Mega Pinsir <br />' + seen('gymldrflamespell') + getBadges('gymldrflamespell'));
},
dark: 'bk',
bk: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('∆Gym Ldr <b>BK</b>∆<br />' +
'<i>"There is always a light even at the darkest of times."</i> <br />' +
'<b>Type: <font color = 15012b>Dark</font></b><br />' +
'<b>Ace:</b> Bisharp<br />' +
seen('gymldrBK') + '<br />');
},
dragon: 'lou',
lou: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('∆Gym Ldr <b>Lou</b>∆<br />' +
'<i>"Dragon mono + Outrage = win"</i> <br />' +
'<b>Type: <font color = 230077>Dragon</font> </b><br />' +
'<b>Ace:</b> Latias<br />' + seen('gymldrlou') + getBadges('gymldrlou'));
},
electric: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('∆Gym Ldr <b>>???</b>∆<br />' +
'<i>"???"</i><br />' +
'<b>Type: <font color = d6cc0c>Electric</font></b><br />' +
'<b>Ace:</b> ???<br />' + seen('') + getBadges(''));
},
elodin: 'fairy',
fairy: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('∆Gym Ldr <b>Elodin</b>∆<br />' +
'<i>"All you need is faith, trust, and a little pixie dust"</i> <br />' +
'<b>Type: <font color = ff42a0>Fairy</font></b><br />' +
'<b>Ace: </b>Mega Gardevoir<br />' + seen('gymldrelodin') + getBadges('gymldrelodin'));
},
ground: 'mewtwo',
mewtwo: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('∆Gym Ldr <b>Mewtwo</b>∆<br />' +
'<i>"Cute, you thought you could beat me. Lemme show you the power of my Excadrill\'s Earthquake or my Zygarde\'s Outrage. You thought you could get my gym badge think again."</i> <br />' +
'<b>Type: <font color = A64000>Ground</font></b><br />' +
'<b>Ace: </b>Zygarde<br />');
},
fighting: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('∆Gym Ldr <b>???</b>∆<br />'+
'<i>"???"</i> <br />'+
'<b>Type: <font color = d83c08>Fighting</font></b><br />'+
'<b>Ace:</b> ???<br />' + seen('') + getBadges(''));
},
fire: 'waffles',
waffles: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('∆Gym Ldr <b>Waffles</b>∆<br />'+
'Leader Ranking: <font color = FFFF00><b>2nd</font></b> <br />' +
'<i>"Don\'t waffle out of the situation."</i> <br />'+
'<b>Type: <font color = FF0000>Fire</font></b><br />'+
'<b>Ace: Infernape</b> <br />' + seen('gymldrwaffles') + '<br>' +
'<img src = "http://sprites.pokecheck.org/t/010.gif"> <img src = "http://play.pokemonshowdown.com/sprites/xyani/heatran.gif"><br>' +
getBadges('gymldrwaffles'));
},
flying: 'float',
float: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('∆Gym Ldr <b>Float</b>∆<br />' +
'<i>"flap... flap... flap... bird type...?"</i> <br />' +
'<b>Type: <font color = 7ab6ff>Flying</font></b><br />' +
'<b>Ace:</b> Hawlucha (John Cena)<br />' +
'<img src="http://play.pokemonshowdown.com/sprites/xyani-shiny/beldum.gif"><img src="http://play.pokemonshowdown.com/sprites/xyani-shiny/aron.gif"><img src="http://play.pokemonshowdown.com/sprites/xyani/metagross-mega.gif"><img src="http://play.pokemonshowdown.com/sprites/xyani-shiny/aron.gif"><img src="http://play.pokemonshowdown.com/sprites/xyani-shiny/beldum.gif"><br />' +
'<audio controls src = "http://picosong.com/cdn/f47cf8120a89402a77ed76e2494d20fb.mp3" style = "border-radius: 0px; background: black;"></audio></br></br>' +
seen('gymldrfloat') + getBadges('gymldrfloat'));
},
ghost: 'tswiv',
tswiv: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('∆Gym Ldr <b>TSwiv</b>∆<br />' +
'<i>"Let the séance begin.......MWAHAHAHA"</i> <br />' +
'<b>Type: <font color = 7814e2>Ghost</font></b><br />' +
'<b>Ace:</b> Sableye<br />' + seen('gymldrtswiv') + getBadges('gymldrtswiv'));
},
mitsuka: 'grass',
grass: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('∆Gym Ldr <b>Mitsuka</b>∆<br />'+
'Leader Ranking: <font color = FF0000><b>1st</font></b> <br />' +
'<i>"Storm of leaf and Draining root!"</i> <br />'+
'<b>Type: <font color = 006b0a>Grass</font></b> <br />'+
'<b>Ace:</b> Victreebel <br />' + seen('gymldrmitsuka') + getBadges('gymldrmitsuka'));
},
ice: 'mark',
mark: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('∆Gym Ldr <b>Mark</b>∆<br />' +
'<i>"Hard work pays off in the end."</i> <br />' +
'<b>Type: <font color = 00e0ac>Ice</font></b><br />' +
'<b>Ace:</b> Don\'t Do Drugs (Mega Glalie)<br />' +
seen('gymldrmark') + '<br>' +
'<img src = "http://play.pokemonshowdown.com/sprites/xyani-shiny/froslass.gif"> ' +
'<img src = "http://play.pokemonshowdown.com/sprites/xyani-shiny/glalie-mega.gif"><br>' +
'<audio controls src = "http://216.227.134.162/ost/rockman-2-megaman-2-complete-works/kbrxwhzvos/2-31-flash-man-stage-smd.mp3" style = "border: 2px solid cyan; border-radius: 3px; background-color: black;"></audio>' +
getBadges('gymldrmark')
);
},
normal: 'bigo',
bigo: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('∆Gym Ldr <b>Bigo</b>∆<br />'+
'<i>"Don\'t underestimate the normal, cause being \'normal\' doesn\'t mean to be weak"</i> <br />'+
'<b>Type: <font color = ffa5d5>Normal</font></b><br />'+
'<b>Ace:</b> Lopunny<br />' + seen('gymldrbigo') + getBadges('gymldrbigo'));
},
poison: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('∆Gym Ldr <b>???</b>∆<br />' +
'<i>"???"</i> <br />'+
'<b>Type: <font color = aa00ff>Poison</font></b><br />' +
'<b>Ace:</b> ???<br />' + seen('') + getBadges('gymldrcrash'));
},
psychic: 'connor',
connor: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('∆Gym Ldr <b>Connor</b>∆<br />' +
'Leader Ranking: <font color = 9dff00><b>3rd</font></b> <br />' +
'<i>"Psychic power isn\'t something that only a few people have. Everyone has psychic power. People just don\'t realize it."</i> <br />' +
'<b>Type: <font color = ff00b6>Psychic</font></b><br />' +
'<b>Ace:</b> Gardevoir <br />' + seen('gymldrconnor') + getBadges ('gymldrconnor'));
},
rock: 'core',
core: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('∆Gym Ldr <b>Core</b>∆<br />' +
'<i>"There\'s always a chance for a comeback if you leave yourself open"</i> <br />' +
'<b>Type: <font color = 472e10>Rock</font></b><br />' +
'<b>Ace:</b> Archeops<br />' + seen('gymldrcore') + getBadges('gymldrcore'));
},
solarwolf: 'steel',
steel: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('∆Gym Ldr <b>SolarWolf</b>∆<br />' +
'<i>"The best steel doesn\'t always shine the brightest, but it will smash your face in."</i> <br />' +
'<b>Type: <font color = 5e6664>Steel</font></b> <br />' +
'<b>Ace:</b> Bisharp <br />' +
seen('gymldrsolarwolf') + getBadges('gymldrsolarwolf'));
},
water: 'angel9',
angel9: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('∆Gym Ldr <b>Angel9</b>∆<br />' +
'<i>"Watch my beautiful waters submerge you deep."</i> <br />' +
'<b>Type: <font color = 0745ff>Water</font></b><br />' +
'<b>Ace:</b> Quagsire <br/>' +
seen('gymldrangel9') + getBadges('gymldrangel9'));
},
/////////////
//Other Cards
//////////////////
aboottothehead: 'abtth',
abtth: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><b><font size="4" color="03b206">ABootToTheHead</font></b></center><br>' +
'<center><i>"Stardust-weaved ARiA, please keep this melody going."</i></center><br /><br />' +
'<b>Ace: </b>Scizor and Whimsicott<br />' +
'<b>Favorite Pokemon: </b>Typhlosion and Scizor<br />' +
'<b>Preferred tiers: </b>VGC, Ubers, OU <br />' +
'<b>Known for: </b>VoltTurn and Whimsistall shenanigans<br />' +
'<b>Achievements: </b>Ex-Elite Frontier, ex-Elite Four<br>' +
'<b>Affiliation:</b> Cheeky Nandos Squad<br><br>' +
'<center><img src="http://sprites.pokecheck.org/i/157.gif"><img src="http://sprites.pokecheck.org/i/530.gif"><img src="http://sprites.pokecheck.org/i/547.gif"><img src="http://sprites.pokecheck.org/t/144.gif"><img src="http://sprites.pokecheck.org/i/205.gif"><img src="http://sprites.pokecheck.org/i/310.gif"><img src="http://sprites.pokecheck.org/i/212.gif"></center><br />' +
'<center><img src = "http://i.imgur.com/AaO6Xze.png" width = "120" height = "120"><img src = "http://i.imgur.com/JSRaFVC.png" width = "120" height = "120"><img src = "http://i.imgur.com/I0NbMSO.png" width = "120" height = "120"></center><br>' +
getBadges('aboottothehead') + '<br>' +
'<center><img src = "http://i.imgur.com/ty6OYpg.png" width = "100" height = "100"> <img src = "http://i.imgur.com/YoDeO4O.png" width = "100" height = "100"></center>');
},
sorarani: 'arani',
arani: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><b><font color = "#331D81" size = 3>∆Arani∆</font></b><br>' +
'<i>"Rain teams are old school? Well... screw you."</i><br><br>' +
'<b>Skilled in:</b> Gen 5 OU - was consistently in the Top 10 on the global OU ladder.<br>' +
'<b>History:</b> First new Champ of Sora - ressurrected it along with Onyx.<br>' +
'<b>Present:</b> Serving in the defense force - Occasionally comes online.<br>' +
seen('sorarani') + '<br>' +
'<img src = "http://play.pokemonshowdown.com/sprites/xyani/keldeo-resolute.gif"><img src = "http://play.pokemonshowdown.com/sprites/xyani/thundurus-therian.gif">');
},
arjunb: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><input type="image" src="http://i.imgur.com/bnCFCm5.png"><div align="center"><br />' +
'<div align="center">"<i>Fall seven times, stand up eight. That\'s what I do</i>"</div><br />' +
'<b>Favorite Types:</b> Fighting, Dark and Poison(with crobat)<br />' +
'<b> Achievements:</b> Former Elite, got the elite position in his first promo tournaments.<br />' +
'<b>Favorite Pokemon:</b><br />' +
'<img src="http://play.pokemonshowdown.com/sprites/xyani/terrakion.gif"><img src="http://play.pokemonshowdown.com/sprites/xyani/weavile.gif"><img src="http://play.pokemonshowdown.com/sprites/xyani/medicham-mega.gif"><img src="http://play.pokemonshowdown.com/sprites/xyani/crobat.gif"><div align="center"><br />' +
+getBadges('arjunb'));
},
ascher: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><b><font size="4" color="86e755">Ascher</font></b></center><br />' +
'<center><img src="http://play.pokemonshowdown.com/sprites/xyani/shroomish.gif"></center> <br />' +getBadges('frontierasch'));
},
azh: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<div style = "padding: 8px; color: white; background: #000 url(http://www.pageresource.com/wallpapers/wallpaper/pokemon_67267.jpg) no-repeat scroll bottom; background-size: 100%;">' +
'<center><b><font size= 5>∆ArthurZH∆</font></b></center><br />'+
'<center><i>"The power of the seas, storms and rivers are mine to hold....and here you dare to stand before me?"</i></center> <br />'+
'<center><b>Favoured Type:</b> Water<br />'+
'<b>Favoured Metagame:</b> Smogon Doubles <br />'+
'<b>Favourite Pokemon:</b> Gyarados</center><br />'+
'<b>Achievements:</b> Ex Water Leader of Sora, Ex Roulette/Champion\'s Challenge/Monotype Frontier of Sora<br />'+
'<b>Current Position:</b> Smogon Doubles OU Frontier<br />'+
'<center><img src="http://fc00.deviantart.net/fs71/f/2014/082/f/8/manaphy_gif_by_gloomymyth-d7bakkc.gif"><img src="http://play.pokemonshowdown.com/sprites/xyani/keldeo-resolute.gif"><img src="http://www.pkparaiso.com/imagenes/xy/sprites/animados/tentacruel.gif"><img src="http://www.pokemonreborn.com/custom/44203.png?530"> <img src="http://play.pokemonshowdown.com/sprites/xyani/kabutops.gif"><img src="http://www.pkparaiso.com/imagenes/xy/sprites/animados/swampert.gif"><img src="http://play.pokemonshowdown.com/sprites/xyani/gyarados.gif"></center>'+
'<center><font size=2 color=#0000FF><b>Battle Theme</b> - <i>Hoenn Oceanic Museum Remix [Credits: GlitchXCity]</i></font><br \><audio src="https://dl.pushbulletusercontent.com/rd0Qhn6drs85cyLNk7XIxGmwLQHQl4q1/Atmosphere-%20Bright.mp3" controls="" style="width: 100% ; border: 2px solid #0000FF ; background-color: #3399FF" target="_blank"></audio></center><br \>' +getBadges('frontierzachary'));
},
bamdee: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><span style = "font-size: 15pt; color: #ff00b6;"><b>Bamdee</b></span></center><br>' +
'<center><img src="http://play.pokemonshowdown.com/sprites/xyani/ditto.gif"></center><br>' +
'<audio controls src = "https://dl.pushbulletusercontent.com/xFgUAMGfNsNhld0TC7Bf9nehzEiVRkGo/sonic.mp3" style = "border: 2px solid pink; background: black; width: 100%;"></audio><br>' +
getBadges('bamdee')
);
},
darkus: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><span style = "font-size: 11pt; font-weight: bold; color: ' + Core.color('soradarkus') + '">∆SoraDarkus∆</span><br>' +
'<i>"It\'s all shits and giggles until someone giggles and shits."</i><br><br>' +
'<b>Aces:</b> Bisharp and Crawdaunt<br>' +
'<b>Skilled in:</b> Monotype<br>' +
'<b>Preferred types:</b> Dark, Psychic and Steel<br>' +
'<b>Achievements:</b> Sora E4, Gym Leader and Side-Mission<br>' +
'<b>Known for:</b> Being one of the original members of Sora, and having mad Dark mono skills.<br>' +
seen('soradarkus') + '<br>' +
'<img src = "http://play.pokemonshowdown.com/sprites/xyani/bisharp.gif"> <img src = "http://play.pokemonshowdown.com/sprites/xyani/crawdaunt.gif" style = "transform: rotateY(180deg)"><br>' +
getBadges('soradarkus'));
},
edgy: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<a><font size= 4><center><b><font color = 00CCFF>Edgy</font></b></center></a><br />' +
'<center><img src="http://play.pokemonshowdown.com/sprites/xyani/gardevoir-mega.gif"><img src="http://play.pokemonshowdown.com/sprites/xyani/lopunny-mega.gif"><img src="http://play.pokemonshowdown.com/sprites/xyani/charizard-mega-x.gif"><img src="http://play.pokemonshowdown.com/sprites/xyani/lopunny-mega.gif"><img src="http://play.pokemonshowdown.com/sprites/xyani/gardevoir-mega.gif"></center> <br />' +
'<center><i>"How can you face your problem, if the problem is your face?"</i></center><br />' +
'<details><summary><font size= 1><b>Badges: (Click here to open)</b></font></summary><br />' +
'<a href="http://soraleague.weebly.com/badges.html#ldr"><img src="http://i.imgur.com/ELFPzW8.png" title="Achieved Gym Leader Status"></a><a href="http://soraleague.weebly.com/badges.html#e4"><img src="http://i.imgur.com/QtECCD9.png" title="Achieved Elite 4 Status"></a><a href="http://soraleague.weebly.com/badges.html#aegislash"><img src="http://i.imgur.com/aJY3eKg.png" title="Winner of Sora\'s first major Monotype Round Robin Tour"></a></details> <br />');
},
gasp: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('Trainer <b>gasp</b><br />' +
'<i>"Lights out."</i> <br />' +
'<b>Ace:</b> Mega Gengar<br />' +
'<b>Honours:</b> Sora\'s first challenger to reach Hall of Fame.<br />' +
'<b>Prefered Tier:</b> Balanced Hackmons' +
'<img src="http://pldh.net/media/pokemon/gen5/blackwhite_animated_front/302.gif"> <img src="http://media.tumblr.com/tumblr_m6ci5tQsEv1qf6fp2.gif"><br />' +getBadges('gasp'));
},
leafy: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReply('|html|<div style = "padding: 5px; text-align: center; background-image: url(http://i1171.photobucket.com/albums/r545/Brahak/maple_zpsg5sgjduk.jpg) no-repeat scroll bottom; background-size: cover;">' +
'<font size = 4 color = "white"><b>∆Leaf∆</b></font><br><br>' +
'<table align = "center" border = "0px" style = "color: #707c71">' +
'<tr><td style = "background: rgba(0, 0, 0, 0.9); width: 200px; height: 120px"><b><u><span style = "font-size: 10pt">Achievements</span></u></b><br>' +
'<li style = "padding: 3px">Successfully ran two leagues.' +
'<li style = "padding: 3px">Been a Gym Leader, Elite Four, and Frontier in Sora.</td>' +
'<td style = "padding: 0px 8px 0px 8px;"><img src = "http://play.pokemonshowdown.com/sprites/xyani/grovyle.gif"></td>' +
'<td style = "background: rgba(0, 0, 0, 0.9); width: 200px;"><b><u><span style = "font-size: 10pt">Known for</span></u></b><br>' +
'<li style = "padding: 3px">Scarf Kyurem set.' +
'<li style = "padding: 3px">Mega Blastoise and Cinccino favourites.' +
'<li style = "padding: 3px">Resident drunk of Sora.</td></tr></table><br>' +
'<table align = "center"><tr><td><div style = "display: inline-block; width: 120px; height: 101px; background: url(http://www.pkparaiso.com/imagenes/xy/sprites/animados/leafeon-2.gif) no-repeat 0px -70px"></div></td>' +
'<td><div style = "transform: rotateY(180deg); display: inline-block; width: 120px; height: 101px; background: url(http://www.pkparaiso.com/imagenes/xy/sprites/animados/leafeon-2.gif) no-repeat 0px -70px"></div></td></tr></table>' +
'<center><audio controls src = "https://dl.pushbulletusercontent.com/91078HKzh36ORZdMm7EaE2suEdL7iwr1/Devil%20Survivor%202%20-%20Septentrion%20%5Bwww.songmirror.org%5D.mp3" style = "width: 100%; border-radius: 0px; background: linear-gradient(45deg, #011100, #00ad17, #011100, #00ad17, #011100, #00ad17, #011100, #00ad17);"></audio><br>' +
getBadges('e4alcor') +
'</div>');
},
meowsofsora: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<b><font color = 55dbe8><a><font size= 4><center>MeowsofSora</font></center></b><br />'+
'<center><i>"I might be a bitch, but I\'m definitely not a pussy"</i><br />'+
'<i>"Abs=Win"</i><br /><br />'+
'<b>Who am I:</b> Resident OU Specialist and OM Lover <br />'+
'<b>Specialty:</b> OU <br />'+
'<b>Ace:</b> Latios and Azumarill </center><br />'+
'<b>Achievements:</b> Peaked top 20 for OU/OU (No Mega), top 500 for Monotype <br />'+
'<b>Current Position:</b> OU Frontier of Sora <br />'+
'<center><img src="http://play.pokemonshowdown.com/sprites/xyani/latios.gif"><img src="http://play.pokemonshowdown.com/sprites/xyani/azumarill.gif"></center><br />'+
'<center><font size=2 color=#0000FF><b>Girl\'s Day</b> - <i>Ring My Bell (for hookups and battles)</i></font><br \><audio src="https://dl.pushbulletusercontent.com/GZk1vZlsoisCqMSCSnSOWV7bZlsjTroX/02%20%EB%A7%81%EB%A7%88%EB%B2%A8%20%28Ring%20My%20Bell%29.mp3" controls="" style="width: 100%" target="_blank"></audio></center><br \><br \>'+ getBadges('frontiermeows'));
},
jeratt: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<a><font size= 4><center><b>∆Artiste Jeratt∆</b></center></a><br />' +
'<center><i>"No one out-predicts me, but me."</i></center><br />' +
'<img src="http://sprites.pokecheck.org/i/235.gif"> <img src="http://sprites.pokecheck.org/t/033.gif"><br />' +
'<b>Highly skilled in:</b> Dragon & Ice<br />' +
'<b>Skilled in:</b> Making quotes, backgrounds for Sora and many Pokemon types.<br />' +
'<b>Note:</b> Close the Lobby and see what I can really do. <br/>' +
'<b>History:</b> Greatest Ice E4, <strike>undefeated</strike> Dragon E4. <br/>' +
'P.S. I\'m still Dragon you away with my coldness. <br/>' +
'P.P.S Use Scizor against me, and I\'ll get fired up and blast you! <br/>' +
'<center><img src="http://play.pokemonshowdown.com/sprites/xyani-shiny/rattata.gif"> <img src="http://play.pokemonshowdown.com/sprites/xyani-shiny/mamoswine.gif"> <img src="http://play.pokemonshowdown.com/sprites/xyani/vanilluxe.gif"> <img src="http://play.pokemonshowdown.com/sprites/xyani/dialga.gif"> <img src="http://play.pokemonshowdown.com/sprites/xyani/zoroark.gif"></center>' +
'<details><summary><b>Badges:</b></summary><br />' +
'<a href="http://soraleague.weebly.com/badges.html#smeargle"><img src="http://i.imgur.com/A8h3FJN.png" title="Smeargle the Creator: Resident Artist of Sora, Metagame Creator: CC, Priomons, Incl Weather, PokeSandbox"></a><a href="http://soraleague.weebly.com/badges.html#ldr"><img src="http://i.imgur.com/ELFPzW8.png" title="Achieved Gym Leader Status"></a><a href="http://soraleague.weebly.com/badges.html#frontier"><img src="http://i.imgur.com/7jbhEJC.png" title="Achieved Frontier Status"></a><a href="http://soraleague.weebly.com/badges.html#e4"><img src="http://i.imgur.com/QtECCD9.png" title="Achieved Elite 4 Status"></a><a href="http://soraleague.weebly.com/badges.html#badges"><img src="http://i.imgur.com/tnkW9J9.png" title="Badge Collector: Defeat all 18 Gym Leaders"></a><a href="http://soraleague.weebly.com/badges.html#starly"><img src="http://i.imgur.com/zaLhq1k.png" title="Starly Badge: One Year on Sora"></a><a href="http://soraleague.weebly.com/badges.html#porygon"><img src="http://i.imgur.com/bJrRxB8.png" title="Broke the server while trying to repair it, good job mate"></a> </details><br />' +
'<center><img src="http://oi62.tinypic.com/14cfyh0.jpg"></center> <br />');
},
nightanglet: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><i><font color="blue"><h1>Nightanglet</h1></font></center><br>' +
'<font color = "blue"><b>Ace: Infernape(CR Ace:Rhydon)<br />' +
'Custom Rules:<br />' +
'- No poke above the base speed of 40<br />' +
'- No Hazards<br />' +
'-Speed should not be increased or decreased<br />' +
'</b></i><img src="http://play.pokemonshowdown.com/sprites/xyani-shiny/infernape.gif"><img src="http://play.pokemonshowdown.com/sprites/xyani/rhydon.gif">');
},
swearwip: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReply('|html|<table style = "color: white; width: 100%; padding: 0px 10px 10px 10px; background: linear-gradient(45deg, #67108c, #3c0654, #67108c, #3c0654, #67108c, #3c0654, #67108c, #3c0654, #67108c, #3c0654);">' +
'<tr><td colspan = "2"><center><br><font size = 3 style = "margin-top: 10px; font-weight: bold; text-shadow: 3px 3px 10px black;">∆Srewop∆</font><br>' +
'<i style = "text-shadow: 3px 3px 10px black;">"I think you\'re in Gotham, \'cause the bat is coming for you..."</i><br><br></td></tr>' +
'<tr><td><center style = "text-shadow: 3px 3px 10px #000;"><b>Symbol:</b> SumTingWong<br><b>Battle Format:</b> RU Monotype<br>' +
'<b>Restrictions:</b><br><li>No Hazards<li>No Knock Off<br>' +
'<b>Ace:</b> Golbat<br>' +
'<img style = "margin: -5px" src = "http://www.pkparaiso.com/imagenes/xy/sprites/animados/golbat-2.gif"></center></td>' +
'<td style = "text-shadow: 0px 0px 8px #d87fff; box-shadow: 0px 0px 40px #000; background: rgba(0, 0, 0, 0.7); width: 200px; color: #e6b2ff; text-align: center;">' +
'<u><b><font size = 2>Achievements</font></b></u>' +
'<li style = "padding: 5px;">Elite Frontier of Sora' +
'<li style = "padding: 5px;">Ranked Top 20 on the PU ladder' +
'<li style = "padding: 5px;">Ranked Top 400 on the RU ladder<br><br>' +
'<u><b><font size = 2>Known for</font></b></u>' +
'<li style = "padding: 5px;">Sub/DD Lapras' +
'<li style = "padding: 5px;">Doctor of Sora' +
'<li style = "padding: 5px;">GOLBAT MOTHER FUCKER</tr></center>' +
'<tr><td colspan = 2><center><font size = 2 style = "text-shadow: 0px 0px 15px #d170ff;"><i style = "color: rgba(0, 0, 0, 0.8);"><b><font size = 2>Pokémon Reborn:</font></b> Byxbysion Wasteland theme</i></font><audio controls src = "https://dl.pushbulletusercontent.com/U6jcDqHbeUTxoZz8LKB3IgwK8u3970rA/Atmosphere-%20Findmuck.mp3" ' +
'style = "width: 100%; background: linear-gradient(135deg, black, #b516ff, black, #b516ff, black, #b516ff, black, #b516ff, black, #b516ff); box-shadow: 0px 0px 15px #d170ff;"></td></tr>' +
'<tr><td colspan = 2 style = "text-shadow: 0px 0px 8px #d170ff; color: rgba(0, 0, 0, 0.8);"><center>' + getBadges('frontiersrewop') + '</center></td></tr></table></div>');
},
terror2: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReply('|html|<div style = "padding: 7px; border: 2px solid black; color: white; background: radial-gradient(circle, #1919c1, #2143ed, #1919c1, #2143ed, #1919c1, #2143ed, #1919c1, #2143ed);"><center><b><font size="4" color="82127a">Terror</font></b></center><br>' +
'<center><i>"Looking for dank memes"</i> </center><br /><br />' +
'<b>Ace: </b>Mega Sharpedo/Garchomp<br />' +
'<b>Skilled at: </b>Being incredibly annoying, Balanced Hackmons, Certain Monotypes.<br />' +
'<b>Achievements: </b><br />' +
'<li>Best Ex-Electric & Ground Leader of Sora<br />' +
'<li>Current Water Leader of Sora<br />' +
'<li>Ex-Balanced Hackmons Frontier of Yagagadrazeel<br />' +
'<li>Achieved Top 10 in the Balanced Hackmons ladder<br />' +
'<li>Achieved Top 25 in the Ubers ladder<br />' +
'<img src="http://play.pokemonshowdown.com/sprites/xyani-shiny/greninja.gif"><img src="http://play.pokemonshowdown.com/sprites/xyani/ferrothorn.gif"><img src="http://play.pokemonshowdown.com/sprites/xyani-shiny/sharpedo.gif"><img src="http://play.pokemonshowdown.com/sprites/xyani/garchomp.gif">'+
getBadges('e4terror'));
},
////////////
//Music Cards
//////////////
feelingit: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<div class="infobox" style="cursor: url("http://i.imgur.com/c4qM0iM.gif") , auto; border: 0px ; background-image: url("http://files.gamebanana.com/img/ss/wips/4ffc9f6bed5e2.jpg") ; background-size: cover"><br \>' +
'<br \><center><b><font color=#FF9900 size=2>You Will Know Our Names</b></font><font color=#FF9900 size=2> \- <i>Xenoblade Chronicles</i></font><br \>' +
'<audio src="http://www.ssbwiki.com/images/f/f5/Victory%21_%28Shulk%29.ogg" controls="" style="width: 100% ; border: 2px solid #00CC00 ; background-color: #00000a" target="_blank"></audio></center><br \><br \>');
},
easymoney: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<div style="background-image: url("http://i.imgur.com/orlVvMg.jpg") ; background-size: cover" target="_blank"><br \>' +
'<br \><center><font size=3 color=#FF9900><b>Easy Money</b> - <i>Bizzaro Flame</i></font><br \>' +
'<audio src="https://dl.pushbulletusercontent.com/qrAveUFTyNQlmvq3HEtlqSmBiuQeUaaQ/Easy%20Money.mp3" controls="" loop style="width: 100% ; border: 2px solid #00CC00 ; background-color: #00000a" target="_blank"></audio></center><br \><br \><br /><br /><br /><br /><br /><br /><br /><br />');
},
afraud: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<div style="background-image: url("http://i.imgur.com/jBfZq5A.jpg") ; background-size: cover"><br \><br /><br /><br /><br /><br /><br /><br /><br />' +
'<br \><center><font size=3 color=#00FF40><b>A Fraud</b> - <i>Izzaro Flame</i></font><br \>' +
'<audio src="https://dl.pushbulletusercontent.com/Pl3dDtxvFMbdAn6IZQHAF6gxFluLoAhA/A%20Fraud%20-%20%20A%20Big%20Fraud.mp3" controls="" loop style="width: 100% ; border: 2px solid #58FAF4 ; background-color: #00000a" target="_blank"></audio></center><br \><br \>');
},
getrekt: 'rekt',
rekt: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><img src = "https://lh3.googleusercontent.com/-6BDWwnjS9Cs/VajnpfmQumI/AAAAAAAAD7s/u1hZqlM09s0/w500-h200/img-3516109-1-Mc5cCal.gif">' +
'<audio autoplay controls style = "border: 2px solid red; background: black; width: 100%" src = "http://www.myinstants.com/media/sounds/wombo-combo_2.mp3">' +
'</audio></center>');
},
nojohns: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<div style = "background: url(http://i.imgur.com/dTD1J7o.gif); text-align: center; height: 299px; background-size: cover;"><span style = "color: red; font-weight: bold; font-size: 13pt;">No Johns</span><br>' +
'<audio controls src = "http://s0.vocaroo.com/media/download_temp/Vocaroo_s0JSb5SljS5I.mp3" style = "border: 1px solid yellow; border-radius: 0px; background: black; width: 100%"></audio>'
);
},
lyin: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReply('|html|<div class = "infobox" style = "background: url(https://pbs.twimg.com/profile_images/639126796223451136/Mwvgb7qH.png) no-repeat 0px -30px; background-size: 100%; height: 300px;">' +
'<audio controls src = "http://b.sc.egghd.com/media/b0/a2/b0a2bf0d5e10ef92fcd8726640fabdb9.mp3?id=223206908&key=eadd7f5398105057d30329e22c595d27e4ce8794" style = "float: right; margin-top: 100px; margin-right: 5px; background: black; border: 2px solid red;"></div>'
);
},
ichibannotakaramono: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<div class="infobox" style="border: 0px ; background-image: url("http://img2.wikia.nocookie.net/__cb20101231031301/angelbeats/images/f/f5/EP10-Yui-and-Hinata-500x281.png") ; background-size: cover" target="_blank">'+
'<center><font size=2 color=#0066FF><b>Original Version</b> - <i>Karuta</i></font><br \><audio src="https://dl.pushbulletusercontent.com/NBtI15PWK0EQDXkB8YNqKe6YZYWpLHaO/19%20-%20Ichiban%20no%20Takaramono%20%28Original%20Version%29.mp3" controls="" target="_blank"></audio><br /><br /><br /><br /><br /><br /><br /><br />'+
'<br \></center><b><font size=2 color=#FF0000> 一番の宝物</b></font><font size=2 color=#FF0000> \- <i>Angel Beats</i></font><br /><font size=1>Ichiban no Takaramono</font><center><br \><br \><br \><br \><br \><br \><font size=2 color=#0099FF><b>Yui\'s Version</b> - <i>Girls Dead Monster, feat. LiSA.</i></font><audio src="https://dl.pushbulletusercontent.com/5CLffau3dUgPCVIPwKyIQUjblB4NgQ5G/09%20-%20Ichiban%20no%20Takaramono%20%20%28Yui%20ver.%29.mp3" controls="" target="_blank"></audio></center>');
},
//////////
//Priomons Cards
/////////////
incweather: 'incweather',
incweather: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('Here is a detailed explanation of the format Inclement Weather:<br />' +
'- <a href="http://soraleague.weebly.com/inclement-weather.html">Inclement Weather</a><br />' +
'</div>');
},
nervepulse: 'priomonsnervepulse',
priomonsnervepulse: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<img src="http://oi58.tinypic.com/ayw0aq.jpg"> <br />');
},
tremorshock: 'priomonstremorshock',
priomonstremorshock: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<img src="http://oi58.tinypic.com/14u8e2s.jpg"> <br />');
},
fairywind: 'priomonsfairywind',
priomonsfairywind: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<img src="http://oi60.tinypic.com/33z7ndf.jpg"> <br />');
},
twineedle: 'priomonstwineedle',
priomonstwineedle: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<img src="http://oi58.tinypic.com/9h6i5z.jpg"> <br />');
},
dracocrash: 'priomonsdracocrash',
priomonsdracocrash: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<img src="http://oi59.tinypic.com/dyvvw2.jpg"> <br />');
},
flameshot: 'priomonsflameshot',
priomonsflameshot: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<img src="http://oi62.tinypic.com/29m6j5e.jpg"> <br />');
},
venomstrike: 'priomonsvenomstrike',
priomonsvenomstrike: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<img src="http://oi60.tinypic.com/2wf761w.jpg"> <br />');
},
divingcharge: 'priomonsdivingcharge',
priomonsdivingcharge: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<img src="http://oi58.tinypic.com/ezj4pl.jpg"> <br />');
},
stonespine: 'priomonsstonespine',
priomonsstonespine: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<img src="http://oi62.tinypic.com/2moy06e.jpg"> <br />');
},
sapblast: 'priomonssapblast',
priomonssapblast: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<img src="http://oi62.tinypic.com/23rk9oz.jpg"> <br />');
},
kineticforce: 'priomonskineticforce',
priomonskineticforce: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<img src="http://oi60.tinypic.com/1ptn36.jpg"> <br />');
},
////////////
//Informative Cards
//////////////
leaderranks: 'ranks',
ranks: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('Listed here are the Top 3 Leaders in The Sora League based on performance in our Monthly Promotional Tournament! Please keep in mind, the number of ranked Leaders may change month to month and the ranking methodology may be changed in the future.<br />' +
'-<b>1st <font color= 006b0a>Mitsuka</font></b> (Grass)<br />' +
'-<b>2nd <font color= FF0000>Waffles</font></b></b> (Fire)<br />' +
'-<b>3rd <font color= ff00b6>Connor</font></b> (Psychic)<br />' +
'</div>');
},
donate: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><font size = 2>If you wish to donate to the server, please click on the button below.<br>' +
'<a href = "https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=Q3B5Z6STF3EA4&lc=AU&item_name=Sora¤cy_code=AUD&bn=PP%2dDonationsBF%3abtn_donate_SM%2egif%3aNonHosted"><img src = "https://www.paypalobjects.com/en_AU/i/btn/btn_donate_SM.gif"></a><br>' +
'Remember to mention your username when you leave a note with your donation, or we won\'t know who donated. To all of those who\'ve donated or plan on donating, thank you! We really appreciate it!</center></font><br><br>' +
'<b>Donation benefits:</b><br>' +
'<strong>$1 or more:</strong>' +
'<li>Earns you the Server Donator badge, which will be displayed on your trainer card.' +
'<li>Allows you to set a custom username colour visible in chats, but not the userlist.<br><br>' +
'<strong>$5 or more:</strong>' +
'<li>All of the above^' +
'<li>A red <span style = "background: rgba(255, 26, 26, 0.5);">userlist highlight color</span>, visible on the Lobby\'s userlist');
},
ateam: 'adminteam',
adminteam: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<a><center><b><font color = 075ff7 size=3>The Admin Team</font></b></center></a><br />' +
'FAQ <br />' +
'<b>Who are we?</b> The Admin team are a group of senior members who make most of the major league decisions and organize most major league events. <br />' +
'<b>Who\'s in the Admin Team?</b> <a href="http://sora.cu.cc/ateam.html"><button style="background: #FF4747 ; border: 1px solid #FF0000">Current active members</button></a><br />' +
'<b>What exactly do you guys do?</b> The Admin Team handle or oversee all matters from disputes in the League, to League Challenge Registration <br />' +
'<b>How does one join the Admin team?</b> The Admin Team usually invites a select few senior members who\'ve shown to be mature and capable of handling responsibility. <br />' +
' <br /><br />' +
'<center><img src="http://sora.cu.cc/img/namelist.png"><br />'+
'All Admin team Members can be identified by their userlist highlight and by having this symbol on their badges:</center> <br />' +
'<center><img src="http://oi62.tinypic.com/14cfyh0.jpg"></center> <br />');
}
};
| custom/trainer-cards.js | function seen (user) {
user = toId(user);
if (Users.get(user) && Users.get(user).connected) return '';
return '<b>Last Seen:</b> ' + Core.getLastSeen(user).split(', ')[0] + ' ago';
}
function getBadges (user) {
var badgeList = JSON.parse(require('fs').readFileSync('storage-files/badges.json'));
user = toId(user);
if (!badgeList[user] || Object.keys(badgeList[user]).length < 3) return '';
var total = '<details><summary><b>Badges:</b> (Click here to open)</summary>';
for (var i in badgeList[user]) {
total += badgeList[user][i];
};
return total + '</details>';
}
exports.commands = {
staff: 'leaguemembers',
attendance: 'leaguemembers',
leaguemembers: function (target, room, user) {
if (!this.canBroadcast()) return;
var total = '<table><tr><th>User</th><th>Last Seen</th></tr>';
var list = ['∆Champiön Nöah∆', '∆Chаmpion Bart∆', '∆FrontierHead Risu∆', 'OnyxEagle', 'Blazing360', '∆Coach Abadon∆', 'Bamdee', '∆Frontier Jerattata∆', '∆Frontier Neith∆'];
for (var i = 0; i < list.length; i++) {
var Seen = Users.get(list[i]) && Users.get(list[i]).connected ? '<font color = "green">Online</font>' : seen(list[i]).substr(18);
if (Seen === 'never') Seen = '<font color = "red">Never</font>';
total += '<tr><td>' + list[i] + '</td><td><center>' + Seen + '</center></td>';
}
this.sendReplyBox('<center><b>Admin Team</b><br />' + total + '</table></center>');
var total = '<table><tr><th>User</th><th>Last Seen</th></tr>';
var list = ['∆E4 Edge∆', '∆E4 Terror∆', '∆E4 Alcor∆', '∆E4 Silvy∆', '∆Frontier Asch∆', '∆Frontier∆ Srewop', '∆Frontier Meows∆'];
for (var i = 0; i < list.length; i++) {
var Seen = Users.get(list[i]) && Users.get(list[i]).connected ? '<font color = "green">Online</font>' : seen(list[i]).substr(18);
if (Seen === 'never') Seen = '<font color = "red">Never</font>';
total += '<tr><td>' + list[i] + '</td><td><center>' + Seen + '</center></td>';
}
this.sendReplyBox('<details><summary><b>Elite 4\'s and Frontiers</b></summary><center>' + total + '</table></details></center>');
var total = '<table><tr><th>User</th><th>Last Seen</th></tr>';
var list = ['∆Gym Ldr Lou∆', '∆Gym Ldr Connor∆', '∆Gym Ldr Float∆',
'∆Gym Ldr Mark∆', '∆Gym Ldr Core∆', '∆Gym Ldr Waffles∆', '∆Gym Ldr Angel9∆', '∆Gym Ldr SolarWolf∆',
'∆Gym Ldr Mitsuka∆', '∆Gym Ldr TSwiv∆', '∆Gym Ldr BK∆', '∆Gym Ldr Flamespell∆', '∆Gym Ldr Bigo', '∆Gym Ldr. Elodin∆'
];
for (var i = 0; i < list.length; i++) {
var Seen = Users.get(list[i]) && Users.get(list[i]).connected ? '<font color = "green">Online</font>' : seen(list[i]).substr(18);
if (Seen === 'never') Seen = '<font color = "red">Never</font>';
total += '<tr><td>' + list[i] + '</td><td><center>' + Seen + '</center></td>';
}
this.sendReplyBox('<details><summary><b>Gym Leaders</b></summary><center>' + total + '</table></details></center>');
},
/////////////////////
//Admin Team
////////////////////
bart: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<a><font size= 4><center><b><font color = 07e1ed>∆Champion Bart∆</font></b></center></a><br />' +
'<center><i>"Sometimes I look at the bright blue sky and say to myself \'I FUCKED UP, I FUCKED UP\' "</i></center> <br />' +
'<b>Ace:</b> Weavile<br />' +
'<b>Battle Rules:</b> <br/>' +
'-Ubers Battle <br/>' +
'-At least 2 must be tiered lower than OU <br/>' +
'-No Lowering opponents stats (Unless caused by attack) <br/>' +
'-No Pokemon with a base stat over 130<br />' +
'<center><img src="http://sprites.pokecheck.org/i/461.gif"> <img src="http://i1280.photobucket.com/albums/a482/Skarmory11/Misc%20sprites/Bart_zps03ad3a7d.png"><img src="http://play.pokemonshowdown.com/sprites/xyani/torterra.gif"></center>' +
'<center><img src="http://oi62.tinypic.com/14cfyh0.jpg"></center> <br />');
},
noah: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<a><font size= 4><center><b><font color = 430747>∆Champion Noah∆</font></b></center></a><br />' +
'<center><i>"Need a Champion? I Noah guy."</i></center> <br />' +
'<center><img src="http://sprites.pokecheck.org/i/134.gif"><img src="http://i.imgur.com/iu4Njdf.png"></center><br />' +
'<b>Ace:</b> All <br />' +
'<b>Battle Rules:</b> <br/>' +
'-Ubers <br/>' +
'<center><img src="http://oi62.tinypic.com/14cfyh0.jpg"></center> <br />');
},
onyx: 'onyxeagle',
onyxeagle: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<a><font face = forte><font color = b27300><font size= 5><center>∆OnyxEagle∆</center></font></a><br />' +
'<center><i>"Heads or Tails? Heads, I Win; Tails, you Lose"</i></center> <br />' +
'<b>Skilled in:</b> Rock types/ Ubers, Random Battle and OU to a certain degree.<br />' +
'<b>History:</b> 2nd Champion of New Sora. One of the 2 people who resurrected Sora from the rubbles. <br/>' +
'<b>Notes:</b> Resident coder of Sora, still conducts tests and registrations, offers advice. <br/>' +
'<img src="http://play.pokemonshowdown.com/sprites/xyani/kabutops.gif"> <img src="http://play.pokemonshowdown.com/sprites/xyani/landorus.gif"> <img src="http://play.pokemonshowdown.com/sprites/xyani/heracross-mega.gif"> <img src="http://play.pokemonshowdown.com/sprites/xyani/tyranitar.gif"> <img src="http://play.pokemonshowdown.com/sprites/xyani/tyrantrum.gif">' +
'<center><img src="http://oi62.tinypic.com/14cfyh0.jpg"></center> <br />');
},
risu: 'ninjarisu',
ninjarisu: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<a><font size= 4><center><b>∆Frontierhead Ninjarisu∆</b></center></a><br />' +
'<i>"I will show you the power of the best of the worst"</i> <br />' +
'<b>Ace:</b> Pachirisu<br />' +
'<b>Symbol:</b> Puny Symbol<br />' +
'<b>Rules:</b> <a href="http://www.smogon.com/forums/threads/oras-fu-winner-of-omotm-machoke-sticky-web-banned.3519286/">FU</a> <br />' +
'<details><summary><b>Badges: (Click here to open)</b></summary><br />' +
'<a href="http://soraleague.weebly.com/badges.html#ldr"><img src="http://i.imgur.com/ELFPzW8.png" title="Achieved Gym Leader Status"></a><a href="http://soraleague.weebly.com/badges.html#frontier"><img src="http://i.imgur.com/7jbhEJC.png" title="Achieved Frontier Status"></a><a href="http://soraleague.weebly.com/badges.html#e4"><img src="http://i.imgur.com/QtECCD9.png" title="Achieved Elite 4 Status"></a><a href="http://soraleague.weebly.com/badges.html#starly"><img src="http://i.imgur.com/zaLhq1k.png" title="Starly Badge: One Year on Sora"></a><a href="http://soraleague.weebly.com/badges.html#staravia"><img src="http://i.imgur.com/2UmjiLt.png" title="Staravia Badge: Two Years on Sora"></a><a href="http://soraleague.weebly.com/badges.html#smeargle"><img src="http://i.imgur.com/A8h3FJN.png" title="Smeargle the Creator: Helped develop Champion\'s Challenge and Inclement Weather Metagames"></a></details><br />' +
'<img src="http://play.pokemonshowdown.com/sprites/xyani/pachirisu.gif"><img src="http://www.pkparaiso.com/imagenes/xy/sprites/animados/unown-romeo.gif"><img src="http://www.pkparaiso.com/imagenes/xy/sprites/animados/unown-india.gif"><img src="http://www.pkparaiso.com/imagenes/xy/sprites/animados/unown-sierra.gif"><img src="http://www.pkparaiso.com/imagenes/xy/sprites/animados/unown-uniform.gif"><img src="http://play.pokemonshowdown.com/sprites/xyani/pachirisu.gif">' +
'<center><img src="http://oi62.tinypic.com/14cfyh0.jpg"></center><br />');
},
//////////////
//Elite Four
//////////////
silvy: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('∆E4 <b>Silvy</b>∆<br />' +
'<i>"Silvy-Chan at your service, here to steel the kill. My body is regi. So come at me, if you will~ ;)"</i> <br />' +
'<b>Type: <font color = 5e6664>Steel</font></b><br />' +
'<b>Ace:</b> None <br />' +
'<b>Battle Rules:</b> <br/>' +
'- None<br />' +
seen('e4silvy') +
getBadges('siiilver'));
},
edge: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('∆E4 <b>Edge</b>∆<br />' +
'<i>"How can you face your problem when your problem is your face?"</i> <br />' +
'<b>Type: <font color = ff00b6>Psychic</font></b><br />' +
'<b>Ace:</b> Victini<br />' +
'<b>Battle Rules:</b><br />' +
'-No Hazards<br />' +
seen('e4edge') +
getBadges('e4edge'));
},
alcor: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('∆E4 <b>Alcor</b>∆<br />' +
'<i>"The pattern repeats, will your flaws too?"</i> <br />' +
'<b>Type: <font color = 7ab6ff>Flying</font></b><br />' +
'<b>Ace:</b> Togekiss<br />' +
'<b>Battle Rules:</b><br />' +
'-No Status Healing Moves<br />' +
seen('e4alcor') +
'<audio src="https://dl.pushbulletusercontent.com/nfP9iY95TAbBnLzJf1cAbLG7qegceAan/Last%20Decision%20%28%20Remastered%20And%20Extended%20%29.mp3" controls="" style="width: 100% ; border: 2px solid #700000 ; background-color: #000000" target="_blank"></audio>' +
getBadges('e4alcor'));
},
terror: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('∆E4 <b>Terror</b>∆<br />' +
'<i>"Better get out of the water because the waves are coming for you."</i> <br />' +
'<b>Type: <font color = 0745ff>Water</font></b><br />' +
'<b>Ace:</b> Mega Sharpedo<br />' +
'<b>Battle Rules:</b><br />' +
'-Item Clause (Only one of the same item may be used)<br />' +
seen('e4terror') +
getBadges('e4terror'));
},
/*sube4: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center>Sub E4 Position: <b><font color = FF0000>Offline</font></b></center><br />'+
'Sub E4 <b>???</b> <br />'+
'<b>Type:</b> <b><font color = 006b0a>???</font></b><br />'+
'<b>Battle Rules:</b> <br />'+
'-??? <br />'+
'-??? <br />');
},*/
/////////////
//Frontiers
/////////////
abadon: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><font size = 3><b>∆Coach Abadon∆<b></font><br>' +
'<i>"SWIGGITY SWOOTY I\'M COMING FOR THAT BOOTY"</i><br><br>' +
'<b>Achievements:</b>' +
'<li>Sora\'s best ground E4' +
'<li>Sora\'s coach' +
'<li>All round top bloke<br>' +
'<img style = "margin: 5px" src = "http://128.199.160.98:8000/avatars/' + Config.customavatars.coachabadon + '">' +
'<div style = "display: inline-block; width: 100px; height: 100px; background: url(http://www.pkparaiso.com/imagenes/xy/sprites/animados/gengar-3.gif) no-repeat -50px -70px"></div><br>' +
'<audio controls src = "https://dl.pushbulletusercontent.com/W9wf3ZGqXSIHvgVbdUtbl9PrWnPTl9SQ/deep.mp3" style = "color: black; width: 100%; border-radius: 0px;"></audio>'
+ getBadges('coachabadon') +'<br><img src="http://oi62.tinypic.com/14cfyh0.jpg"></center>');
},
asch: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('∆Elite Frontier <b>Asch</b>∆<br />' +
'<i>"Chief Akkie, head of the meme police, serving for 38 years; no meme slips through her cracks."</i> <br />' +
'<b>Symbol:</b> White Knight Symbol<br />' +
'<b>Ace:</b> Crawdaunt <br />' +
'<b>Battle Rules:</b> <br/>' +
'-Only BL, BL2, BL3 and BL4 Pokemon may be used.<br/>' +
'-No Mega Evolution<br />' +
seen('frontierasch') + '<br/>' +
'<img src="http://www.pkparaiso.com/imagenes/xy/sprites/animados/bulbasaur-3.gif"><img src="http://www.pkparaiso.com/imagenes/xy/sprites/animados/bulbasaur-3.gif">' +getBadges('frontierasch'));
},
blade: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<details><summary>This Frontier is currently on leave, Please contatc the Frontierhead for the subsitute</summary><a><center><img src="http://sprites.pokecheck.org/i/494.gif"><b><font color = FF0000 size= 4>∆Fröntier∆Blade☯</font></b><img src="http://sprites.pokecheck.org/i/080.gif"></center></a><br />' +
'<center><i>"Be Stronger Than Your Strongest Excuse"</i></center> <br />' +
'<b>Symbol:</b> Yin and Yang <br />' +
'<b>Ace:</b> Mybro (Slowbro) <br />' +
'<b>Battle Rules:</b> <br />' +
'-Ability Shift Tier<br />' +
'-No Johns<br />' +
'<a href="http://www.smogon.com/forums/threads/ability-shift.3503100/">How Ability Shift works</a> <br />' +
'<a href="http://www.psypokes.com/lab/abilities.php">Pokemon Ability List</a> <br />' +
'<details><summary><b>Champion\'s Challenge Rules:</b></summary> <br />' +
'-NU Monotype<br />' +
'-R U Too Strong?</details><br />' +
'<details><summary><b>Badges: (Click here to open)</b></summary><br />' +
'<a href="http://soraleague.weebly.com/badges.html#ldr"><img src="http://i.imgur.com/ELFPzW8.png" title="Achieved Gym Leader Status"></a><a href="http://soraleague.weebly.com/badges.html#frontier"><img src="http://i.imgur.com/7jbhEJC.png" title="Achieved Frontier Status"></a><a href="http://soraleague.weebly.com/badges.html#efrontier"><img src="http://i.imgur.com/2iZp7Mi.png" title="Achieved Elite Frontier Status"></a><a href="http://soraleague.weebly.com/badges.html#starly"><img src="http://i.imgur.com/zaLhq1k.png" title="Starly Badge: One Year on Sora"></a><a href="http://soraleague.weebly.com/badges.html#porygon"><img src="http://i.imgur.com/bJrRxB8.png" title="Broke the server while trying to repair and implement new features, good job mate, now go fix it"></a><a href="http://soraleague.weebly.com/badges.html#smeargle"><img src="http://i.imgur.com/A8h3FJN.png" title="Smeargle the Creator: Creator of the Badge System"></a></details> <br />' +
'<details><summary><font color = 009900><center><b>Torkoal Shrine</b></center></font></summary><center><img src="http://play.pokemonshowdown.com/sprites/xyani-shiny/torkoal.gif"></center>' +
'<center><b>R.I.P. War Turtle</b></center> <br />' +
'<center>1st Apostle of the All Mighty Lord Parasect</center></details><br />' +
'<center><img src="http://oi62.tinypic.com/14cfyh0.jpg"></center> <br /></details>');
},
meows: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('∆Frontier <b>Meows</b>∆<br />' +
'<i>"Abs=Win"</i> <br />' +
'<b>Symbol: </b>Patience <br />' +
'<b>Ace:</b> Quagsire<br />' +
'<b>Battle rules:</b> <br />' +
'-OU<br />' +
'-No Trick/Switcheroo <br />' + seen('frontiermeows') + getBadges('frontiermeows'));
},
srewop: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('∆Elite Frontier <b>Srewop</b>∆<br />' +
'<i>"You came to the wong place if you wanted a win."</i> <br />' +
'<b>Symbol:</b> SumTingWong<br />' +
'<b>Ace:</b> Golbat <br />' +
'<b>Battle Rules:</b> <br/>' +
'-RU Monotype <br/>' +
'-No Hazards <br/>' +
'-No Knock off<br />' +
'-No Megas<br />' +
seen('frontiersrewop') + '<br/>' +
'<center><img src="http://play.pokemonshowdown.com/sprites/xyani/zubat.gif"><img src="http://play.pokemonshowdown.com/sprites/xyani/golbat.gif"><img src="http://play.pokemonshowdown.com/sprites/xyani/zubat.gif"><img src="http://play.pokemonshowdown.com/sprites/xyani/gengar.gif"></center> <br />');
},
jerattata: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('∆Frontier <b>Jerattata</b>∆<br />' +
'<i>"Decide which of the two options is harder, and do the other. You might enjoy the battle."</i> <br />' +
'<b>Symbol:</b> Foresight <br />' +
'<b>Ace:</b> All<br />' +
'<b>Battle rules:</b> <br />' +
'-Challenger picks either a Tier/Meta <b>or</b> Battle Rule (within reason) <br />' +
'-Jeratt picks either a Tier/Meta or Battle Rule depending on which the challenger picks. <br />'+
'-Both the Tier/Meta and Battle rule that are decided upon are combined and are used for the battle.<br />'+
'-Monotype battles are banned. <br />' + seen('frontierjerattata'));
},
zachary: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('∆Frontier <b>Zachary</b>∆<br/>' +
'<i>"Can you do a few things at the same time?"</i><br/>' +
'<b>Symbol:</b> Multitasking<br/>' +
'<b>Ace:</b> All<br/>' +
'<b>Battle Rules:</b><br/>' +
'-Smogon Doubles<br />' +
'-No hazards<br />' +
'<details><summary><b>Champion\'s Challenge Rules:</b></summary> <br />' +
'-Pikachu Tournamentchu <br />' +
'-No CAP Pokemon</details> <br />' + seen('frontierzachary') + getBadges('frontierzachary'));
},
/*subfrontier: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center>Sub Frontier Position: <b><font color = FF0000>Offline</font></b></center><br />'+
'Sub Frontier <b>???</b> <br />'+
'<b>Symbol:</b> ???<br />'+
'<b>Battle Rules:</b> <br />');
},*/
//////////////
//Gym Leaders
//////////////
bug: 'flamespell',
flamespell: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('∆Gym Ldr <b>Flamespell</b>∆<br />'+
'<i>"Fear is the ultimate weapon, Fear my swarm."</i> <br />'+
'<b>Type: <font color = 65b510>Bug</font></b><br />'+
'<b>Ace:</b> Mega Pinsir <br />' + seen('gymldrflamespell') + getBadges('gymldrflamespell'));
},
dark: 'bk',
bk: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('∆Gym Ldr <b>BK</b>∆<br />' +
'<i>"There is always a light even at the darkest of times."</i> <br />' +
'<b>Type: <font color = 15012b>Dark</font></b><br />' +
'<b>Ace:</b> Bisharp<br />' +
seen('gymldrBK') + '<br />');
},
dragon: 'lou',
lou: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('∆Gym Ldr <b>Lou</b>∆<br />' +
'<i>"Dragon mono + Outrage = win"</i> <br />' +
'<b>Type: <font color = 230077>Dragon</font> </b><br />' +
'<b>Ace:</b> Latias<br />' + seen('gymldrlou') + getBadges('gymldrlou'));
},
electric: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('∆Gym Ldr <b>>???</b>∆<br />' +
'<i>"???"</i><br />' +
'<b>Type: <font color = d6cc0c>Electric</font></b><br />' +
'<b>Ace:</b> ???<br />' + seen('') + getBadges(''));
},
elodin: 'fairy',
fairy: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('∆Gym Ldr <b>Elodin</b>∆<br />' +
'<i>"All you need is faith, trust, and a little pixie dust"</i> <br />' +
'<b>Type: <font color = ff42a0>Fairy</font></b><br />' +
'<b>Ace: </b>Mega Gardevoir<br />' + seen('gymldrelodin') + getBadges('gymldrelodin'));
},
ground: 'mewtwo',
mewtwo: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('∆Gym Ldr <b>Mewtwo</b>∆<br />' +
'<i>"Cute, you thought you could beat me. Lemme show you the power of my Excadrill\'s Earthquake or my Zygarde\'s Outrage. You thought you could get my gym badge think again."</i> <br />' +
'<b>Type: <font color = A64000>Ground</font></b><br />' +
'<b>Ace: </b>Zygarde<br />');
},
fighting: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('∆Gym Ldr <b>???</b>∆<br />'+
'<i>"???"</i> <br />'+
'<b>Type: <font color = d83c08>Fighting</font></b><br />'+
'<b>Ace:</b> ???<br />' + seen('') + getBadges(''));
},
fire: 'waffles',
waffles: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('∆Gym Ldr <b>Waffles</b>∆<br />'+
'Leader Ranking: <font color = FFFF00><b>2nd</font></b> <br />' +
'<i>"Don\'t waffle out of the situation."</i> <br />'+
'<b>Type: <font color = FF0000>Fire</font></b><br />'+
'<b>Ace: Infernape</b> <br />' + seen('gymldrwaffles') + '<br>' +
'<img src = "http://sprites.pokecheck.org/t/010.gif"> <img src = "http://play.pokemonshowdown.com/sprites/xyani/heatran.gif"><br>' +
getBadges('gymldrwaffles'));
},
flying: 'float',
float: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('∆Gym Ldr <b>Float</b>∆<br />' +
'<i>"flap... flap... flap... bird type...?"</i> <br />' +
'<b>Type: <font color = 7ab6ff>Flying</font></b><br />' +
'<b>Ace:</b> Hawlucha (John Cena)<br />' +
'<img src="http://play.pokemonshowdown.com/sprites/xyani-shiny/beldum.gif"><img src="http://play.pokemonshowdown.com/sprites/xyani-shiny/aron.gif"><img src="http://play.pokemonshowdown.com/sprites/xyani/metagross-mega.gif"><img src="http://play.pokemonshowdown.com/sprites/xyani-shiny/aron.gif"><img src="http://play.pokemonshowdown.com/sprites/xyani-shiny/beldum.gif"><br />' +
'<audio controls src = "http://picosong.com/cdn/f47cf8120a89402a77ed76e2494d20fb.mp3" style = "border-radius: 0px; background: black;"></audio></br></br>' +
seen('gymldrfloat') + getBadges('gymldrfloat'));
},
ghost: 'tswiv',
tswiv: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('∆Gym Ldr <b>TSwiv</b>∆<br />' +
'<i>"Let the séance begin.......MWAHAHAHA"</i> <br />' +
'<b>Type: <font color = 7814e2>Ghost</font></b><br />' +
'<b>Ace:</b> Sableye<br />' + seen('gymldrtswiv') + getBadges('gymldrtswiv'));
},
mitsuka: 'grass',
grass: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('∆Gym Ldr <b>Mitsuka</b>∆<br />'+
'Leader Ranking: <font color = FF0000><b>1st</font></b> <br />' +
'<i>"Storm of leaf and Draining root!"</i> <br />'+
'<b>Type: <font color = 006b0a>Grass</font></b> <br />'+
'<b>Ace:</b> Victreebel <br />' + seen('gymldrmitsuka') + getBadges('gymldrmitsuka'));
},
ice: 'mark',
mark: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('∆Gym Ldr <b>Mark</b>∆<br />' +
'<i>"Hard work pays off in the end."</i> <br />' +
'<b>Type: <font color = 00e0ac>Ice</font></b><br />' +
'<b>Ace:</b> Don\'t Do Drugs (Mega Glalie)<br />' +
seen('gymldrmark') + '<br>' +
'<img src = "http://play.pokemonshowdown.com/sprites/xyani-shiny/froslass.gif"> ' +
'<img src = "http://play.pokemonshowdown.com/sprites/xyani-shiny/glalie-mega.gif"><br>' +
'<audio controls src = "http://216.227.134.162/ost/rockman-2-megaman-2-complete-works/kbrxwhzvos/2-31-flash-man-stage-smd.mp3" style = "border: 2px solid cyan; border-radius: 3px; background-color: black;"></audio>' +
getBadges('gymldrmark')
);
},
normal: 'bigo',
bigo: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('∆Gym Ldr <b>Bigo</b>∆<br />'+
'<i>"Don\'t underestimate the normal, cause being \'normal\' doesn\'t mean to be weak"</i> <br />'+
'<b>Type: <font color = ffa5d5>Normal</font></b><br />'+
'<b>Ace:</b> Lopunny<br />' + seen('gymldrbigo') + getBadges('gymldrbigo'));
},
poison: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('∆Gym Ldr <b>???</b>∆<br />' +
'<i>"???"</i> <br />'+
'<b>Type: <font color = aa00ff>Poison</font></b><br />' +
'<b>Ace:</b> ???<br />' + seen('') + getBadges('gymldrcrash'));
},
psychic: 'connor',
connor: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('∆Gym Ldr <b>Connor</b>∆<br />' +
'Leader Ranking: <font color = 9dff00><b>3rd</font></b> <br />' +
'<i>"Psychic power isn\'t something that only a few people have. Everyone has psychic power. People just don\'t realize it."</i> <br />' +
'<b>Type: <font color = ff00b6>Psychic</font></b><br />' +
'<b>Ace:</b> Gardevoir <br />' + seen('gymldrconnor') + getBadges ('gymldrconnor'));
},
rock: 'core',
core: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('∆Gym Ldr <b>Core</b>∆<br />' +
'<i>"There\'s always a chance for a comeback if you leave yourself open"</i> <br />' +
'<b>Type: <font color = 472e10>Rock</font></b><br />' +
'<b>Ace:</b> Archeops<br />' + seen('gymldrcore') + getBadges('gymldrcore'));
},
solarwolf: 'steel',
steel: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('∆Gym Ldr <b>SolarWolf</b>∆<br />' +
'<i>"The best steel doesn\'t always shine the brightest, but it will smash your face in."</i> <br />' +
'<b>Type: <font color = 5e6664>Steel</font></b> <br />' +
'<b>Ace:</b> Bisharp <br />' +
seen('gymldrsolarwolf') + getBadges('gymldrsolarwolf'));
},
water: 'angel9',
angel9: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('∆Gym Ldr <b>Angel9</b>∆<br />' +
'<i>"Watch my beautiful waters submerge you deep."</i> <br />' +
'<b>Type: <font color = 0745ff>Water</font></b><br />' +
'<b>Ace:</b> Quagsire <br/>' +
seen('gymldrangel9') + getBadges('gymldrangel9'));
},
/////////////
//Other Cards
//////////////////
aboottothehead: 'abtth',
abtth: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><b><font size="4" color="03b206">ABootToTheHead</font></b></center><br>' +
'<center><i>"Stardust-weaved ARiA, please keep this melody going."</i></center><br /><br />' +
'<b>Ace: </b>Scizor and Whimsicott<br />' +
'<b>Favorite Pokemon: </b>Typhlosion and Scizor<br />' +
'<b>Preferred tiers: </b>VGC, Ubers, OU <br />' +
'<b>Known for: </b>VoltTurn and Whimsistall shenanigans<br />' +
'<b>Achievements: </b>Ex-Elite Frontier, ex-Elite Four<br>' +
'<b>Affiliation:</b> Cheeky Nandos Squad<br><br>' +
'<center><img src="http://sprites.pokecheck.org/i/157.gif"><img src="http://sprites.pokecheck.org/i/530.gif"><img src="http://sprites.pokecheck.org/i/547.gif"><img src="http://sprites.pokecheck.org/t/144.gif"><img src="http://sprites.pokecheck.org/i/205.gif"><img src="http://sprites.pokecheck.org/i/310.gif"><img src="http://sprites.pokecheck.org/i/212.gif"></center><br />' +
'<center><img src = "http://i.imgur.com/AaO6Xze.png" width = "120" height = "120"><img src = "http://i.imgur.com/JSRaFVC.png" width = "120" height = "120"><img src = "http://i.imgur.com/I0NbMSO.png" width = "120" height = "120"></center><br>' +
getBadges('aboottothehead') + '<br>' +
'<center><img src = "http://i.imgur.com/ty6OYpg.png" width = "100" height = "100"> <img src = "http://i.imgur.com/YoDeO4O.png" width = "100" height = "100"></center>');
},
sorarani: 'arani',
arani: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><b><font color = "#331D81" size = 3>∆Arani∆</font></b><br>' +
'<i>"Rain teams are old school? Well... screw you."</i><br><br>' +
'<b>Skilled in:</b> Gen 5 OU - was consistently in the Top 10 on the global OU ladder.<br>' +
'<b>History:</b> First new Champ of Sora - ressurrected it along with Onyx.<br>' +
'<b>Present:</b> Serving in the defense force - Occasionally comes online.<br>' +
seen('sorarani') + '<br>' +
'<img src = "http://play.pokemonshowdown.com/sprites/xyani/keldeo-resolute.gif"><img src = "http://play.pokemonshowdown.com/sprites/xyani/thundurus-therian.gif">');
},
arjunb: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><input type="image" src="http://i.imgur.com/bnCFCm5.png"><div align="center"><br />' +
'<div align="center">"<i>Fall seven times, stand up eight. That\'s what I do</i>"</div><br />' +
'<b>Favorite Types:</b> Fighting, Dark and Poison(with crobat)<br />' +
'<b> Achievements:</b> Former Elite, got the elite position in his first promo tournaments.<br />' +
'<b>Favorite Pokemon:</b><br />' +
'<img src="http://play.pokemonshowdown.com/sprites/xyani/terrakion.gif"><img src="http://play.pokemonshowdown.com/sprites/xyani/weavile.gif"><img src="http://play.pokemonshowdown.com/sprites/xyani/medicham-mega.gif"><img src="http://play.pokemonshowdown.com/sprites/xyani/crobat.gif"><div align="center"><br />' +
+getBadges('arjunb'));
},
ascher: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><b><font size="4" color="86e755">Ascher</font></b></center><br />' +
'<center><img src="http://play.pokemonshowdown.com/sprites/xyani/shroomish.gif"></center> <br />' +getBadges('frontierasch'));
},
azh: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<div style = "padding: 8px; color: white; background: #000 url(http://www.pageresource.com/wallpapers/wallpaper/pokemon_67267.jpg) no-repeat scroll bottom; background-size: 100%;">' +
'<center><b><font size= 5>∆ArthurZH∆</font></b></center><br />'+
'<center><i>"The power of the seas, storms and rivers are mine to hold....and here you dare to stand before me?"</i></center> <br />'+
'<center><b>Favoured Type:</b> Water<br />'+
'<b>Favoured Metagame:</b> Smogon Doubles <br />'+
'<b>Favourite Pokemon:</b> Gyarados</center><br />'+
'<b>Achievements:</b> Ex Water Leader of Sora, Ex Roulette/Champion\'s Challenge/Monotype Frontier of Sora<br />'+
'<b>Current Position:</b> Smogon Doubles OU Frontier<br />'+
'<center><img src="http://fc00.deviantart.net/fs71/f/2014/082/f/8/manaphy_gif_by_gloomymyth-d7bakkc.gif"><img src="http://play.pokemonshowdown.com/sprites/xyani/keldeo-resolute.gif"><img src="http://www.pkparaiso.com/imagenes/xy/sprites/animados/tentacruel.gif"><img src="http://www.pokemonreborn.com/custom/44203.png?530"> <img src="http://play.pokemonshowdown.com/sprites/xyani/kabutops.gif"><img src="http://www.pkparaiso.com/imagenes/xy/sprites/animados/swampert.gif"><img src="http://play.pokemonshowdown.com/sprites/xyani/gyarados.gif"></center>'+
'<center><font size=2 color=#0000FF><b>Battle Theme</b> - <i>Hoenn Oceanic Museum Remix [Credits: GlitchXCity]</i></font><br \><audio src="https://dl.pushbulletusercontent.com/rd0Qhn6drs85cyLNk7XIxGmwLQHQl4q1/Atmosphere-%20Bright.mp3" controls="" style="width: 100% ; border: 2px solid #0000FF ; background-color: #3399FF" target="_blank"></audio></center><br \>' +getBadges('frontierzachary'));
},
bamdee: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><span style = "font-size: 15pt; color: #ff00b6;"><b>Bamdee</b></span></center><br>' +
'<center><img src="http://play.pokemonshowdown.com/sprites/xyani/ditto.gif"></center><br>' +
'<audio controls src = "https://dl.pushbulletusercontent.com/xFgUAMGfNsNhld0TC7Bf9nehzEiVRkGo/sonic.mp3" style = "border: 2px solid pink; background: black; width: 100%;"></audio><br>' +
getBadges('bamdee')
);
},
darkus: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><span style = "font-size: 11pt; font-weight: bold; color: ' + Core.color('soradarkus') + '">∆SoraDarkus∆</span><br>' +
'<i>"It\'s all shits and giggles until someone giggles and shits."</i><br><br>' +
'<b>Aces:</b> Bisharp and Crawdaunt<br>' +
'<b>Skilled in:</b> Monotype<br>' +
'<b>Preferred types:</b> Dark, Psychic and Steel<br>' +
'<b>Achievements:</b> Sora E4, Gym Leader and Side-Mission<br>' +
'<b>Known for:</b> Being one of the original members of Sora, and having mad Dark mono skills.<br>' +
seen('soradarkus') + '<br>' +
'<img src = "http://play.pokemonshowdown.com/sprites/xyani/bisharp.gif"> <img src = "http://play.pokemonshowdown.com/sprites/xyani/crawdaunt.gif" style = "transform: rotateY(180deg)"><br>' +
getBadges('soradarkus'));
},
edgy: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<a><font size= 4><center><b><font color = 00CCFF>Edgy</font></b></center></a><br />' +
'<center><img src="http://play.pokemonshowdown.com/sprites/xyani/gardevoir-mega.gif"><img src="http://play.pokemonshowdown.com/sprites/xyani/lopunny-mega.gif"><img src="http://play.pokemonshowdown.com/sprites/xyani/charizard-mega-x.gif"><img src="http://play.pokemonshowdown.com/sprites/xyani/lopunny-mega.gif"><img src="http://play.pokemonshowdown.com/sprites/xyani/gardevoir-mega.gif"></center> <br />' +
'<center><i>"How can you face your problem, if the problem is your face?"</i></center><br />' +
'<details><summary><font size= 1><b>Badges: (Click here to open)</b></font></summary><br />' +
'<a href="http://soraleague.weebly.com/badges.html#ldr"><img src="http://i.imgur.com/ELFPzW8.png" title="Achieved Gym Leader Status"></a><a href="http://soraleague.weebly.com/badges.html#e4"><img src="http://i.imgur.com/QtECCD9.png" title="Achieved Elite 4 Status"></a><a href="http://soraleague.weebly.com/badges.html#aegislash"><img src="http://i.imgur.com/aJY3eKg.png" title="Winner of Sora\'s first major Monotype Round Robin Tour"></a></details> <br />');
},
gasp: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('Trainer <b>gasp</b><br />' +
'<i>"Lights out."</i> <br />' +
'<b>Ace:</b> Mega Gengar<br />' +
'<b>Honours:</b> Sora\'s first challenger to reach Hall of Fame.<br />' +
'<b>Prefered Tier:</b> Balanced Hackmons' +
'<img src="http://pldh.net/media/pokemon/gen5/blackwhite_animated_front/302.gif"> <img src="http://media.tumblr.com/tumblr_m6ci5tQsEv1qf6fp2.gif"><br />' +getBadges('gasp'));
},
leafy: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReply('|html|<div style = "padding: 5px; text-align: center; background-image: url(http://i1171.photobucket.com/albums/r545/Brahak/maple_zpsg5sgjduk.jpg) no-repeat scroll bottom; background-size: cover;">' +
'<font size = 4 color = "white"><b>∆Leaf∆</b></font><br><br>' +
'<table align = "center" border = "0px" style = "color: #707c71">' +
'<tr><td style = "background: rgba(0, 0, 0, 0.9); width: 200px; height: 120px"><b><u><span style = "font-size: 10pt">Achievements</span></u></b><br>' +
'<li style = "padding: 3px">Successfully ran two leagues.' +
'<li style = "padding: 3px">Been a Gym Leader, Elite Four, and Frontier in Sora.</td>' +
'<td style = "padding: 0px 8px 0px 8px;"><img src = "http://play.pokemonshowdown.com/sprites/xyani/grovyle.gif"></td>' +
'<td style = "background: rgba(0, 0, 0, 0.9); width: 200px;"><b><u><span style = "font-size: 10pt">Known for</span></u></b><br>' +
'<li style = "padding: 3px">Scarf Kyurem set.' +
'<li style = "padding: 3px">Mega Blastoise and Cinccino favourites.' +
'<li style = "padding: 3px">Resident drunk of Sora.</td></tr></table><br>' +
'<table align = "center"><tr><td><div style = "display: inline-block; width: 120px; height: 101px; background: url(http://www.pkparaiso.com/imagenes/xy/sprites/animados/leafeon-2.gif) no-repeat 0px -70px"></div></td>' +
'<td><div style = "transform: rotateY(180deg); display: inline-block; width: 120px; height: 101px; background: url(http://www.pkparaiso.com/imagenes/xy/sprites/animados/leafeon-2.gif) no-repeat 0px -70px"></div></td></tr></table>' +
'<center><audio controls src = "https://dl.pushbulletusercontent.com/91078HKzh36ORZdMm7EaE2suEdL7iwr1/Devil%20Survivor%202%20-%20Septentrion%20%5Bwww.songmirror.org%5D.mp3" style = "width: 100%; border-radius: 0px; background: linear-gradient(45deg, #011100, #00ad17, #011100, #00ad17, #011100, #00ad17, #011100, #00ad17);"></audio><br>' +
getBadges('e4alcor') +
'</div>');
},
meowsofsora: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<b><font color = 55dbe8><a><font size= 4><center>MeowsofSora</font></center></b><br />'+
'<center><i>"I might be a bitch, but I\'m definitely not a pussy"</i><br />'+
'<i>"Abs=Win"</i><br /><br />'+
'<b>Who am I:</b> Resident OU Specialist and OM Lover <br />'+
'<b>Specialty:</b> OU <br />'+
'<b>Ace:</b> Latios and Azumarill </center><br />'+
'<b>Achievements:</b> Peaked top 20 for OU/OU (No Mega), top 500 for Monotype <br />'+
'<b>Current Position:</b> OU Frontier of Sora <br />'+
'<center><img src="http://play.pokemonshowdown.com/sprites/xyani/latios.gif"><img src="http://play.pokemonshowdown.com/sprites/xyani/azumarill.gif"></center><br />'+
'<center><font size=2 color=#0000FF><b>Girl\'s Day</b> - <i>Ring My Bell (for hookups and battles)</i></font><br \><audio src="https://dl.pushbulletusercontent.com/GZk1vZlsoisCqMSCSnSOWV7bZlsjTroX/02%20%EB%A7%81%EB%A7%88%EB%B2%A8%20%28Ring%20My%20Bell%29.mp3" controls="" style="width: 100%" target="_blank"></audio></center><br \><br \>'+ getBadges('frontiermeows'));
},
jeratt: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<a><font size= 4><center><b>∆Artiste Jeratt∆</b></center></a><br />' +
'<center><i>"No one out-predicts me, but me."</i></center><br />' +
'<img src="http://sprites.pokecheck.org/i/235.gif"> <img src="http://sprites.pokecheck.org/t/033.gif"><br />' +
'<b>Highly skilled in:</b> Dragon & Ice<br />' +
'<b>Skilled in:</b> Making quotes, backgrounds for Sora and many Pokemon types.<br />' +
'<b>Note:</b> Close the Lobby and see what I can really do. <br/>' +
'<b>History:</b> Greatest Ice E4, <strike>undefeated</strike> Dragon E4. <br/>' +
'P.S. I\'m still Dragon you away with my coldness. <br/>' +
'P.P.S Use Scizor against me, and I\'ll get fired up and blast you! <br/>' +
'<center><img src="http://play.pokemonshowdown.com/sprites/xyani-shiny/rattata.gif"> <img src="http://play.pokemonshowdown.com/sprites/xyani-shiny/mamoswine.gif"> <img src="http://play.pokemonshowdown.com/sprites/xyani/vanilluxe.gif"> <img src="http://play.pokemonshowdown.com/sprites/xyani/dialga.gif"> <img src="http://play.pokemonshowdown.com/sprites/xyani/zoroark.gif"></center>' +
'<details><summary><b>Badges:</b></summary><br />' +
'<a href="http://soraleague.weebly.com/badges.html#smeargle"><img src="http://i.imgur.com/A8h3FJN.png" title="Smeargle the Creator: Resident Artist of Sora, Metagame Creator: CC, Priomons, Incl Weather, PokeSandbox"></a><a href="http://soraleague.weebly.com/badges.html#ldr"><img src="http://i.imgur.com/ELFPzW8.png" title="Achieved Gym Leader Status"></a><a href="http://soraleague.weebly.com/badges.html#frontier"><img src="http://i.imgur.com/7jbhEJC.png" title="Achieved Frontier Status"></a><a href="http://soraleague.weebly.com/badges.html#e4"><img src="http://i.imgur.com/QtECCD9.png" title="Achieved Elite 4 Status"></a><a href="http://soraleague.weebly.com/badges.html#badges"><img src="http://i.imgur.com/tnkW9J9.png" title="Badge Collector: Defeat all 18 Gym Leaders"></a><a href="http://soraleague.weebly.com/badges.html#starly"><img src="http://i.imgur.com/zaLhq1k.png" title="Starly Badge: One Year on Sora"></a><a href="http://soraleague.weebly.com/badges.html#porygon"><img src="http://i.imgur.com/bJrRxB8.png" title="Broke the server while trying to repair it, good job mate"></a> </details><br />' +
'<center><img src="http://oi62.tinypic.com/14cfyh0.jpg"></center> <br />');
},
nightanglet: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><i><font color="blue"><h1>Nightanglet</h1></font></center><br>' +
'<font color = "blue"><b>Ace: Infernape(CR Ace:Rhydon)<br />' +
'Custom Rules:<br />' +
'- No poke above the base speed of 40<br />' +
'- No Hazards<br />' +
'-Speed should not be increased or decreased<br />' +
'</b></i><img src="http://play.pokemonshowdown.com/sprites/xyani-shiny/infernape.gif"><img src="http://play.pokemonshowdown.com/sprites/xyani/rhydon.gif">');
},
swearwip: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReply('|html|<table style = "color: white; width: 100%; padding: 0px 10px 10px 10px; background: linear-gradient(45deg, #67108c, #3c0654, #67108c, #3c0654, #67108c, #3c0654, #67108c, #3c0654, #67108c, #3c0654);">' +
'<tr><td colspan = "2"><center><br><font size = 3 style = "margin-top: 10px; font-weight: bold; text-shadow: 3px 3px 10px black;">∆Srewop∆</font><br>' +
'<i style = "text-shadow: 3px 3px 10px black;">"I think you\'re in Gotham, \'cause the bat is coming for you..."</i><br><br></td></tr>' +
'<tr><td><center style = "text-shadow: 3px 3px 10px #000;"><b>Symbol:</b> SumTingWong<br><b>Battle Format:</b> RU Monotype<br>' +
'<b>Restrictions:</b><br><li>No Hazards<li>No Knock Off<br>' +
'<b>Ace:</b> Golbat<br>' +
'<img style = "margin: -5px" src = "http://www.pkparaiso.com/imagenes/xy/sprites/animados/golbat-2.gif"></center></td>' +
'<td style = "text-shadow: 0px 0px 8px #d87fff; box-shadow: 0px 0px 40px #000; background: rgba(0, 0, 0, 0.7); width: 200px; color: #e6b2ff; text-align: center;">' +
'<u><b><font size = 2>Achievements</font></b></u>' +
'<li style = "padding: 5px;">Elite Frontier of Sora' +
'<li style = "padding: 5px;">Ranked Top 20 on the PU ladder' +
'<li style = "padding: 5px;">Ranked Top 400 on the RU ladder<br><br>' +
'<u><b><font size = 2>Known for</font></b></u>' +
'<li style = "padding: 5px;">Sub/DD Lapras' +
'<li style = "padding: 5px;">Doctor of Sora' +
'<li style = "padding: 5px;">GOLBAT MOTHER FUCKER</tr></center>' +
'<tr><td colspan = 2><center><font size = 2 style = "text-shadow: 0px 0px 15px #d170ff;"><i style = "color: rgba(0, 0, 0, 0.8);"><b><font size = 2>Pokémon Reborn:</font></b> Byxbysion Wasteland theme</i></font><audio controls src = "https://dl.pushbulletusercontent.com/U6jcDqHbeUTxoZz8LKB3IgwK8u3970rA/Atmosphere-%20Findmuck.mp3" ' +
'style = "width: 100%; background: linear-gradient(135deg, black, #b516ff, black, #b516ff, black, #b516ff, black, #b516ff, black, #b516ff); box-shadow: 0px 0px 15px #d170ff;"></td></tr>' +
'<tr><td colspan = 2 style = "text-shadow: 0px 0px 8px #d170ff; color: rgba(0, 0, 0, 0.8);"><center>' + getBadges('frontiersrewop') + '</center></td></tr></table></div>');
},
terror2: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReply('|html|<div style = "padding: 7px; border: 2px solid black; color: white; background: radial-gradient(circle, #1919c1, #2143ed, #1919c1, #2143ed, #1919c1, #2143ed, #1919c1, #2143ed);"><center><b><font size="4" color="82127a">Terror</font></b></center><br>' +
'<center><i>"Looking for dank memes"</i> </center><br /><br />' +
'<b>Ace: </b>Mega Sharpedo/Garchomp<br />' +
'<b>Skilled at: </b>Being incredibly annoying, Balanced Hackmons, Certain Monotypes.<br />' +
'<b>Achievements: </b><br />' +
'<li>Best Ex-Electric & Ground Leader of Sora<br />' +
'<li>Current Water Leader of Sora<br />' +
'<li>Ex-Balanced Hackmons Frontier of Yagagadrazeel<br />' +
'<li>Achieved Top 10 in the Balanced Hackmons ladder<br />' +
'<li>Achieved Top 25 in the Ubers ladder<br />' +
'<img src="http://play.pokemonshowdown.com/sprites/xyani-shiny/greninja.gif"><img src="http://play.pokemonshowdown.com/sprites/xyani/ferrothorn.gif"><img src="http://play.pokemonshowdown.com/sprites/xyani-shiny/sharpedo.gif"><img src="http://play.pokemonshowdown.com/sprites/xyani/garchomp.gif">'+
getBadges('e4terror'));
},
////////////
//Music Cards
//////////////
feelingit: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<div class="infobox" style="cursor: url("http://i.imgur.com/c4qM0iM.gif") , auto; border: 0px ; background-image: url("http://files.gamebanana.com/img/ss/wips/4ffc9f6bed5e2.jpg") ; background-size: cover"><br \>' +
'<br \><center><b><font color=#FF9900 size=2>You Will Know Our Names</b></font><font color=#FF9900 size=2> \- <i>Xenoblade Chronicles</i></font><br \>' +
'<audio src="http://www.ssbwiki.com/images/f/f5/Victory%21_%28Shulk%29.ogg" controls="" style="width: 100% ; border: 2px solid #00CC00 ; background-color: #00000a" target="_blank"></audio></center><br \><br \>');
},
easymoney: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<div style="background-image: url("http://i.imgur.com/orlVvMg.jpg") ; background-size: cover" target="_blank"><br \>' +
'<br \><center><font size=3 color=#FF9900><b>Easy Money</b> - <i>Bizzaro Flame</i></font><br \>' +
'<audio src="https://dl.pushbulletusercontent.com/qrAveUFTyNQlmvq3HEtlqSmBiuQeUaaQ/Easy%20Money.mp3" controls="" loop style="width: 100% ; border: 2px solid #00CC00 ; background-color: #00000a" target="_blank"></audio></center><br \><br \><br /><br /><br /><br /><br /><br /><br /><br />');
},
afraud: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<div style="background-image: url("http://i.imgur.com/jBfZq5A.jpg") ; background-size: cover"><br \><br /><br /><br /><br /><br /><br /><br /><br />' +
'<br \><center><font size=3 color=#00FF40><b>A Fraud</b> - <i>Izzaro Flame</i></font><br \>' +
'<audio src="https://dl.pushbulletusercontent.com/Pl3dDtxvFMbdAn6IZQHAF6gxFluLoAhA/A%20Fraud%20-%20%20A%20Big%20Fraud.mp3" controls="" loop style="width: 100% ; border: 2px solid #58FAF4 ; background-color: #00000a" target="_blank"></audio></center><br \><br \>');
},
getrekt: 'rekt',
rekt: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><img src = "https://lh3.googleusercontent.com/-6BDWwnjS9Cs/VajnpfmQumI/AAAAAAAAD7s/u1hZqlM09s0/w500-h200/img-3516109-1-Mc5cCal.gif">' +
'<audio autoplay controls style = "border: 2px solid red; background: black; width: 100%" src = "http://www.myinstants.com/media/sounds/wombo-combo_2.mp3">' +
'</audio></center>');
},
nojohns: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<div style = "background: url(http://i.imgur.com/dTD1J7o.gif); text-align: center; height: 299px; background-size: cover;"><span style = "color: red; font-weight: bold; font-size: 13pt;">No Johns</span><br>' +
'<audio controls src = "http://s0.vocaroo.com/media/download_temp/Vocaroo_s0JSb5SljS5I.mp3" style = "border: 1px solid yellow; border-radius: 0px; background: black; width: 100%"></audio>'
);
},
lyin: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReply('|html|<div class = "infobox" style = "background: url(https://pbs.twimg.com/profile_images/639126796223451136/Mwvgb7qH.png) no-repeat 0px -30px; background-size: 100%; height: 300px;">' +
'<audio controls src = "http://b.sc.egghd.com/media/b0/a2/b0a2bf0d5e10ef92fcd8726640fabdb9.mp3?id=223206908&key=eadd7f5398105057d30329e22c595d27e4ce8794" style = "float: right; margin-top: 100px; margin-right: 5px; background: black; border: 2px solid red;"></div>'
);
},
ichibannotakaramono: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<div class="infobox" style="border: 0px ; background-image: url("http://img2.wikia.nocookie.net/__cb20101231031301/angelbeats/images/f/f5/EP10-Yui-and-Hinata-500x281.png") ; background-size: cover" target="_blank">'+
'<center><font size=2 color=#0066FF><b>Original Version</b> - <i>Karuta</i></font><br \><audio src="https://dl.pushbulletusercontent.com/NBtI15PWK0EQDXkB8YNqKe6YZYWpLHaO/19%20-%20Ichiban%20no%20Takaramono%20%28Original%20Version%29.mp3" controls="" target="_blank"></audio><br /><br /><br /><br /><br /><br /><br /><br />'+
'<br \></center><b><font size=2 color=#FF0000> 一番の宝物</b></font><font size=2 color=#FF0000> \- <i>Angel Beats</i></font><br /><font size=1>Ichiban no Takaramono</font><center><br \><br \><br \><br \><br \><br \><font size=2 color=#0099FF><b>Yui\'s Version</b> - <i>Girls Dead Monster, feat. LiSA.</i></font><audio src="https://dl.pushbulletusercontent.com/5CLffau3dUgPCVIPwKyIQUjblB4NgQ5G/09%20-%20Ichiban%20no%20Takaramono%20%20%28Yui%20ver.%29.mp3" controls="" target="_blank"></audio></center>');
},
//////////
//Priomons Cards
/////////////
incweather: 'incweather',
incweather: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('Here is a detailed explanation of the format Inclement Weather:<br />' +
'- <a href="http://soraleague.weebly.com/inclement-weather.html">Inclement Weather</a><br />' +
'</div>');
},
nervepulse: 'priomonsnervepulse',
priomonsnervepulse: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<img src="http://oi58.tinypic.com/ayw0aq.jpg"> <br />');
},
tremorshock: 'priomonstremorshock',
priomonstremorshock: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<img src="http://oi58.tinypic.com/14u8e2s.jpg"> <br />');
},
fairywind: 'priomonsfairywind',
priomonsfairywind: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<img src="http://oi60.tinypic.com/33z7ndf.jpg"> <br />');
},
twineedle: 'priomonstwineedle',
priomonstwineedle: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<img src="http://oi58.tinypic.com/9h6i5z.jpg"> <br />');
},
dracocrash: 'priomonsdracocrash',
priomonsdracocrash: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<img src="http://oi59.tinypic.com/dyvvw2.jpg"> <br />');
},
flameshot: 'priomonsflameshot',
priomonsflameshot: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<img src="http://oi62.tinypic.com/29m6j5e.jpg"> <br />');
},
venomstrike: 'priomonsvenomstrike',
priomonsvenomstrike: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<img src="http://oi60.tinypic.com/2wf761w.jpg"> <br />');
},
divingcharge: 'priomonsdivingcharge',
priomonsdivingcharge: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<img src="http://oi58.tinypic.com/ezj4pl.jpg"> <br />');
},
stonespine: 'priomonsstonespine',
priomonsstonespine: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<img src="http://oi62.tinypic.com/2moy06e.jpg"> <br />');
},
sapblast: 'priomonssapblast',
priomonssapblast: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<img src="http://oi62.tinypic.com/23rk9oz.jpg"> <br />');
},
kineticforce: 'priomonskineticforce',
priomonskineticforce: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<img src="http://oi60.tinypic.com/1ptn36.jpg"> <br />');
},
////////////
//Informative Cards
//////////////
leaderranks: 'ranks',
ranks: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('Listed here are the Top 3 Leaders in The Sora League based on performance in our Monthly Promotional Tournament! Please keep in mind, the number of ranked Leaders may change month to month and the ranking methodology may be changed in the future.<br />' +
'-<b>1st <font color= 006b0a>Mitsuka</font></b> (Grass)<br />' +
'-<b>2nd <font color= FF0000>Waffles</font></b></b> (Fire)<br />' +
'-<b>3rd <font color= ff00b6>Connor</font></b> (Psychic)<br />' +
'</div>');
},
donate: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><font size = 2>If you wish to donate to the server, please click on the button below.<br>' +
'<a href = "https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=Q3B5Z6STF3EA4&lc=AU&item_name=Sora¤cy_code=AUD&bn=PP%2dDonationsBF%3abtn_donate_SM%2egif%3aNonHosted"><img src = "https://www.paypalobjects.com/en_AU/i/btn/btn_donate_SM.gif"></a><br>' +
'Remember to mention your username when you leave a note with your donation, or we won\'t know who donated. To all of those who\'ve donated or plan on donating, thank you! We really appreciate it!</center></font><br><br>' +
'<b>Donation benefits:</b><br>' +
'<strong>$1 or more:</strong>' +
'<li>Earns you the Server Donator badge, which will be displayed on your trainer card.' +
'<li>Allows you to set a custom username colour visible in chats, but not the userlist.<br><br>' +
'<strong>$5 or more:</strong>' +
'<li>All of the above^' +
'<li>A red <span style = "background: rgba(255, 26, 26, 0.5);">userlist highlight color</span>, visible on the Lobby\'s userlist');
},
ateam: 'adminteam',
adminteam: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<a><center><b><font color = 075ff7 size=3>The Admin Team</font></b></center></a><br />' +
'FAQ <br />' +
'<b>Who are we?</b> The Admin team are a group of senior members who make most of the major league decisions and organize most major league events. <br />' +
'<b>Who\'s in the Admin Team?</b> <a href="http://sora.cu.cc/ateam.html"><button style="background: #FF4747 ; border: 1px solid #FF0000">Current active members</button></a><br />' +
'<b>What exactly do you guys do?</b> The Admin Team handle or oversee all matters from disputes in the League, to League Challenge Registration <br />' +
'<b>How does one join the Admin team?</b> The Admin Team usually invites a select few senior members who\'ve shown to be mature and capable of handling responsibility. <br />' +
' <br /><br />' +
'<center><img src="http://sora.cu.cc/img/namelist.png"><br />'+
'All Admin team Members can be identified by their userlist highlight and by having this symbol on their badges:</center> <br />' +
'<center><img src="http://oi62.tinypic.com/14cfyh0.jpg"></center> <br />');
}
};
| Update trainer-cards.js | custom/trainer-cards.js | Update trainer-cards.js | <ide><path>ustom/trainer-cards.js
<ide> var total = '<table><tr><th>User</th><th>Last Seen</th></tr>';
<ide> var list = ['∆Gym Ldr Lou∆', '∆Gym Ldr Connor∆', '∆Gym Ldr Float∆',
<ide> '∆Gym Ldr Mark∆', '∆Gym Ldr Core∆', '∆Gym Ldr Waffles∆', '∆Gym Ldr Angel9∆', '∆Gym Ldr SolarWolf∆',
<del> '∆Gym Ldr Mitsuka∆', '∆Gym Ldr TSwiv∆', '∆Gym Ldr BK∆', '∆Gym Ldr Flamespell∆', '∆Gym Ldr Bigo', '∆Gym Ldr. Elodin∆'
<add> '∆Gym Ldr Mitsuka∆', '∆Gym Ldr TSwiv∆', '∆Gym Ldr BK∆', '∆Gym Ldr Flamespell∆', '∆Gym Ldr Bigo∆', '∆Gym Ldr. Elodin∆', '∆Gym Ldr. Mewtwo∆'
<ide> ];
<ide> for (var i = 0; i < list.length; i++) {
<ide> var Seen = Users.get(list[i]) && Users.get(list[i]).connected ? '<font color = "green">Online</font>' : seen(list[i]).substr(18);
<ide>
<ide> blade: function (target, room, user) {
<ide> if (!this.canBroadcast()) return;
<del> this.sendReplyBox('<details><summary>This Frontier is currently on leave, Please contatc the Frontierhead for the subsitute</summary><a><center><img src="http://sprites.pokecheck.org/i/494.gif"><b><font color = FF0000 size= 4>∆Fröntier∆Blade☯</font></b><img src="http://sprites.pokecheck.org/i/080.gif"></center></a><br />' +
<add> this.sendReplyBox('<details><summary>This Frontier is currently on leave, Please contact the Frontierhead for the subsitute. P.s click me I have a sexy card</summary><a><center><img src="http://sprites.pokecheck.org/i/494.gif"><b><font color = FF0000 size= 4>∆Fröntier∆Blade☯</font></b><img src="http://sprites.pokecheck.org/i/080.gif"></center></a><br />' +
<ide> '<center><i>"Be Stronger Than Your Strongest Excuse"</i></center> <br />' +
<ide> '<b>Symbol:</b> Yin and Yang <br />' +
<ide> '<b>Ace:</b> Mybro (Slowbro) <br />' + |
|
Java | apache-2.0 | a18aaefe855ea789bdadee945d7d763bc83529c4 | 0 | mF2C/COMPSs,mF2C/COMPSs,mF2C/COMPSs,mF2C/COMPSs,mF2C/COMPSs,mF2C/COMPSs | package integratedtoolkit.types.allocatableactions;
import integratedtoolkit.comm.Comm;
import integratedtoolkit.components.impl.ResourceScheduler;
import integratedtoolkit.components.impl.TaskProducer;
import integratedtoolkit.log.Loggers;
import integratedtoolkit.types.Task;
import integratedtoolkit.types.TaskDescription;
import integratedtoolkit.types.Task.TaskState;
import integratedtoolkit.types.annotations.parameter.Direction;
import integratedtoolkit.scheduler.exceptions.BlockedActionException;
import integratedtoolkit.scheduler.exceptions.FailedActionException;
import integratedtoolkit.scheduler.exceptions.UnassignedActionException;
import integratedtoolkit.scheduler.types.ActionOrchestrator;
import integratedtoolkit.scheduler.types.AllocatableAction;
import integratedtoolkit.scheduler.types.Profile;
import integratedtoolkit.scheduler.types.SchedulingInformation;
import integratedtoolkit.scheduler.types.Score;
import integratedtoolkit.types.data.DataAccessId;
import integratedtoolkit.types.data.DataInstanceId;
import integratedtoolkit.types.data.LogicalData;
import integratedtoolkit.types.data.location.DataLocation;
import integratedtoolkit.types.data.operation.JobTransfersListener;
import integratedtoolkit.types.implementations.Implementation;
import integratedtoolkit.types.implementations.Implementation.TaskType;
import integratedtoolkit.types.job.Job;
import integratedtoolkit.types.job.JobListener.JobEndStatus;
import integratedtoolkit.types.parameter.DependencyParameter;
import integratedtoolkit.types.parameter.Parameter;
import integratedtoolkit.types.job.JobStatusListener;
import integratedtoolkit.types.resources.Worker;
import integratedtoolkit.types.resources.WorkerResourceDescription;
import integratedtoolkit.types.uri.SimpleURI;
import integratedtoolkit.util.CoreManager;
import integratedtoolkit.util.ErrorManager;
import integratedtoolkit.util.JobDispatcher;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class ExecutionAction<P extends Profile, T extends WorkerResourceDescription, I extends Implementation<T>>
extends AllocatableAction<P, T, I> {
// Fault tolerance parameters
private static final int TRANSFER_CHANCES = 2;
private static final int SUBMISSION_CHANCES = 2;
private static final int SCHEDULING_CHANCES = 2;
// LOGGER
private static final Logger JOB_LOGGER = LogManager.getLogger(Loggers.JM_COMP);
// Execution Info
protected final TaskProducer producer;
protected final Task task;
private final LinkedList<Integer> jobs;
private int transferErrors = 0;
protected int executionErrors = 0;
// Resource execution information
private final ResourceScheduler<P, T, I> forcedResource;
private T resourceConsumption;
/**
* Creates a new execution action
*
* @param schedulingInformation
* @param producer
* @param task
* @param forcedResource
*/
@SuppressWarnings("unchecked")
public ExecutionAction(SchedulingInformation<P, T, I> schedulingInformation, ActionOrchestrator<P, T, I> orchestrator,
TaskProducer producer, Task task, ResourceScheduler<P, T, I> forcedResource) {
super(schedulingInformation, orchestrator);
this.producer = producer;
this.task = task;
this.jobs = new LinkedList<>();
this.transferErrors = 0;
this.executionErrors = 0;
this.forcedResource = forcedResource;
this.resourceConsumption = null;
// Add execution to task
this.task.addExecution(this);
// Register data dependencies events
for (Task predecessor : this.task.getPredecessors()) {
for (ExecutionAction<?, ?, ?> e : predecessor.getExecutions()) {
if (e != null && e.isPending()) {
addDataPredecessor((ExecutionAction<P, T, I>) e);
}
}
}
// Scheduling constraints
// Restricted resource
Task resourceConstraintTask = this.task.getEnforcingTask();
if (resourceConstraintTask != null) {
for (ExecutionAction<?, ?, ?> e : resourceConstraintTask.getExecutions()) {
addResourceConstraint((ExecutionAction<P, T, I>) e);
}
}
}
/**
* Returns the associated task
*
* @return
*/
public final Task getTask() {
return this.task;
}
/*
* ***************************************************************************************************************
* EXECUTION AND LIFECYCLE MANAGEMENT
* ***************************************************************************************************************
*/
@Override
public final boolean areEnoughResources() {
Worker<T, I> w = selectedResource.getResource();
return w.canRunNow(selectedImpl.getRequirements());
}
@Override
protected final void reserveResources() {
Worker<T, I> w = selectedResource.getResource();
resourceConsumption = w.runTask(selectedImpl.getRequirements());
}
@Override
protected final void releaseResources() {
Worker<T, I> w = selectedResource.getResource();
w.endTask(resourceConsumption);
}
@Override
protected void doAction() {
JOB_LOGGER.info("Ordering transfers to " + selectedResource + " to run task: " + task.getId());
transferErrors = 0;
executionErrors = 0;
doInputTransfers();
}
private final void doInputTransfers() {
JobTransfersListener<P, T, I> listener = new JobTransfersListener<>(this);
transferInputData(listener);
listener.enable();
}
private final void transferInputData(JobTransfersListener<P, T, I> listener) {
TaskDescription taskDescription = task.getTaskDescription();
for (Parameter p : taskDescription.getParameters()) {
JOB_LOGGER.debug(" * " + p);
if (p instanceof DependencyParameter) {
DependencyParameter dp = (DependencyParameter) p;
switch (taskDescription.getType()) {
case METHOD:
transferJobData(dp, listener);
break;
case SERVICE:
if (dp.getDirection() != Direction.INOUT) {
// For services we only transfer IN parameters because the only
// parameter that can be INOUT is the target
transferJobData(dp, listener);
}
break;
}
}
}
}
// Private method that performs data transfers
private final void transferJobData(DependencyParameter param, JobTransfersListener<P, T, I> listener) {
Worker<T, I> w = selectedResource.getResource();
DataAccessId access = param.getDataAccessId();
if (access instanceof DataAccessId.WAccessId) {
String tgtName = ((DataAccessId.WAccessId) access).getWrittenDataInstance().getRenaming();
if (DEBUG) {
JOB_LOGGER.debug("Setting data target job transfer: " + w.getCompleteRemotePath(param.getType(), tgtName));
}
param.setDataTarget(w.getCompleteRemotePath(param.getType(), tgtName).getPath());
return;
}
listener.addOperation();
if (access instanceof DataAccessId.RAccessId) {
String srcName = ((DataAccessId.RAccessId) access).getReadDataInstance().getRenaming();
w.getData(srcName, srcName, param, listener);
} else {
// Is RWAccess
String srcName = ((DataAccessId.RWAccessId) access).getReadDataInstance().getRenaming();
String tgtName = ((DataAccessId.RWAccessId) access).getWrittenDataInstance().getRenaming();
w.getData(srcName, tgtName, (LogicalData) null, param, listener);
}
}
/*
* ***************************************************************************************************************
* EXECUTED SUPPORTING THREAD ON JOB_TRANSFERS_LISTENER
* ***************************************************************************************************************
*/
/**
* Code executed after some input transfers have failed
*
* @param failedtransfers
*/
public final void failedTransfers(int failedtransfers) {
JOB_LOGGER.debug("Received a notification for the transfers for task " + task.getId() + " with state FAILED");
++transferErrors;
if (transferErrors < TRANSFER_CHANCES) {
JOB_LOGGER.debug("Resubmitting input files for task " + task.getId() + " to host " + selectedResource.getName() + " since "
+ failedtransfers + " transfers failed.");
doInputTransfers();
} else {
ErrorManager.warn("Transfers for running task " + task.getId() + " on worker " + selectedResource.getName() + " have failed.");
this.notifyError();
}
}
/**
* Code executed when all transfers have successed
*
* @param transferGroupId
*/
public final void doSubmit(int transferGroupId) {
JOB_LOGGER.debug("Received a notification for the transfers of task " + task.getId() + " with state DONE");
JobStatusListener<P, T, I> listener = new JobStatusListener<>(this);
Job<?> job = submitJob(transferGroupId, listener);
// Register job
jobs.add(job.getJobId());
JOB_LOGGER.info(
(this.executingResources.size() > 1 ? "Rescheduled" : "New") + " Job " + job.getJobId() + " (Task: " + task.getId() + ")");
JOB_LOGGER.info(" * Method name: " + task.getTaskDescription().getName());
JOB_LOGGER.info(" * Target host: " + selectedResource.getName());
profile.start();
JobDispatcher.dispatch(job);
}
protected Job<?> submitJob(int transferGroupId, JobStatusListener<P, T, I> listener) {
// Create job
if (DEBUG) {
LOGGER.debug(this.toString() + " starts job creation");
}
Worker<T, I> w = selectedResource.getResource();
List<String> slaveNames = new ArrayList<>(); // No salves
Job<?> job = w.newJob(this.task.getId(), this.task.getTaskDescription(), this.selectedImpl, slaveNames, listener);
job.setTransferGroupId(transferGroupId);
job.setHistory(Job.JobHistory.NEW);
return job;
}
/**
* Code executed when the job execution has failed
*
* @param job
* @param endStatus
*/
public final void failedJob(Job<?> job, JobEndStatus endStatus) {
profile.end();
int jobId = job.getJobId();
JOB_LOGGER.error("Received a notification for job " + jobId + " with state FAILED");
++executionErrors;
if (transferErrors + executionErrors < SUBMISSION_CHANCES) {
JOB_LOGGER.error("Job " + job.getJobId() + " for running task " + task.getId() + " on worker " + selectedResource.getName()
+ " has failed; resubmitting task to the same worker.");
ErrorManager.warn("Job " + job.getJobId() + " for running task " + task.getId() + " on worker " + selectedResource.getName()
+ " has failed; resubmitting task to the same worker.");
job.setHistory(Job.JobHistory.RESUBMITTED);
profile.start();
JobDispatcher.dispatch(job);
} else {
notifyError();
}
}
/**
* Code executed when the job execution has been completed
*
* @param job
*/
public final void completedJob(Job<?> job) {
// End profile
profile.end();
// Notify end
int jobId = job.getJobId();
JOB_LOGGER.info("Received a notification for job " + jobId + " with state OK");
// Job finished, update info about the generated/updated data
doOutputTransfers(job);
// Notify completion
notifyCompleted();
}
private final void doOutputTransfers(Job<?> job) {
// Job finished, update info about the generated/updated data
Worker<T, I> w = selectedResource.getResource();
for (Parameter p : job.getTaskParams().getParameters()) {
if (p instanceof DependencyParameter) {
// OUT or INOUT: we must tell the FTM about the
// generated/updated datum
DataInstanceId dId = null;
DependencyParameter dp = (DependencyParameter) p;
switch (p.getDirection()) {
case IN:
// FTM already knows about this datum
continue;
case OUT:
dId = ((DataAccessId.WAccessId) dp.getDataAccessId()).getWrittenDataInstance();
break;
case INOUT:
dId = ((DataAccessId.RWAccessId) dp.getDataAccessId()).getWrittenDataInstance();
if (job.getType() == TaskType.SERVICE) {
continue;
}
break;
}
String name = dId.getRenaming();
if (job.getType() == TaskType.METHOD) {
String targetProtocol = null;
switch (dp.getType()) {
case FILE_T:
targetProtocol = DataLocation.Protocol.FILE_URI.getSchema();
break;
case OBJECT_T:
targetProtocol = DataLocation.Protocol.OBJECT_URI.getSchema();
break;
case PSCO_T:
targetProtocol = DataLocation.Protocol.PERSISTENT_URI.getSchema();
break;
case EXTERNAL_PSCO_T:
// External PSCOs are treated as objects within the runtime
// Its value is the PSCO Id
targetProtocol = DataLocation.Protocol.OBJECT_URI.getSchema();
break;
default:
// Should never reach this point because only
// DependencyParameter types are treated
// Ask for any_uri just in case
targetProtocol = DataLocation.Protocol.ANY_URI.getSchema();
break;
}
DataLocation outLoc = null;
try {
SimpleURI targetURI = new SimpleURI(targetProtocol + dp.getDataTarget());
outLoc = DataLocation.createLocation(w, targetURI);
} catch (Exception e) {
ErrorManager.error(DataLocation.ERROR_INVALID_LOCATION + " " + dp.getDataTarget(), e);
}
Comm.registerLocation(name, outLoc);
} else {
// Service
Object value = job.getReturnValue();
Comm.registerValue(name, value);
}
}
}
}
/*
* ***************************************************************************************************************
* EXECUTION TRIGGERS
* ***************************************************************************************************************
*/
@Override
protected void doCompleted() {
// Profile the resource
selectedResource.profiledExecution(selectedImpl, profile);
// Decrease the execution counter and set the task as finished and notify the producer
task.decreaseExecutionCount();
task.setStatus(TaskState.FINISHED);
producer.notifyTaskEnd(task);
}
@Override
protected void doError() throws FailedActionException {
if (this.executingResources.size() >= SCHEDULING_CHANCES) {
LOGGER.warn("Task " + task.getId() + " has already been rescheduled; notifying task failure.");
ErrorManager.warn("Task " + task.getId() + " has already been rescheduled; notifying task failure.");
throw new FailedActionException();
} else {
ErrorManager.warn("Task " + task.getId() + " execution on worker " + selectedResource.getName()
+ " has failed; rescheduling task execution. (changing worker)");
LOGGER.warn("Task " + task.getId() + " execution on worker " + selectedResource.getName()
+ " has failed; rescheduling task execution. (changing worker)");
}
}
@Override
protected void doFailed() {
// Failed message
String taskName = task.getTaskDescription().getName();
StringBuilder sb = new StringBuilder();
sb.append("Task '").append(taskName).append("' TOTALLY FAILED.\n");
sb.append("Possible causes:\n");
sb.append(" -Exception thrown by task '").append(taskName).append("'.\n");
sb.append(" -Expected output files not generated by task '").append(taskName).append("'.\n");
sb.append(" -Could not provide nor retrieve needed data between master and worker.\n");
sb.append("\n");
sb.append("Check files '").append(Comm.getAppHost().getJobsDirPath()).append("job[");
Iterator<Integer> j = jobs.iterator();
while (j.hasNext()) {
sb.append(j.next());
if (!j.hasNext()) {
break;
}
sb.append("|");
}
sb.append("'] to find out the error.\n");
sb.append(" \n");
ErrorManager.warn(sb.toString());
// Notify task failure
task.decreaseExecutionCount();
task.setStatus(TaskState.FAILED);
producer.notifyTaskEnd(task);
}
/*
* ***************************************************************************************************************
* SCHEDULING MANAGEMENT
* ***************************************************************************************************************
*/
@Override
public final LinkedList<ResourceScheduler<P, T, I>> getCompatibleWorkers() {
return getCoreElementExecutors(task.getTaskDescription().getId());
}
@Override
public final LinkedList<I> getCompatibleImplementations(ResourceScheduler<P, T, I> r) {
return r.getExecutableImpls(task.getTaskDescription().getId());
}
@SuppressWarnings("unchecked")
@Override
public final I[] getImplementations() {
return (I[]) CoreManager.getCoreImplementations(task.getTaskDescription().getId());
}
@Override
public final boolean isCompatible(Worker<T, I> r) {
return r.canRun(task.getTaskDescription().getId());
}
@Override
public final Integer getCoreId() {
return task.getTaskDescription().getId();
}
@Override
public final int getPriority() {
return task.getTaskDescription().hasPriority() ? 1 : 0;
}
@Override
public final Score schedulingScore(ResourceScheduler<P, T, I> targetWorker, Score actionScore) {
Score computedScore = targetWorker.generateResourceScore(this, task.getTaskDescription(), actionScore);
// LOGGER.debug("Scheduling Score " + computedScore);
return computedScore;
}
@Override
public final void schedule(Score actionScore) throws BlockedActionException, UnassignedActionException {
//if (DEBUG) {
// LOGGER.debug("Scheduling " + this + ". Computing best worker and best implementation");
//}
StringBuilder debugString = new StringBuilder("Scheduling " + this + " execution:\n");
// COMPUTE RESOURCE CANDIDATES
LinkedList<ResourceScheduler<P, T, I>> candidates = new LinkedList<>();
if (this.forcedResource != null) {
// The scheduling is forced to a given resource
candidates.add(this.forcedResource);
} else if (isSchedulingConstrained()) {
// The scheduling is constrained by dependencies
for (AllocatableAction<P, T, I> a : this.getConstrainingPredecessors()) {
candidates.add(a.getAssignedResource());
}
} else {
// Free scheduling
candidates = getCompatibleWorkers();
}
// COMPUTE BEST WORKER AND IMPLEMENTATION
ResourceScheduler<P, T, I> bestWorker = null;
I bestImpl = null;
Score bestScore = null;
int usefulResources = 0;
for (ResourceScheduler<P, T, I> worker : candidates) {
if (executingResources.contains(worker)) {
if (DEBUG) {
LOGGER.debug("Task already running on worker " + worker.getName());
}
continue;
}
Score resourceScore = worker.generateResourceScore(this, task.getTaskDescription(), actionScore);
++usefulResources;
for (I impl : getCompatibleImplementations(worker)) {
Score implScore = worker.generateImplementationScore(this, task.getTaskDescription(), impl, resourceScore);
if (DEBUG) {
debugString.append(" Resource ").append(worker.getName()).append(" ").append(" Implementation ")
.append(impl.getImplementationId()).append(" ").append(" Score ").append(implScore).append("\n");
}
if (Score.isBetter(implScore, bestScore)) {
bestWorker = worker;
bestImpl = impl;
bestScore = implScore;
}
}
}
// CHECK SCHEDULING RESULT
if (DEBUG) {
LOGGER.debug(debugString.toString());
}
if (bestWorker == null && usefulResources == 0) {
LOGGER.warn("No worker can run " + this);
throw new BlockedActionException();
}
schedule(bestWorker, bestImpl);
}
@Override
public final void schedule(ResourceScheduler<P, T, I> targetWorker, Score actionScore)
throws BlockedActionException, UnassignedActionException {
//if (DEBUG) {
// LOGGER.debug("Scheduling " + this + " on worker " + targetWorker.getName() + ". Computing best implementation");
//}
if (targetWorker == null
// Resource is not compatible with the Core
|| !targetWorker.getResource().canRun(task.getTaskDescription().getId())
// already ran on the resource
|| executingResources.contains(targetWorker)) {
String message = "Worker " + (targetWorker == null ? "null" : targetWorker.getName()) + " has not available resources to run "
+ this;
LOGGER.warn(message);
throw new UnassignedActionException();
}
StringBuilder debugString = new StringBuilder("Scheduling " + this + " execution for worker " + targetWorker + ":\n");
if (DEBUG) {
debugString.append("\t Resource ").append(targetWorker.getName()).append("\n");
}
I bestImpl = null;
Score bestScore = null;
Score resourceScore = targetWorker.generateResourceScore(this, task.getTaskDescription(), actionScore);
for (I impl : getCompatibleImplementations(targetWorker)) {
Score implScore = targetWorker.generateImplementationScore(this, task.getTaskDescription(), impl, resourceScore);
if (DEBUG) {
debugString.append("\t\t Implementation ").append(impl.getImplementationId()).append(implScore).append("\n");
}
if (Score.isBetter(implScore, bestScore)) {
bestImpl = impl;
bestScore = implScore;
}
}
// CHECK SCHEDULING RESULT
if (DEBUG) {
LOGGER.debug(debugString.toString());
}
schedule(targetWorker, bestImpl);
}
@Override
public final void schedule(ResourceScheduler<P, T, I> targetWorker, I impl) throws BlockedActionException, UnassignedActionException {
if (targetWorker == null || impl == null) {
/*if (targetWorker == null && impl == null) {
LOGGER.debug("Not available resources to run " + this + " because both the target worker and the best implementation are null");
} else if (targetWorker == null) {
LOGGER.debug("Not available resources to run " + this + " because the target worker is null");
} else if (impl == null) {
LOGGER.debug("Not available resources to run " + this + " because the best implementation is null");
}*/
throw new UnassignedActionException();
}
//if (DEBUG) {
// LOGGER.debug(
// "Scheduling " + this + " on worker " + targetWorker.getName() + " with implementation " + impl.getImplementationId());
//}
if (// Resource is not compatible with the implementation
!targetWorker.getResource().canRun(impl)
// already ran on the resource
|| executingResources.contains(targetWorker)) {
LOGGER.debug("Worker " + targetWorker.getName() + " has not available resources to run " + this);
throw new UnassignedActionException();
}
LOGGER.info(
"Assigning action " + this + " to worker " + targetWorker.getName() + " with implementation " + impl.getImplementationId());
this.assignImplementation(impl);
this.assignResources(targetWorker);
targetWorker.scheduleAction(this);
}
/*
* ***************************************************************************************************************
* OTHER
* ***************************************************************************************************************
*/
@Override
public String toString() {
return "ExecutionAction ( Task " + task.getId() + ", CE name " + task.getTaskDescription().getName() + ")";
}
}
| compss/runtime/engine/src/main/java/integratedtoolkit/types/allocatableactions/ExecutionAction.java | package integratedtoolkit.types.allocatableactions;
import integratedtoolkit.comm.Comm;
import integratedtoolkit.components.impl.ResourceScheduler;
import integratedtoolkit.components.impl.TaskProducer;
import integratedtoolkit.log.Loggers;
import integratedtoolkit.types.Task;
import integratedtoolkit.types.TaskDescription;
import integratedtoolkit.types.Task.TaskState;
import integratedtoolkit.types.annotations.parameter.Direction;
import integratedtoolkit.scheduler.exceptions.BlockedActionException;
import integratedtoolkit.scheduler.exceptions.FailedActionException;
import integratedtoolkit.scheduler.exceptions.UnassignedActionException;
import integratedtoolkit.scheduler.types.ActionOrchestrator;
import integratedtoolkit.scheduler.types.AllocatableAction;
import integratedtoolkit.scheduler.types.Profile;
import integratedtoolkit.scheduler.types.SchedulingInformation;
import integratedtoolkit.scheduler.types.Score;
import integratedtoolkit.types.data.DataAccessId;
import integratedtoolkit.types.data.DataInstanceId;
import integratedtoolkit.types.data.LogicalData;
import integratedtoolkit.types.data.location.DataLocation;
import integratedtoolkit.types.data.operation.JobTransfersListener;
import integratedtoolkit.types.implementations.Implementation;
import integratedtoolkit.types.implementations.Implementation.TaskType;
import integratedtoolkit.types.job.Job;
import integratedtoolkit.types.job.JobListener.JobEndStatus;
import integratedtoolkit.types.parameter.DependencyParameter;
import integratedtoolkit.types.parameter.Parameter;
import integratedtoolkit.types.job.JobStatusListener;
import integratedtoolkit.types.resources.Worker;
import integratedtoolkit.types.resources.WorkerResourceDescription;
import integratedtoolkit.types.uri.SimpleURI;
import integratedtoolkit.util.CoreManager;
import integratedtoolkit.util.ErrorManager;
import integratedtoolkit.util.JobDispatcher;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class ExecutionAction<P extends Profile, T extends WorkerResourceDescription, I extends Implementation<T>>
extends AllocatableAction<P, T, I> {
// Fault tolerance parameters
private static final int TRANSFER_CHANCES = 2;
private static final int SUBMISSION_CHANCES = 2;
private static final int SCHEDULING_CHANCES = 2;
// LOGGER
private static final Logger JOB_LOGGER = LogManager.getLogger(Loggers.JM_COMP);
// Execution Info
protected final TaskProducer producer;
protected final Task task;
private final LinkedList<Integer> jobs;
private int transferErrors = 0;
protected int executionErrors = 0;
// Resource execution information
private final ResourceScheduler<P, T, I> forcedResource;
private T resourceConsumption;
/**
* Creates a new execution action
*
* @param schedulingInformation
* @param producer
* @param task
* @param forcedResource
*/
@SuppressWarnings("unchecked")
public ExecutionAction(SchedulingInformation<P, T, I> schedulingInformation, ActionOrchestrator<P, T, I> orchestrator,
TaskProducer producer, Task task, ResourceScheduler<P, T, I> forcedResource) {
super(schedulingInformation, orchestrator);
this.producer = producer;
this.task = task;
this.jobs = new LinkedList<>();
this.transferErrors = 0;
this.executionErrors = 0;
this.forcedResource = forcedResource;
this.resourceConsumption = null;
// Add execution to task
this.task.addExecution(this);
// Register data dependencies events
for (Task predecessor : this.task.getPredecessors()) {
for (ExecutionAction<?, ?, ?> e : predecessor.getExecutions()) {
if (e != null && e.isPending()) {
addDataPredecessor((ExecutionAction<P, T, I>) e);
}
}
}
// Scheduling constraints
// Restricted resource
Task resourceConstraintTask = this.task.getEnforcingTask();
if (resourceConstraintTask != null) {
for (ExecutionAction<?, ?, ?> e : resourceConstraintTask.getExecutions()) {
addResourceConstraint((ExecutionAction<P, T, I>) e);
}
}
}
/**
* Returns the associated task
*
* @return
*/
public final Task getTask() {
return this.task;
}
/*
* ***************************************************************************************************************
* EXECUTION AND LIFECYCLE MANAGEMENT
* ***************************************************************************************************************
*/
@Override
public final boolean areEnoughResources() {
Worker<T, I> w = selectedResource.getResource();
return w.canRunNow(selectedImpl.getRequirements());
}
@Override
protected final void reserveResources() {
Worker<T, I> w = selectedResource.getResource();
resourceConsumption = w.runTask(selectedImpl.getRequirements());
}
@Override
protected final void releaseResources() {
Worker<T, I> w = selectedResource.getResource();
w.endTask(resourceConsumption);
}
@Override
protected void doAction() {
JOB_LOGGER.info("Ordering transfers to " + selectedResource + " to run task: " + task.getId());
transferErrors = 0;
executionErrors = 0;
doInputTransfers();
}
private final void doInputTransfers() {
JobTransfersListener<P, T, I> listener = new JobTransfersListener<>(this);
transferInputData(listener);
listener.enable();
}
private final void transferInputData(JobTransfersListener<P, T, I> listener) {
TaskDescription taskDescription = task.getTaskDescription();
for (Parameter p : taskDescription.getParameters()) {
JOB_LOGGER.debug(" * " + p);
if (p instanceof DependencyParameter) {
DependencyParameter dp = (DependencyParameter) p;
switch (taskDescription.getType()) {
case METHOD:
transferJobData(dp, listener);
break;
case SERVICE:
if (dp.getDirection() != Direction.INOUT) {
// For services we only transfer IN parameters because the only
// parameter that can be INOUT is the target
transferJobData(dp, listener);
}
break;
}
}
}
}
// Private method that performs data transfers
private final void transferJobData(DependencyParameter param, JobTransfersListener<P, T, I> listener) {
Worker<T, I> w = selectedResource.getResource();
DataAccessId access = param.getDataAccessId();
if (access instanceof DataAccessId.WAccessId) {
String tgtName = ((DataAccessId.WAccessId) access).getWrittenDataInstance().getRenaming();
if (DEBUG) {
JOB_LOGGER.debug("Setting data target job transfer: " + w.getCompleteRemotePath(param.getType(), tgtName));
}
param.setDataTarget(w.getCompleteRemotePath(param.getType(), tgtName).getPath());
return;
}
listener.addOperation();
if (access instanceof DataAccessId.RAccessId) {
String srcName = ((DataAccessId.RAccessId) access).getReadDataInstance().getRenaming();
w.getData(srcName, srcName, param, listener);
} else {
// Is RWAccess
String srcName = ((DataAccessId.RWAccessId) access).getReadDataInstance().getRenaming();
String tgtName = ((DataAccessId.RWAccessId) access).getWrittenDataInstance().getRenaming();
w.getData(srcName, tgtName, (LogicalData) null, param, listener);
}
}
/*
* ***************************************************************************************************************
* EXECUTED SUPPORTING THREAD ON JOB_TRANSFERS_LISTENER
* ***************************************************************************************************************
*/
/**
* Code executed after some input transfers have failed
*
* @param failedtransfers
*/
public final void failedTransfers(int failedtransfers) {
JOB_LOGGER.debug("Received a notification for the transfers for task " + task.getId() + " with state FAILED");
++transferErrors;
if (transferErrors < TRANSFER_CHANCES) {
JOB_LOGGER.debug("Resubmitting input files for task " + task.getId() + " to host " + selectedResource.getName() + " since "
+ failedtransfers + " transfers failed.");
doInputTransfers();
} else {
ErrorManager.warn("Transfers for running task " + task.getId() + " on worker " + selectedResource.getName() + " have failed.");
this.notifyError();
}
}
/**
* Code executed when all transfers have successed
*
* @param transferGroupId
*/
public final void doSubmit(int transferGroupId) {
JOB_LOGGER.debug("Received a notification for the transfers of task " + task.getId() + " with state DONE");
JobStatusListener<P, T, I> listener = new JobStatusListener<>(this);
Job<?> job = submitJob(transferGroupId, listener);
// Register job
jobs.add(job.getJobId());
JOB_LOGGER.info(
(this.executingResources.size() > 1 ? "Rescheduled" : "New") + " Job " + job.getJobId() + " (Task: " + task.getId() + ")");
JOB_LOGGER.info(" * Method name: " + task.getTaskDescription().getName());
JOB_LOGGER.info(" * Target host: " + selectedResource.getName());
profile.start();
JobDispatcher.dispatch(job);
}
protected Job<?> submitJob(int transferGroupId, JobStatusListener<P, T, I> listener) {
// Create job
if (DEBUG) {
LOGGER.debug(this.toString() + " starts job creation");
}
Worker<T, I> w = selectedResource.getResource();
List<String> slaveNames = new ArrayList<>(); // No salves
Job<?> job = w.newJob(this.task.getId(), this.task.getTaskDescription(), this.selectedImpl, slaveNames, listener);
job.setTransferGroupId(transferGroupId);
job.setHistory(Job.JobHistory.NEW);
return job;
}
/**
* Code executed when the job execution has failed
*
* @param job
* @param endStatus
*/
public final void failedJob(Job<?> job, JobEndStatus endStatus) {
profile.end();
int jobId = job.getJobId();
JOB_LOGGER.error("Received a notification for job " + jobId + " with state FAILED");
++executionErrors;
if (transferErrors + executionErrors < SUBMISSION_CHANCES) {
JOB_LOGGER.error("Job " + job.getJobId() + " for running task " + task.getId() + " on worker " + selectedResource.getName()
+ " has failed; resubmitting task to the same worker.");
ErrorManager.warn("Job " + job.getJobId() + " for running task " + task.getId() + " on worker " + selectedResource.getName()
+ " has failed; resubmitting task to the same worker.");
job.setHistory(Job.JobHistory.RESUBMITTED);
profile.start();
JobDispatcher.dispatch(job);
} else {
notifyError();
}
}
/**
* Code executed when the job execution has been completed
*
* @param job
*/
public final void completedJob(Job<?> job) {
// End profile
profile.end();
// Notify end
int jobId = job.getJobId();
JOB_LOGGER.info("Received a notification for job " + jobId + " with state OK");
// Job finished, update info about the generated/updated data
doOutputTransfers(job);
// Notify completion
notifyCompleted();
}
private final void doOutputTransfers(Job<?> job) {
// Job finished, update info about the generated/updated data
Worker<T, I> w = selectedResource.getResource();
for (Parameter p : job.getTaskParams().getParameters()) {
if (p instanceof DependencyParameter) {
// OUT or INOUT: we must tell the FTM about the
// generated/updated datum
DataInstanceId dId = null;
DependencyParameter dp = (DependencyParameter) p;
switch (p.getDirection()) {
case IN:
// FTM already knows about this datum
continue;
case OUT:
dId = ((DataAccessId.WAccessId) dp.getDataAccessId()).getWrittenDataInstance();
break;
case INOUT:
dId = ((DataAccessId.RWAccessId) dp.getDataAccessId()).getWrittenDataInstance();
if (job.getType() == TaskType.SERVICE) {
continue;
}
break;
}
String name = dId.getRenaming();
if (job.getType() == TaskType.METHOD) {
String targetProtocol = null;
switch (dp.getType()) {
case FILE_T:
targetProtocol = DataLocation.Protocol.FILE_URI.getSchema();
break;
case OBJECT_T:
targetProtocol = DataLocation.Protocol.OBJECT_URI.getSchema();
break;
case PSCO_T:
targetProtocol = DataLocation.Protocol.PERSISTENT_URI.getSchema();
break;
case EXTERNAL_PSCO_T:
// External PSCOs are treated as objects within the runtime
// Its value is the PSCO Id
targetProtocol = DataLocation.Protocol.OBJECT_URI.getSchema();
break;
default:
// Should never reach this point because only
// DependencyParameter types are treated
// Ask for any_uri just in case
targetProtocol = DataLocation.Protocol.ANY_URI.getSchema();
break;
}
DataLocation outLoc = null;
try {
SimpleURI targetURI = new SimpleURI(targetProtocol + dp.getDataTarget());
outLoc = DataLocation.createLocation(w, targetURI);
} catch (Exception e) {
ErrorManager.error(DataLocation.ERROR_INVALID_LOCATION + " " + dp.getDataTarget(), e);
}
Comm.registerLocation(name, outLoc);
} else {
// Service
Object value = job.getReturnValue();
Comm.registerValue(name, value);
}
}
}
}
/*
* ***************************************************************************************************************
* EXECUTION TRIGGERS
* ***************************************************************************************************************
*/
@Override
protected void doCompleted() {
// Profile the resource
selectedResource.profiledExecution(selectedImpl, profile);
// Decrease the execution counter and set the task as finished and notify the producer
task.decreaseExecutionCount();
task.setStatus(TaskState.FINISHED);
producer.notifyTaskEnd(task);
}
@Override
protected void doError() throws FailedActionException {
if (this.executingResources.size() >= SCHEDULING_CHANCES) {
LOGGER.warn("Task " + task.getId() + " has already been rescheduled; notifying task failure.");
ErrorManager.warn("Task " + task.getId() + " has already been rescheduled; notifying task failure.");
throw new FailedActionException();
} else {
ErrorManager.warn("Task " + task.getId() + " execution on worker " + selectedResource.getName()
+ " has failed; rescheduling task execution. (changing worker)");
LOGGER.warn("Task " + task.getId() + " execution on worker " + selectedResource.getName()
+ " has failed; rescheduling task execution. (changing worker)");
}
}
@Override
protected void doFailed() {
// Failed message
String taskName = task.getTaskDescription().getName();
StringBuilder sb = new StringBuilder();
sb.append("Task '").append(taskName).append("' TOTALLY FAILED.\n");
sb.append("Possible causes:\n");
sb.append(" -Exception thrown by task '").append(taskName).append("'.\n");
sb.append(" -Expected output files not generated by task '").append(taskName).append("'.\n");
sb.append(" -Could not provide nor retrieve needed data between master and worker.\n");
sb.append("\n");
sb.append("Check files '").append(Comm.getAppHost().getJobsDirPath()).append("job[");
Iterator<Integer> j = jobs.iterator();
while (j.hasNext()) {
sb.append(j.next());
if (!j.hasNext()) {
break;
}
sb.append("|");
}
sb.append("'] to find out the error.\n");
sb.append(" \n");
ErrorManager.warn(sb.toString());
// Notify task failure
task.decreaseExecutionCount();
task.setStatus(TaskState.FAILED);
producer.notifyTaskEnd(task);
}
/*
* ***************************************************************************************************************
* SCHEDULING MANAGEMENT
* ***************************************************************************************************************
*/
@Override
public final LinkedList<ResourceScheduler<P, T, I>> getCompatibleWorkers() {
return getCoreElementExecutors(task.getTaskDescription().getId());
}
@Override
public final LinkedList<I> getCompatibleImplementations(ResourceScheduler<P, T, I> r) {
return r.getExecutableImpls(task.getTaskDescription().getId());
}
@SuppressWarnings("unchecked")
@Override
public final I[] getImplementations() {
return (I[]) CoreManager.getCoreImplementations(task.getTaskDescription().getId());
}
@Override
public final boolean isCompatible(Worker<T, I> r) {
return r.canRun(task.getTaskDescription().getId());
}
@Override
public final Integer getCoreId() {
return task.getTaskDescription().getId();
}
@Override
public final int getPriority() {
return task.getTaskDescription().hasPriority() ? 1 : 0;
}
@Override
public final Score schedulingScore(ResourceScheduler<P, T, I> targetWorker, Score actionScore) {
Score computedScore = targetWorker.generateResourceScore(this, task.getTaskDescription(), actionScore);
LOGGER.debug("Scheduling Score " + computedScore);
return computedScore;
}
@Override
public final void schedule(Score actionScore) throws BlockedActionException, UnassignedActionException {
if (DEBUG) {
LOGGER.debug("Scheduling " + this + ". Computing best worker and best implementation");
}
StringBuilder debugString = new StringBuilder("Scheduling " + this + " execution:\n");
// COMPUTE RESOURCE CANDIDATES
LinkedList<ResourceScheduler<P, T, I>> candidates = new LinkedList<>();
if (this.forcedResource != null) {
// The scheduling is forced to a given resource
candidates.add(this.forcedResource);
} else if (isSchedulingConstrained()) {
// The scheduling is constrained by dependencies
for (AllocatableAction<P, T, I> a : this.getConstrainingPredecessors()) {
candidates.add(a.getAssignedResource());
}
} else {
// Free scheduling
candidates = getCompatibleWorkers();
}
// COMPUTE BEST WORKER AND IMPLEMENTATION
ResourceScheduler<P, T, I> bestWorker = null;
I bestImpl = null;
Score bestScore = null;
int usefulResources = 0;
for (ResourceScheduler<P, T, I> worker : candidates) {
if (executingResources.contains(worker)) {
if (DEBUG) {
LOGGER.debug("Task already running on worker " + worker.getName());
}
continue;
}
Score resourceScore = worker.generateResourceScore(this, task.getTaskDescription(), actionScore);
++usefulResources;
for (I impl : getCompatibleImplementations(worker)) {
Score implScore = worker.generateImplementationScore(this, task.getTaskDescription(), impl, resourceScore);
if (DEBUG) {
debugString.append(" Resource ").append(worker.getName()).append(" ").append(" Implementation ")
.append(impl.getImplementationId()).append(" ").append(" Score ").append(implScore).append("\n");
}
if (Score.isBetter(implScore, bestScore)) {
bestWorker = worker;
bestImpl = impl;
bestScore = implScore;
}
}
}
// CHECK SCHEDULING RESULT
if (DEBUG) {
LOGGER.debug(debugString.toString());
}
if (bestWorker == null && usefulResources == 0) {
LOGGER.warn("No worker can run " + this);
throw new BlockedActionException();
}
schedule(bestWorker, bestImpl);
}
@Override
public final void schedule(ResourceScheduler<P, T, I> targetWorker, Score actionScore)
throws BlockedActionException, UnassignedActionException {
if (DEBUG) {
LOGGER.debug("Scheduling " + this + " on worker " + targetWorker.getName() + ". Computing best implementation");
}
if (targetWorker == null
// Resource is not compatible with the Core
|| !targetWorker.getResource().canRun(task.getTaskDescription().getId())
// already ran on the resource
|| executingResources.contains(targetWorker)) {
String message = "Worker " + (targetWorker == null ? "null" : targetWorker.getName()) + " has not available resources to run "
+ this;
LOGGER.warn(message);
throw new UnassignedActionException();
}
StringBuilder debugString = new StringBuilder("Scheduling " + this + " execution for worker " + targetWorker + ":\n");
if (DEBUG) {
debugString.append("\t Resource ").append(targetWorker.getName()).append("\n");
}
I bestImpl = null;
Score bestScore = null;
Score resourceScore = targetWorker.generateResourceScore(this, task.getTaskDescription(), actionScore);
for (I impl : getCompatibleImplementations(targetWorker)) {
Score implScore = targetWorker.generateImplementationScore(this, task.getTaskDescription(), impl, resourceScore);
if (DEBUG) {
debugString.append("\t\t Implementation ").append(impl.getImplementationId()).append(implScore).append("\n");
}
if (Score.isBetter(implScore, bestScore)) {
bestImpl = impl;
bestScore = implScore;
}
}
// CHECK SCHEDULING RESULT
if (DEBUG) {
LOGGER.debug(debugString.toString());
}
schedule(targetWorker, bestImpl);
}
@Override
public final void schedule(ResourceScheduler<P, T, I> targetWorker, I impl) throws BlockedActionException, UnassignedActionException {
if (targetWorker == null || impl == null) {
/*if (targetWorker == null && impl == null) {
LOGGER.debug("Not available resources to run " + this + " because both the target worker and the best implementation are null");
} else if (targetWorker == null) {
LOGGER.debug("Not available resources to run " + this + " because the target worker is null");
} else if (impl == null) {
LOGGER.debug("Not available resources to run " + this + " because the best implementation is null");
}*/
throw new UnassignedActionException();
}
if (DEBUG) {
LOGGER.debug(
"Scheduling " + this + " on worker " + targetWorker.getName() + " with implementation " + impl.getImplementationId());
}
if (// Resource is not compatible with the implementation
!targetWorker.getResource().canRun(impl)
// already ran on the resource
|| executingResources.contains(targetWorker)) {
LOGGER.debug("Worker " + targetWorker.getName() + " has not available resources to run " + this);
throw new UnassignedActionException();
}
LOGGER.info(
"Assigning action " + this + " to worker " + targetWorker.getName() + " with implementation " + impl.getImplementationId());
this.assignImplementation(impl);
this.assignResources(targetWorker);
targetWorker.scheduleAction(this);
}
/*
* ***************************************************************************************************************
* OTHER
* ***************************************************************************************************************
*/
@Override
public String toString() {
return "ExecutionAction ( Task " + task.getId() + ", CE name " + task.getTaskDescription().getName() + ")";
}
}
| Scheduling logs commented
git-svn-id: http://compss.bsc.es/svn/compss/framework/trunk@2982 9ab3861e-6c05-4e1b-b5ef-99af60850597
Former-commit-id: 8d95bfca186573995fde295d18905101e133ce67 | compss/runtime/engine/src/main/java/integratedtoolkit/types/allocatableactions/ExecutionAction.java | Scheduling logs commented | <ide><path>ompss/runtime/engine/src/main/java/integratedtoolkit/types/allocatableactions/ExecutionAction.java
<ide> @Override
<ide> public final Score schedulingScore(ResourceScheduler<P, T, I> targetWorker, Score actionScore) {
<ide> Score computedScore = targetWorker.generateResourceScore(this, task.getTaskDescription(), actionScore);
<del> LOGGER.debug("Scheduling Score " + computedScore);
<add> // LOGGER.debug("Scheduling Score " + computedScore);
<ide> return computedScore;
<ide> }
<ide>
<ide> @Override
<ide> public final void schedule(Score actionScore) throws BlockedActionException, UnassignedActionException {
<del> if (DEBUG) {
<del> LOGGER.debug("Scheduling " + this + ". Computing best worker and best implementation");
<del> }
<add> //if (DEBUG) {
<add> // LOGGER.debug("Scheduling " + this + ". Computing best worker and best implementation");
<add> //}
<ide> StringBuilder debugString = new StringBuilder("Scheduling " + this + " execution:\n");
<ide>
<ide> // COMPUTE RESOURCE CANDIDATES
<ide> public final void schedule(ResourceScheduler<P, T, I> targetWorker, Score actionScore)
<ide> throws BlockedActionException, UnassignedActionException {
<ide>
<del> if (DEBUG) {
<del> LOGGER.debug("Scheduling " + this + " on worker " + targetWorker.getName() + ". Computing best implementation");
<del> }
<add> //if (DEBUG) {
<add> // LOGGER.debug("Scheduling " + this + " on worker " + targetWorker.getName() + ". Computing best implementation");
<add> //}
<ide>
<ide> if (targetWorker == null
<ide> // Resource is not compatible with the Core
<ide> throw new UnassignedActionException();
<ide> }
<ide>
<del> if (DEBUG) {
<del> LOGGER.debug(
<del> "Scheduling " + this + " on worker " + targetWorker.getName() + " with implementation " + impl.getImplementationId());
<del> }
<add> //if (DEBUG) {
<add> // LOGGER.debug(
<add> // "Scheduling " + this + " on worker " + targetWorker.getName() + " with implementation " + impl.getImplementationId());
<add> //}
<ide>
<ide> if (// Resource is not compatible with the implementation
<ide> !targetWorker.getResource().canRun(impl) |
|
Java | apache-2.0 | 626a9daecf884d0a925724612e8a41fffc167316 | 0 | vergilchiu/hive,alanfgates/hive,nishantmonu51/hive,b-slim/hive,jcamachor/hive,alanfgates/hive,jcamachor/hive,b-slim/hive,vergilchiu/hive,jcamachor/hive,sankarh/hive,anishek/hive,alanfgates/hive,b-slim/hive,jcamachor/hive,jcamachor/hive,vergilchiu/hive,vineetgarg02/hive,jcamachor/hive,alanfgates/hive,lirui-apache/hive,sankarh/hive,sankarh/hive,lirui-apache/hive,lirui-apache/hive,sankarh/hive,anishek/hive,b-slim/hive,lirui-apache/hive,alanfgates/hive,sankarh/hive,vineetgarg02/hive,anishek/hive,nishantmonu51/hive,alanfgates/hive,vineetgarg02/hive,lirui-apache/hive,sankarh/hive,vineetgarg02/hive,anishek/hive,anishek/hive,vergilchiu/hive,nishantmonu51/hive,vergilchiu/hive,sankarh/hive,vineetgarg02/hive,vineetgarg02/hive,vergilchiu/hive,b-slim/hive,nishantmonu51/hive,nishantmonu51/hive,b-slim/hive,nishantmonu51/hive,jcamachor/hive,sankarh/hive,alanfgates/hive,b-slim/hive,lirui-apache/hive,nishantmonu51/hive,vineetgarg02/hive,anishek/hive,anishek/hive,jcamachor/hive,b-slim/hive,vineetgarg02/hive,vineetgarg02/hive,vergilchiu/hive,lirui-apache/hive,anishek/hive,anishek/hive,vergilchiu/hive,nishantmonu51/hive,lirui-apache/hive,jcamachor/hive,b-slim/hive,alanfgates/hive,vergilchiu/hive,alanfgates/hive,sankarh/hive,lirui-apache/hive,nishantmonu51/hive | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hive.ql.exec;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfo;
/**
* The default UDAF Method resolver. This resolver is used for resolving the
* UDAF methods are used for partial and final evaluation given the list of the
* argument types. The getEvalMethod goes through all the evaluate methods and
* returns the one that matches the argument signature or is the closest match.
* Closest match is defined as the one that requires the least number of
* arguments to be converted. In case more than one matches are found, the
* method throws an ambiguous method exception.
*/
public class DefaultUDAFEvaluatorResolver implements UDAFEvaluatorResolver {
/**
* The class of the UDAF.
*/
private final Class<? extends UDAF> udafClass;
/**
* Constructor. This constructor sets the resolver to be used for comparison
* operators. See {@link UDAFEvaluatorResolver}
*/
public DefaultUDAFEvaluatorResolver(Class<? extends UDAF> udafClass) {
this.udafClass = udafClass;
}
/**
* Gets the evaluator class for the UDAF given the parameter types.
*
* @param argClasses
* The list of the parameter types.
*/
public Class<? extends UDAFEvaluator> getEvaluatorClass(
List<TypeInfo> argClasses) throws UDFArgumentException {
ArrayList<Class<? extends UDAFEvaluator>> classList =
new ArrayList<Class<? extends UDAFEvaluator>>();
// Add all the public member classes that implement an evaluator
for (Class<?> enclClass : udafClass.getClasses()) {
if (UDAFEvaluator.class.isAssignableFrom(enclClass)) {
classList.add((Class<? extends UDAFEvaluator>) enclClass);
}
}
// Next we locate all the iterate methods for each of these classes.
ArrayList<Method> mList = new ArrayList<Method>();
ArrayList<Class<? extends UDAFEvaluator>> cList =
new ArrayList<Class<? extends UDAFEvaluator>>();
for (Class<? extends UDAFEvaluator> evaluator : classList) {
for (Method m : evaluator.getMethods()) {
if (m.getName().equalsIgnoreCase("iterate")) {
mList.add(m);
cList.add(evaluator);
}
}
}
Method m = FunctionRegistry.getMethodInternal(udafClass, mList, false, argClasses);
// Find the class that has this method.
// Note that Method.getDeclaringClass() may not work here because the method
// can be inherited from a base class.
int found = -1;
for (int i = 0; i < mList.size(); i++) {
if (mList.get(i) == m) {
if (found == -1) {
found = i;
} else {
throw new AmbiguousMethodException(udafClass, argClasses, mList);
}
}
}
assert (found != -1);
return cList.get(found);
}
}
| ql/src/java/org/apache/hadoop/hive/ql/exec/DefaultUDAFEvaluatorResolver.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hive.ql.exec;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfo;
/**
* The default UDAF Method resolver. This resolver is used for resolving the
* UDAF methods are used for partial and final evaluation given the list of the
* argument types. The getEvalMethod goes through all the evaluate methods and
* returns the one that matches the argument signature or is the closest match.
* Closest match is defined as the one that requires the least number of
* arguments to be converted. In case more than one matches are found, the
* method throws an ambiguous method exception.
*/
public class DefaultUDAFEvaluatorResolver implements UDAFEvaluatorResolver {
/**
* The class of the UDAF.
*/
private final Class<? extends UDAF> udafClass;
/**
* Constructor. This constructor sets the resolver to be used for comparison
* operators. See {@link UDAFEvaluatorResolver}
*/
public DefaultUDAFEvaluatorResolver(Class<? extends UDAF> udafClass) {
this.udafClass = udafClass;
}
/**
* Gets the evaluator class for the UDAF given the parameter types.
*
* @param argClasses
* The list of the parameter types.
*/
public Class<? extends UDAFEvaluator> getEvaluatorClass(
List<TypeInfo> argClasses) throws UDFArgumentException {
ArrayList<Class<? extends UDAFEvaluator>> classList =
new ArrayList<Class<? extends UDAFEvaluator>>();
// Add all the public member classes that implement an evaluator
for (Class<?> enclClass : udafClass.getClasses()) {
if (UDAFEvaluator.class.isAssignableFrom(enclClass)) {
classList.add((Class<? extends UDAFEvaluator>) enclClass);
}
}
// Next we locate all the iterate methods for each of these classes.
ArrayList<Method> mList = new ArrayList<Method>();
ArrayList<Class<? extends UDAFEvaluator>> cList =
new ArrayList<Class<? extends UDAFEvaluator>>();
for (Class<? extends UDAFEvaluator> evaluator : classList) {
for (Method m : evaluator.getMethods()) {
if (m.getName().equalsIgnoreCase("iterate")) {
mList.add(m);
cList.add(evaluator);
}
}
}
Method m = FunctionRegistry.getMethodInternal(udafClass, mList, false, argClasses);
// Find the class that has this method.
// Note that Method.getDeclaringClass() may not work here because the method
// can be inherited from a base class.
int found = -1;
for (int i = 0; i < mList.size(); i++) {
if (mList.get(i) == m) {
if (found == -1) {
found = i;
} else {
throw new AmbiguousMethodException(udafClass, null, null);
}
}
}
assert (found != -1);
return cList.get(found);
}
}
| HIVE-9936: fix potential NPE in DefaultUDAFEvaluatorResolver (Alexander Pivovarov via Jason Dere)
git-svn-id: c2303eb81cb646bce052f55f7f0d14f181a5956c@1667082 13f79535-47bb-0310-9956-ffa450edef68
| ql/src/java/org/apache/hadoop/hive/ql/exec/DefaultUDAFEvaluatorResolver.java | HIVE-9936: fix potential NPE in DefaultUDAFEvaluatorResolver (Alexander Pivovarov via Jason Dere) | <ide><path>l/src/java/org/apache/hadoop/hive/ql/exec/DefaultUDAFEvaluatorResolver.java
<ide>
<ide> import java.lang.reflect.Method;
<ide> import java.util.ArrayList;
<del>import java.util.Arrays;
<ide> import java.util.List;
<ide>
<ide> import org.apache.hadoop.hive.serde2.typeinfo.TypeInfo;
<ide> if (found == -1) {
<ide> found = i;
<ide> } else {
<del> throw new AmbiguousMethodException(udafClass, null, null);
<add> throw new AmbiguousMethodException(udafClass, argClasses, mList);
<ide> }
<ide> }
<ide> }
<ide> assert (found != -1);
<del>
<add>
<ide> return cList.get(found);
<ide> }
<ide> |
|
JavaScript | mit | d861f059afe6f737403210e008248385b45faf46 | 0 | pyrolabs/PyroLibrary | /* Pyro for Firebase*/
// Pyro Platform Firebase:
var pyroRef = new Firebase('http://pyro.firebaseio.com');
// Constructor:
function Pyro (argPyroData, errorCb) {
//Check for existance of Firebase
if(typeof Firebase != 'undefined' && typeof argPyroData != 'undefined') {
if(argPyroData.hasOwnProperty('url')){
// [TODO] Check that url is firebase
this.url = argPyroData.url;
this.mainRef = new Firebase(argPyroData.url);
this.pyroRef = pyroRef;
// Not Required variables
if(argPyroData.hasOwnProperty('secret')) {
this.secret = argPyroData.secret;
}
if(argPyroData.hasOwnProperty('name')) {
this.name = argPyroData.name;
} else {
//Regex name from url
// this.name =
}
} else {
console.error('Missing firebase url.');
if(errorCb) {
errorCb({message:'Please provide your when running new Pyro() firebase URL'});
}
}
return this;
} else if(typeof argPyroData == 'undefined') {
console.error('New pyro object does not include nessesary information.');
}
else throw Error('Firebase library does not exist. Check that firebase.js is included in your index.html file.');
//for incorrect scope
// if (window === this) {
// return new _(id);
// }
}
Pyro.prototype = {
userSignup: function(argSignupData, successCb, errorCb) {
var self = this;
emailSignup(argSignupData, self, successCb, errorCb);
},
authAnonymously: function(){
//check for auth info
var auth = this.mainRef.getAuth();
console.log('authAnonymously', auth);
var currentThis = this;
if(auth != null) {
this.mainRef.authAnonymously(function(error, authData){
if (error) {
console.log('Login Failed!', error);
} else {
console.log('Authenticated successfully with payload:', authData);
var anon = {uid: authData.uid, provider:authData.provider};
currentThis.mainRef.child('users').child(authData.uid).set(anon);
}
});
} else {
//auth exists
}
},
login: function(argLoginData, successCb, errorCb) {
console.log('Pyro login:', arguments);
var self = this;
// check for existnace of main ref
authWithPassword(argLoginData, self.mainRef, successCb, errorCb);
},
logout:function(callback){
this.mainRef.unauth();
if(callback){
callback();
}
},
getAuth: function() {
console.log('getAuth called');
var authData = this.mainRef.getAuth();
if (authData) {
return authData;
} else {
console.warn('Not Authenticated');
return null;
}
},
getListByAuthor: function(argListName, callback) {
var auth = this.getAuth();
if(auth != null) {
this.mainRef.child(argListName).orderByChild('author').equalTo(auth.uid).on('value', function(listSnap){
callback(listSnap.val());
});
} else {
console.warn('listByAuthor cannot load list without current user');
}
},
createObject: function(argListName, argObject, callback) {
var auth = this.getAuth();
if(auth) {
argObject.author = auth.uid;
}
var newObj = this.mainRef.child(argListName).push(argObject, function(){
callback(newObj);
});
},
getUser: function(callback) {
if (this.getAuth() != null) {
var self = this;
userById(this.getAuth().uid, self.mainRef.child('users'), function(returnedAccount){
callback(returnedAccount);
});
} else {
callback(null);
}
},
loadObject:function(argListName, argObjectId, callback){
var listRef = this.mainRef.child(argListName);
listRef.child(argObjectId).on('value', function(objectSnap){
callback(objectSnap.val());
});
},
instanceRef: function(argInstanceData, successCb, errorCb) {
console.log('loadInstance:', argInstanceData);
this.currentInstance = {name:argInstanceData.name}
checkForInstance(this, successCb, errorCb);
},
getObjectCount: function(argListName, callback){
var self = this;
this.mainRef.child(argListName).on('value', function(usersListSnap){
callback(usersListSnap.numChildren());
});
},
getUserCount: function(callback){
var self = this;
this.mainRef.child('users').on('value', function(usersListSnap){
callback(usersListSnap.numChildren());
});
},
getUserList: function(callback){
this.mainRef.child('users').on('value', function(usersListSnap){
callback(usersListSnap.val());
});
},
createInstance: function (argPyroData, successCb, errorCb) {
var self = this;
if(argPyroData.hasOwnProperty('name') && argPyroData.hasOwnProperty('secret')){
// [TODO] Check that url is firebase
this.mainRef = new Firebase(self.url);
checkForInstance(this, function(returnedInstance){
successCb(returnedInstance);
});
//request admin auth token
// var xmlhttp = new XMLHttpRequest();
// xmlhttp.open("POST", "http://pyro-server.herokuapp.com/auth");
// xmlhttp.onreadystatechange = function() {
// if (xmlhttp.readyState==4 && xmlhttp.status==200) {
// console.log('xmlresponse:', xmlhttp.responseText);
// // document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
// }
// }
// xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded", true);
// xmlhttp.send("secret=" + this.secret);
//Login to firebase
// this.mainRef.authWithPassword()
} else {
console.log('Missing app info.');
if(argPyroData.hasOwnProperty('name')) {
errorCb({message:'Please enter the name of your firebase instance.'});
} else {
errorCb({message:'Please enter your firebase secret'})
}
}
}
};
function loadUsersList(argRef, callback){
argRef.child('users').on('value', function(usersListSnap){
callback(usersListSnap);
});
}
//------------ Instance action functions -----------------//
function createNewInstance(argPyro, successCb, errorCb) {
checkForInstance(argPyro, function(returnedInstance){
if(returnedInstance == null) {
instanceList.child(argPyro.name).set(instanceData, function(){
argPyro.pyroRef = instanceList.child(argPyro.name);
if(successCb) {
successCb(argPyro.pyroRef);
}
});
} else {
var err = {message:'App already exists'}
console.warn(err.message);
errorCb(err);
}
});
}
function checkForInstance(argPyro, argName, callback) {
// [TODO] Add user's id to author object?
//check for app existance on pyroBase
console.log('checkForInstance:', argPyro);
var instanceList = argPyro.pyroRef.child("instances");
var instanceName = argPyro.currentInstance.name;
instanceList.orderByChild("name").equalTo(instanceName).once('value', function(usersSnap){
console.log('usersSnap:', usersSnap);
if(usersSnap.val() == null) {
console.log('App does not already exist');
// Add instance to instance list under the instance name
callback(null);
}
else {
console.log('app already exists');
if(callback) {
callback(usersSnap.child(instanceName));
}
}
});
}
//------------- User ---------------//
function User(argUserData, argMainRef) {
console.log('NEW User');
if(argUserData.hasOwnProperty('email')) {
this.email = argUserData.email
} else {
throw Error('Email needed to create user');
}
this.account = checkForUser(argUserData.email, argMainRef, function(returnedAccount){
return returnedAccount;
})
return this;
}
function getAccountOrSignup(){
return checkForUser(argUserData, argMainRef, function(userAccount){
if(userAccount != null) {
return userAccount;
} else {
return new User(argUserData, this);
emailSignup(argUserData, function(returnedUser){
}, function(){
});
}
})
}
function emailSignup(argSignupData, argThis, successCb, errorCb) {
argThis.mainRef.createUser(argSignupData, function(error) {
if (error === null) {
console.log("User created successfully");
// Login with new account and create profile
argThis.login(argSignupData, function(authData){
createUserProfile(authData, argThis.mainRef, function(userAccount){
var newUser = new User(authData);
successCb(newUser);
});
});
} else {
console.error("Error creating user:", error.message);
errorCb(error);
}
});
}
function authWithPassword(argLoginData, argRef, successCb, errorCb) {
console.log('authWithPassword',argLoginData, argRef, successCb, errorCb);
if(argLoginData.hasOwnProperty('email') && argLoginData.hasOwnProperty('password')) {
argRef.authWithPassword(argLoginData, function(error, authData) {
if (error === null) {
// user authenticated with Firebase
console.log("User ID: " + authData.uid + ", Provider: " + authData.provider);
// Manage presense
setupPresence(authData.uid, argRef);
// Add account if it doesn't already exist
userById(authData.uid, argRef.child('users'), function(userAccount){
successCb(userAccount);
});
} else {
console.error("Error authenticating user:", error);
errorCb(error);
}
});
} else {
// [TODO] Use error handling from Firbase.authWithPassword()
console.error('Incorrect login info', argLoginData);
var err = {message:'Incorrect login info'}
errorCb('Incorrect login info:', argLoginData);
}
}
function createUserProfile(argAuthData, argRef, callback) {
console.log('createUserAccount called');
var userRef = argRef.child('users').child(argAuthData.uid);
var userObj = {role:10, provider: argAuthData.provider};
if(argAuthData.provider == 'password') {
userObj.email = argAuthData.password.email;
}
userRef.on('value', function(userSnap){
if(userSnap.val() == null) {
userObj.createdAt = Firebase.ServerValue.TIMESTAMP
userRef.setWithPriority(userObj, userEmail, function(){
console.log('New user account created:', userSnap.val());
callback(userSnap.val());
});
} else {
console.error('User account already exists');
throw Error('User account already exists');
}
});
}
function setupPresence(argUserId, argMainRef) {
console.log('setupPresence:', arguments);
var amOnline = argMainRef.child('.info/connected');
var onlineRef = argMainRef.child('presense').child(argUserId);
var sessionsRef = argMainRef.child('sessions');
var userRef = argMainRef.child('users').child(argUserId);
var userSessionRef = argMainRef.child('users').child(argUserId).child('sessions');
var pastSessionsRef = userSessionRef.child('past');
amOnline.on('value', function(snapShot){
if(snapShot.val()) {
//user is online
var onDisconnectRef = argMainRef.onDisconnect();
// add session and set disconnect
var session = sessionsRef.push({began: Firebase.ServerValue.TIMESTAMP, user:argUserId});
session.child('ended').onDisconnect().set(Firebase.ServerValue.TIMESTAMP);
//add correct session id to user
// adding session id to current list under user's session
var currentSesh = userSessionRef.child('current').push(session.name());
// Remove session id from users current session folder
currentSesh.onDisconnect().remove();
// remove from presense list
onlineRef.set(true);
onlineRef.onDisconnect().remove();
// Add session id to past sessions on disconnect
// pastSessionsRef.onDisconnect().push(session.name());
}
});
}
function userById(argUserId, argUsersRef, callback) {
console.log('userById run with id:', argUserId);
argUsersRef.child(argUserId).on('value', function(userSnap){
callback(userSnap.val());
});
}
// Single Checking function for all user types (should be in one folder)
// [TODO] Fix repative code within if statements
function checkForUser(argUserData, argUsersRef, callback) {
console.log('CheckForUser:', argUserData);
var userEmail = '[email protected]';
// [TODO] Change to switch statement
// [TODO] Change to using provider folder (password if for email/password)
if(argUserData.hasOwnProperty('email') || argUserData.hasOwnProperty('password')) {
if (argUserData.hasOwnProperty('password')){
userEmail = argUserData.password.email;
}
else if(argUserData.hasOwnProperty('email')) {
// object contains email
userEmail = argUserData.email;
}
argUsersRef.orderByChild('email').startAt(userEmail).endAt(userEmail).on("value", function(querySnapshot) {
console.log('check for user returned:', querySnapshot.val());
querySnapshot.forEach(function(){
});
callback(querySnapshot.val());
if(querySnapshot.val() != null) {
console.log('Usersnap:', querySnapshot.val());
}
});
}
else {
console.error('Incorrect user info');
}
} | pyro.js | /* Pyro for Firebase*/
// Pyro Platform Firebase:
var pyroRef = new Firebase('http://pyro.firebaseio.com');
// Constructor:
function Pyro (argPyroData, errorCb) {
//Check for existance of Firebase
if(typeof Firebase != 'undefined' && typeof argPyroData != 'undefined') {
if(argPyroData.hasOwnProperty('url')){
// [TODO] Check that url is firebase
this.url = argPyroData.url;
this.mainRef = new Firebase(argPyroData.url);
this.pyroRef = pyroRef;
// Not Required variables
if(argPyroData.hasOwnProperty('secret')) {
this.secret = argPyroData.secret;
}
if(argPyroData.hasOwnProperty('name')) {
this.name = argPyroData.name;
} else {
//Regex name from url
// this.name =
}
} else {
console.error('Missing firebase url.');
if(errorCb) {
errorCb({message:'Please provide your when running new Pyro() firebase URL'});
}
}
return this;
} else if(typeof argPyroData == 'undefined') {
console.error('New pyro object does not include nessesary information.');
}
else throw Error('Firebase library does not exist. Check that firebase.js is included in your index.html file.');
//for incorrect scope
// if (window === this) {
// return new _(id);
// }
}
Pyro.prototype = {
userSignup: function(argUserData, successCb, errorCb) {
emailSignup(argSignupData, successCb, errorCb);
},
authAnonymously: function(){
//check for auth info
var auth = this.mainRef.getAuth();
console.log('authAnonymously', auth);
var currentThis = this;
if(auth != null) {
this.mainRef.authAnonymously(function(error, authData){
if (error) {
console.log('Login Failed!', error);
} else {
console.log('Authenticated successfully with payload:', authData);
var anon = {uid: authData.uid, provider:authData.provider};
currentThis.mainRef.child('users').child(authData.uid).set(anon);
}
});
} else {
//auth exists
}
},
login: function(argLoginData, successCb, errorCb) {
console.log('Pyro login:', arguments);
var self = this;
// check for existnace of main ref
authWithPassword(argLoginData, self.mainRef, successCb, errorCb);
},
logout:function(){
this.mainRef.unauth();
},
getAuth: function() {
console.log('getAuth called');
var authData = this.mainRef.getAuth();
if (authData) {
return authData;
} else {
console.warn('Not Authenticated');
return null;
}
},
getListByAuthor: function(argListName, callback) {
var auth = this.getAuth();
if(auth != null) {
this.mainRef.child(argListName).orderByChild('author').equalTo(auth.uid).on('value', function(listSnap){
callback(listSnap.val());
});
} else {
console.warn('listByAuthor cannot load list without current user');
}
},
createObject: function(argListName, argObject, callback) {
var auth = this.getAuth();
if(auth) {
argObject.author = auth.uid;
}
var newObj = this.mainRef.child(argListName).push(argObject, function(){
console.log('New object of type:' + argListName + ' was created successfully:', newObj);
callback(newObj);
})
},
getUser: function(callback) {
if (this.getAuth() != null) {
console.log('Authenticated user with email:', this.getAuth().password.email);
var self = this;
userById(this.getAuth().uid, self.mainRef.child('users'), function(returnedAccount){
console.log('checkForUser loaded user:', returnedAccount);
callback(returnedAccount);
});
} else {
callback(null);
}
},
getListByAuthor:function(argListName, callback){
// [TODO] Better method of checking auth
console.log('getListByAuthor:', argListName);
var listRef = this.mainRef.child(argListName);
this.getUser(function(account){
if(account != null) {
console.log('getInstances running for:', account);
listRef.orderByChild('author').equalTo(account.email).limitToFirst(1).on('value', function(userInstancesSnap){
callback(userInstancesSnap.val());
});
}
});
},
// Functions specific to managing Pyro instances (Pyro inception)
getInstances: function(callback) {
// [TODO] Better method of checking auth
var instancesRef = this.instancesRef;
this.getUser(function(account){
if(account != null) {
console.log('getInstances running for:', account);
instancesRef.orderByChild('author').equalTo(account.email).on('value', function(userInstancesSnap){
callback(userInstancesSnap.val());
});
}
});
},
loadInstance: function(argInstanceData, successCb, errorCb) {
console.log('loadInstance:', argInstanceData);
this.currentInstance = {name:argInstanceData.name}
checkForInstance(this, function(instanceRef){
successCb(instanceRef.val());
}, errorCb);
},
instanceRef: function(argInstanceData, successCb, errorCb) {
console.log('loadInstance:', argInstanceData);
this.currentInstance = {name:argInstanceData.name}
checkForInstance(this, successCb, errorCb);
},
// addAdminModule: function() {
// console.log('add admin module called', this);
// var self = this;
// if(PyroAdmin) {
// console.log('PyroAdmin exists... Creating instance');
// var pyroAdmin = new PyroAdmin(self);
// }
// },
getUserCount: function(callback){
var self = this;
this.mainRef.child('users').on('value', function(usersListSnap){
callback(usersListSnap.numChildren());
});
},
getUserList: function(callback){
this.mainRef.child('users').on('value', function(usersListSnap){
callback(usersListSnap.val());
});
},
createInstance: function (argPyroData, successCb, errorCb) {
var self = this;
if(argPyroData.hasOwnProperty('name') && argPyroData.hasOwnProperty('secret')){
// [TODO] Check that url is firebase
this.mainRef = new Firebase(self.url);
checkForInstance(this, function(returnedInstance){
successCb(returnedInstance);
});
//request admin auth token
// var xmlhttp = new XMLHttpRequest();
// xmlhttp.open("POST", "http://pyro-server.herokuapp.com/auth");
// xmlhttp.onreadystatechange = function() {
// if (xmlhttp.readyState==4 && xmlhttp.status==200) {
// console.log('xmlresponse:', xmlhttp.responseText);
// // document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
// }
// }
// xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded", true);
// xmlhttp.send("secret=" + this.secret);
//Login to firebase
// this.mainRef.authWithPassword()
} else {
console.log('Missing app info.');
if(argPyroData.hasOwnProperty('name')) {
errorCb({message:'Please enter the name of your firebase instance.'});
} else {
errorCb({message:'Please enter your firebase secret'})
}
}
}
};
function loadUsersList(argRef, callback){
argRef.child('users').on('value', function(usersListSnap){
callback(usersListSnap);
});
}
//------------ Instance action functions -----------------//
function createNewInstance(argPyro, successCb, errorCb) {
checkForInstance(argPyro, function(returnedInstance){
if(returnedInstance == null) {
instanceList.child(argPyro.name).set(instanceData, function(){
argPyro.pyroRef = instanceList.child(argPyro.name);
if(successCb) {
successCb(argPyro.pyroRef);
}
});
} else {
var err = {message:'App already exists'}
console.warn(err.message);
errorCb(err);
}
});
}
function checkForInstance(argPyro, argName, callback) {
// [TODO] Add user's id to author object?
//check for app existance on pyroBase
console.log('checkForInstance:', argPyro);
var instanceList = argPyro.pyroRef.child("instances");
var instanceName = argPyro.currentInstance.name;
instanceList.orderByChild("name").equalTo(instanceName).once('value', function(usersSnap){
console.log('usersSnap:', usersSnap);
if(usersSnap.val() == null) {
console.log('App does not already exist');
// Add instance to instance list under the instance name
callback(null);
}
else {
console.log('app already exists');
if(callback) {
callback(usersSnap.child(instanceName));
}
}
});
}
//------------- User ---------------//
function User(argUserData, argMainRef) {
console.log('NEW User');
if(argUserData.hasOwnProperty('email')) {
this.email = argUserData.email
} else {
throw Error('Email needed to create user');
}
this.account = checkForUser(argUserData.email, argMainRef, function(returnedAccount){
return returnedAccount;
})
return this;
}
function getAccountOrSignup(){
return checkForUser(argUserData, argMainRef, function(userAccount){
if(userAccount != null) {
return userAccount;
} else {
return new User(argUserData, this);
emailSignup(argUserData, function(returnedUser){
}, function(){
});
}
})
}
function emailSignup(argSignupData, successCb, errorCb) {
this.mainRef.createUser(argSignupData, function(error) {
if (error === null) {
console.log("User created successfully");
// Login with new account and create profile
currentThis.login(argSignupData, function(authData){
createUserProfile(authData, currentThis.mainRef, function(userAccount){
var newUser = new User(authData);
successCb(newUser);
});
});
} else {
console.error("Error creating user:", error.message);
errorCb(error.message);
}
});
}
function authWithPassword(argLoginData, argRef, successCb, errorCb) {
console.log('authWithPassword',argLoginData, argRef, successCb, errorCb);
if(argLoginData.hasOwnProperty('email') && argLoginData.hasOwnProperty('password')) {
argRef.authWithPassword(argLoginData, function(error, authData) {
if (error === null) {
// user authenticated with Firebase
console.log("User ID: " + authData.uid + ", Provider: " + authData.provider);
// Manage presense
setupPresence(authData.uid, argRef);
// Add account if it doesn't already exist
userById(authData.uid, argRef.child('users'), function(userAccount){
successCb(userAccount);
});
} else {
console.error("Error authenticating user:", error);
errorCb(error);
}
});
} else {
// [TODO] Use error handling from Firbase.authWithPassword()
console.error('Incorrect login info', argLoginData);
var err = {message:'Incorrect login info'}
errorCb('Incorrect login info:', argLoginData);
}
}
function createUserProfile(argAuthData, argRef, callback) {
console.log('createUserAccount called');
var userRef = argRef.child('users').child(argAuthData.uid);
var userObj = {role:10, provider: argAuthData.provider};
if(argAuthData.provider == 'password') {
userObj.email = argAuthData.password.email;
}
userRef.on('value', function(userSnap){
if(userSnap.val() == null) {
userObj.createdAt = Firebase.ServerValue.TIMESTAMP
userRef.setWithPriority(userObj, userEmail, function(){
console.log('New user account created:', userSnap.val());
callback(userSnap.val());
});
} else {
console.error('User account already exists');
throw Error('User account already exists');
}
});
}
function setupPresence(argUserId, argMainRef) {
console.log('setupPresence:', arguments);
var amOnline = argMainRef.child('.info/connected');
var onlineRef = argMainRef.child('presense').child(argUserId);
var sessionsRef = argMainRef.child('sessions');
var userRef = argMainRef.child('users').child(argUserId);
var userSessionRef = argMainRef.child('users').child(argUserId).child('sessions');
var pastSessionsRef = userSessionRef.child('past');
amOnline.on('value', function(snapShot){
if(snapShot.val()) {
//user is online
var onDisconnectRef = argMainRef.onDisconnect();
// add session and set disconnect
var session = sessionsRef.push({began: Firebase.ServerValue.TIMESTAMP, user:argUserId});
session.child('ended').onDisconnect().set(Firebase.ServerValue.TIMESTAMP);
//add correct session id to user
// adding session id to current list under user's session
var currentSesh = userSessionRef.child('current').push(session.name());
// Remove session id from users current session folder
currentSesh.onDisconnect().remove();
// remove from presense list
onlineRef.set(true);
onlineRef.onDisconnect().remove();
// Add session id to past sessions on disconnect
// pastSessionsRef.onDisconnect().push(session.name());
}
});
}
function userById(argUserId, argUsersRef, callback) {
console.log('userById run with id:', argUserId);
argUsersRef.child(argUserId).on('value', function(userSnap){
callback(userSnap.val());
});
}
// Single Checking function for all user types (should be in one folder)
// [TODO] Fix repative code within if statements
function checkForUser(argUserData, argUsersRef, callback) {
console.log('CheckForUser:', argUserData);
var userEmail = '[email protected]';
// [TODO] Change to switch statement
// [TODO] Change to using provider folder (password if for email/password)
if(argUserData.hasOwnProperty('email') || argUserData.hasOwnProperty('password')) {
if (argUserData.hasOwnProperty('password')){
userEmail = argUserData.password.email;
}
else if(argUserData.hasOwnProperty('email')) {
// object contains email
userEmail = argUserData.email;
}
argUsersRef.orderByChild('email').startAt(userEmail).endAt(userEmail).on("value", function(querySnapshot) {
console.log('check for user returned:', querySnapshot.val());
querySnapshot.forEach(function(){
});
callback(querySnapshot.val());
if(querySnapshot.val() != null) {
console.log('Usersnap:', querySnapshot.val());
}
});
}
else {
console.error('Incorrect user info');
}
} | General Object count function added.
| pyro.js | General Object count function added. | <ide><path>yro.js
<ide> // }
<ide> }
<ide> Pyro.prototype = {
<del> userSignup: function(argUserData, successCb, errorCb) {
<del> emailSignup(argSignupData, successCb, errorCb);
<add> userSignup: function(argSignupData, successCb, errorCb) {
<add> var self = this;
<add> emailSignup(argSignupData, self, successCb, errorCb);
<ide> },
<ide> authAnonymously: function(){
<ide> //check for auth info
<ide> // check for existnace of main ref
<ide> authWithPassword(argLoginData, self.mainRef, successCb, errorCb);
<ide> },
<del> logout:function(){
<add> logout:function(callback){
<ide> this.mainRef.unauth();
<add> if(callback){
<add> callback();
<add> }
<ide> },
<ide> getAuth: function() {
<ide> console.log('getAuth called');
<ide> argObject.author = auth.uid;
<ide> }
<ide> var newObj = this.mainRef.child(argListName).push(argObject, function(){
<del> console.log('New object of type:' + argListName + ' was created successfully:', newObj);
<ide> callback(newObj);
<del> })
<add> });
<ide> },
<ide> getUser: function(callback) {
<ide> if (this.getAuth() != null) {
<del> console.log('Authenticated user with email:', this.getAuth().password.email);
<ide> var self = this;
<ide> userById(this.getAuth().uid, self.mainRef.child('users'), function(returnedAccount){
<del> console.log('checkForUser loaded user:', returnedAccount);
<ide> callback(returnedAccount);
<ide> });
<ide> } else {
<ide> callback(null);
<ide> }
<ide> },
<del> getListByAuthor:function(argListName, callback){
<del> // [TODO] Better method of checking auth
<del> console.log('getListByAuthor:', argListName);
<add> loadObject:function(argListName, argObjectId, callback){
<ide> var listRef = this.mainRef.child(argListName);
<del> this.getUser(function(account){
<del> if(account != null) {
<del> console.log('getInstances running for:', account);
<del> listRef.orderByChild('author').equalTo(account.email).limitToFirst(1).on('value', function(userInstancesSnap){
<del> callback(userInstancesSnap.val());
<del> });
<del> }
<del> });
<del> },
<del> // Functions specific to managing Pyro instances (Pyro inception)
<del> getInstances: function(callback) {
<del> // [TODO] Better method of checking auth
<del> var instancesRef = this.instancesRef;
<del> this.getUser(function(account){
<del> if(account != null) {
<del> console.log('getInstances running for:', account);
<del> instancesRef.orderByChild('author').equalTo(account.email).on('value', function(userInstancesSnap){
<del> callback(userInstancesSnap.val());
<del> });
<del> }
<del> });
<del> },
<del> loadInstance: function(argInstanceData, successCb, errorCb) {
<del> console.log('loadInstance:', argInstanceData);
<del> this.currentInstance = {name:argInstanceData.name}
<del> checkForInstance(this, function(instanceRef){
<del> successCb(instanceRef.val());
<del> }, errorCb);
<add> listRef.child(argObjectId).on('value', function(objectSnap){
<add> callback(objectSnap.val());
<add> });
<ide> },
<ide> instanceRef: function(argInstanceData, successCb, errorCb) {
<ide> console.log('loadInstance:', argInstanceData);
<ide> this.currentInstance = {name:argInstanceData.name}
<ide> checkForInstance(this, successCb, errorCb);
<ide> },
<del> // addAdminModule: function() {
<del> // console.log('add admin module called', this);
<del> // var self = this;
<del> // if(PyroAdmin) {
<del> // console.log('PyroAdmin exists... Creating instance');
<del> // var pyroAdmin = new PyroAdmin(self);
<del> // }
<del> // },
<add> getObjectCount: function(argListName, callback){
<add> var self = this;
<add> this.mainRef.child(argListName).on('value', function(usersListSnap){
<add> callback(usersListSnap.numChildren());
<add> });
<add> },
<ide> getUserCount: function(callback){
<ide> var self = this;
<ide> this.mainRef.child('users').on('value', function(usersListSnap){
<ide> })
<ide> }
<ide>
<del> function emailSignup(argSignupData, successCb, errorCb) {
<del> this.mainRef.createUser(argSignupData, function(error) {
<add> function emailSignup(argSignupData, argThis, successCb, errorCb) {
<add> argThis.mainRef.createUser(argSignupData, function(error) {
<ide> if (error === null) {
<ide> console.log("User created successfully");
<ide> // Login with new account and create profile
<del> currentThis.login(argSignupData, function(authData){
<del> createUserProfile(authData, currentThis.mainRef, function(userAccount){
<add> argThis.login(argSignupData, function(authData){
<add> createUserProfile(authData, argThis.mainRef, function(userAccount){
<ide> var newUser = new User(authData);
<del> successCb(newUser);
<add> successCb(newUser);
<ide> });
<ide> });
<ide> } else {
<ide> console.error("Error creating user:", error.message);
<del> errorCb(error.message);
<add> errorCb(error);
<ide> }
<ide> });
<ide> } |
|
Java | agpl-3.0 | c7535bb8065ac7cd948fa0d92393cf469d5bb572 | 0 | SoftInstigate/restheart,mergul/restheart,SoftInstigate/restheart,rahulsharma1991/restheart,rafaelsisweb/restheart,gokrokvertskhov/restheart,rahulsharma1991/restheart,akshayvaidya/restheart,SkydiverFL/restheart,SoftInstigate/restheart,gokrokvertskhov/restheart,SoftInstigate/restheart,anteneh72/restheart,rafaelsisweb/restheart,anteneh72/restheart,mergul/restheart,anteneh72/restheart,akshayvaidya/restheart,SkydiverFL/restheart,anteneh72/restheart | /*
* RESTHeart - the data REST API server
* Copyright (C) 2014 - 2015 SoftInstigate Srl
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.restheart.handlers.applicationlogic;
import com.mongodb.BasicDBObject;
import org.restheart.hal.Representation;
import org.restheart.handlers.PipedHttpHandler;
import org.restheart.handlers.RequestContext;
import org.restheart.handlers.RequestContext.METHOD;
import org.restheart.utils.HttpStatus;
import io.undertow.server.HttpServerExchange;
import io.undertow.util.Headers;
import io.undertow.util.HttpString;
import java.util.Map;
import java.util.Set;
import static org.restheart.hal.Representation.HAL_JSON_MEDIA_TYPE;
import static org.restheart.security.handlers.IAuthToken.AUTH_TOKEN_HEADER;
import static org.restheart.security.handlers.IAuthToken.AUTH_TOKEN_LOCATION_HEADER;
import static org.restheart.security.handlers.IAuthToken.AUTH_TOKEN_VALID_HEADER;
import org.restheart.utils.URLUtils;
/**
*
* @author Andrea Di Cesare <[email protected]>
*/
public class GetRoleHandler extends ApplicationLogicHandler {
/**
* the key for the url property.
*/
public static final String urlKey = "url";
private String url;
/**
* Creates a new instance of GetRoleHandler
*
* @param next
* @param args
* @throws Exception
*/
public GetRoleHandler(PipedHttpHandler next, Map<String, Object> args) throws Exception {
super(next, args);
if (args == null) {
throw new IllegalArgumentException("args cannot be null");
}
this.url = (String) ((Map<String, Object>) args).get(urlKey);
}
/**
* Handles the request.
*
* @param exchange
* @param context
* @throws Exception
*/
@Override
public void handleRequest(HttpServerExchange exchange, RequestContext context) throws Exception {
Representation rep;
if (context.getMethod() == METHOD.OPTIONS) {
exchange.getResponseHeaders().put(HttpString.tryFromString("Access-Control-Allow-Methods"), "GET");
exchange.getResponseHeaders().put(HttpString.tryFromString("Access-Control-Allow-Headers"), "Accept, Accept-Encoding, Authorization, Content-Length, Content-Type, Host, Origin, X-Requested-With, User-Agent, No-Auth-Challenge");
exchange.setResponseCode(HttpStatus.SC_OK);
exchange.endExchange();
} else if (context.getMethod() == METHOD.GET) {
if ((exchange.getSecurityContext() == null
|| exchange.getSecurityContext().getAuthenticatedAccount() == null
|| exchange.getSecurityContext().getAuthenticatedAccount().getPrincipal() == null)
|| !(context.getUnmappedRequestUri().equals(URLUtils.removeTrailingSlashes(url) + "/" + exchange.getSecurityContext().getAuthenticatedAccount().getPrincipal().getName()))) {
{
exchange.setResponseCode(HttpStatus.SC_UNAUTHORIZED);
// REMOVE THE AUTH TOKEN HEADERS!!!!!!!!!!!
exchange.getResponseHeaders().remove(AUTH_TOKEN_HEADER);
exchange.getResponseHeaders().remove(AUTH_TOKEN_VALID_HEADER);
exchange.getResponseHeaders().remove(AUTH_TOKEN_LOCATION_HEADER);
exchange.endExchange();
return;
}
} else {
rep = new Representation(URLUtils.removeTrailingSlashes(url) + "/" + exchange.getSecurityContext().getAuthenticatedAccount().getPrincipal().getName());
BasicDBObject root = new BasicDBObject();
Set<String> _roles = exchange.getSecurityContext().getAuthenticatedAccount().getRoles();
root.append("authenticated", true);
root.append("roles", _roles);
rep.addProperties(root);
}
exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, HAL_JSON_MEDIA_TYPE);
exchange.getResponseSender().send(rep.toString());
exchange.endExchange();
} else {
exchange.setResponseCode(HttpStatus.SC_METHOD_NOT_ALLOWED);
exchange.endExchange();
}
}
}
| src/main/java/org/restheart/handlers/applicationlogic/GetRoleHandler.java | /*
* RESTHeart - the data REST API server
* Copyright (C) 2014 - 2015 SoftInstigate Srl
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.restheart.handlers.applicationlogic;
import com.mongodb.BasicDBObject;
import org.restheart.hal.Representation;
import org.restheart.handlers.PipedHttpHandler;
import org.restheart.handlers.RequestContext;
import org.restheart.handlers.RequestContext.METHOD;
import org.restheart.utils.HttpStatus;
import io.undertow.server.HttpServerExchange;
import io.undertow.util.Headers;
import io.undertow.util.HttpString;
import java.util.Map;
import java.util.Set;
import static org.restheart.hal.Representation.HAL_JSON_MEDIA_TYPE;
import static org.restheart.security.handlers.IAuthToken.AUTH_TOKEN_HEADER;
import static org.restheart.security.handlers.IAuthToken.AUTH_TOKEN_LOCATION_HEADER;
import static org.restheart.security.handlers.IAuthToken.AUTH_TOKEN_VALID_HEADER;
import org.restheart.utils.URLUtils;
/**
*
* @author Andrea Di Cesare <[email protected]>
*/
public class GetRoleHandler extends ApplicationLogicHandler {
/**
* the key for the url property.
*/
public static final String urlKey = "url";
private String url;
/**
* Creates a new instance of GetRoleHandler
*
* @param next
* @param args
* @throws Exception
*/
public GetRoleHandler(PipedHttpHandler next, Map<String, Object> args) throws Exception {
super(next, args);
if (args == null) {
throw new IllegalArgumentException("args cannot be null");
}
this.url = (String) ((Map<String, Object>) args).get(urlKey);
}
/**
* Handles the request.
*
* @param exchange
* @param context
* @throws Exception
*/
@Override
public void handleRequest(HttpServerExchange exchange, RequestContext context) throws Exception {
if (context.getMethod() == METHOD.OPTIONS) {
exchange.getResponseHeaders().put(HttpString.tryFromString("Access-Control-Allow-Methods"), "GET");
exchange.getResponseHeaders().put(HttpString.tryFromString("Access-Control-Allow-Headers"), "Accept, Accept-Encoding, Authorization, Content-Length, Content-Type, Host, Origin, X-Requested-With, User-Agent, No-Auth-Challenge");
exchange.setResponseCode(HttpStatus.SC_OK);
exchange.endExchange();
} else if (context.getMethod() == METHOD.GET) {
if (!(context.getUnmappedRequestUri().equals(URLUtils.removeTrailingSlashes(url) + "/" + exchange.getSecurityContext().getAuthenticatedAccount().getPrincipal().getName()))) {
exchange.setResponseCode(HttpStatus.SC_UNAUTHORIZED);
// REMOVE THE AUTH TOKEN HEADERS!!!!!!!!!!!
exchange.getResponseHeaders().remove(AUTH_TOKEN_HEADER);
exchange.getResponseHeaders().remove(AUTH_TOKEN_VALID_HEADER);
exchange.getResponseHeaders().remove(AUTH_TOKEN_LOCATION_HEADER);
exchange.endExchange();
return;
}
Representation rep = new Representation(url);
if (exchange.getSecurityContext() == null
|| exchange.getSecurityContext().getAuthenticatedAccount() == null
|| exchange.getSecurityContext().getAuthenticatedAccount().getPrincipal() == null) {
BasicDBObject root = new BasicDBObject();
root.append("authenticated", false);
root.append("roles", null);
rep.addProperties(root);
} else {
BasicDBObject root = new BasicDBObject();
Set<String> _roles = exchange.getSecurityContext().getAuthenticatedAccount().getRoles();
root.append("authenticated", true);
root.append("roles", _roles);
rep.addProperties(root);
}
exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, HAL_JSON_MEDIA_TYPE);
exchange.getResponseSender().send(rep.toString());
exchange.endExchange();
} else {
exchange.setResponseCode(HttpStatus.SC_METHOD_NOT_ALLOWED);
exchange.endExchange();
}
}
}
| NPE bug fixed on GetRoleHandler
| src/main/java/org/restheart/handlers/applicationlogic/GetRoleHandler.java | NPE bug fixed on GetRoleHandler | <ide><path>rc/main/java/org/restheart/handlers/applicationlogic/GetRoleHandler.java
<ide> public static final String urlKey = "url";
<ide>
<ide> private String url;
<del>
<add>
<ide> /**
<ide> * Creates a new instance of GetRoleHandler
<ide> *
<ide> */
<ide> @Override
<ide> public void handleRequest(HttpServerExchange exchange, RequestContext context) throws Exception {
<add> Representation rep;
<add>
<ide> if (context.getMethod() == METHOD.OPTIONS) {
<ide> exchange.getResponseHeaders().put(HttpString.tryFromString("Access-Control-Allow-Methods"), "GET");
<ide> exchange.getResponseHeaders().put(HttpString.tryFromString("Access-Control-Allow-Headers"), "Accept, Accept-Encoding, Authorization, Content-Length, Content-Type, Host, Origin, X-Requested-With, User-Agent, No-Auth-Challenge");
<ide> exchange.setResponseCode(HttpStatus.SC_OK);
<ide> exchange.endExchange();
<ide> } else if (context.getMethod() == METHOD.GET) {
<del> if (!(context.getUnmappedRequestUri().equals(URLUtils.removeTrailingSlashes(url) + "/" + exchange.getSecurityContext().getAuthenticatedAccount().getPrincipal().getName()))) {
<del> exchange.setResponseCode(HttpStatus.SC_UNAUTHORIZED);
<del>
<del> // REMOVE THE AUTH TOKEN HEADERS!!!!!!!!!!!
<del> exchange.getResponseHeaders().remove(AUTH_TOKEN_HEADER);
<del> exchange.getResponseHeaders().remove(AUTH_TOKEN_VALID_HEADER);
<del> exchange.getResponseHeaders().remove(AUTH_TOKEN_LOCATION_HEADER);
<add> if ((exchange.getSecurityContext() == null
<add> || exchange.getSecurityContext().getAuthenticatedAccount() == null
<add> || exchange.getSecurityContext().getAuthenticatedAccount().getPrincipal() == null)
<add> || !(context.getUnmappedRequestUri().equals(URLUtils.removeTrailingSlashes(url) + "/" + exchange.getSecurityContext().getAuthenticatedAccount().getPrincipal().getName()))) {
<ide>
<del> exchange.endExchange();
<del> return;
<del> }
<add> {
<add> exchange.setResponseCode(HttpStatus.SC_UNAUTHORIZED);
<ide>
<del> Representation rep = new Representation(url);
<add> // REMOVE THE AUTH TOKEN HEADERS!!!!!!!!!!!
<add> exchange.getResponseHeaders().remove(AUTH_TOKEN_HEADER);
<add> exchange.getResponseHeaders().remove(AUTH_TOKEN_VALID_HEADER);
<add> exchange.getResponseHeaders().remove(AUTH_TOKEN_LOCATION_HEADER);
<ide>
<del> if (exchange.getSecurityContext() == null
<del> || exchange.getSecurityContext().getAuthenticatedAccount() == null
<del> || exchange.getSecurityContext().getAuthenticatedAccount().getPrincipal() == null) {
<add> exchange.endExchange();
<add> return;
<add> }
<ide>
<del> BasicDBObject root = new BasicDBObject();
<del>
<del> root.append("authenticated", false);
<del> root.append("roles", null);
<del>
<del> rep.addProperties(root);
<ide> } else {
<add> rep = new Representation(URLUtils.removeTrailingSlashes(url) + "/" + exchange.getSecurityContext().getAuthenticatedAccount().getPrincipal().getName());
<ide> BasicDBObject root = new BasicDBObject();
<ide>
<ide> Set<String> _roles = exchange.getSecurityContext().getAuthenticatedAccount().getRoles(); |
|
Java | mit | 03388d427a9d9acf3c513d5565391a427d27a373 | 0 | sikuli/sikuli-slides,sikuli/sikuli-slides,sikuli/sikuli-slides | /**
* @author Khalid Alharbi
*/
package org.sikuli.slides.utils;
import java.io.File;
/**
* This class contains constants.
*/
public class Constants {
/**
* The working directory absolute path.
* This holds the sikuli slides working directory in the operating system's temp directory.
*/
public static String workingDirectoryPath;
/**
* The current project directory name that contains the imported and extracted .pptx file.
*/
public static String projectDirectory;
/**
* The relative directory path to the embedding resources icons for the GUIs.
*/
public static final String RESOURCES_ICON_DIR="/org/sikuli/slides/gui/icons/";
/**
* The name of the directory that sikuli-slides creates in the operating system's tmp directory.
*/
public static final String SIKULI_SLIDES_ROOT_DIRECTORY="org.sikuli.SikuliSlides";
/**
* The name of the directory that contains all sikuli related files in the .pptx file.
*/
public static final String SIKULI_DIRECTORY=File.separator+"sikuli";
/**
* The name of the directory that contains the downloaded files.
*/
public static final String SIKULI_DOWNLOAD_DIRECTORY=File.separator+"download";
/**
* The name of the images directory that contains the cropped target images.
*/
public static final String IMAGES_DIRECTORY=File.separator+"images";
/**
* The slides directory that contains the XML files for each slide in the .pptx file.
*/
public static final String SLIDES_DIRECTORY=File.separator+"ppt"+File.separator+"slides";
/**
* The slides directory that contains the media files for each slide in the .pptx file.
*/
public static final String MEDIA_DIRECTORY=File.separator+"ppt"+File.separator+"media";
/**
* The slides directory that contains the slide notes.
*/
public static final String SLIDE_NOTES_DIRECTORY=File.separator+"ppt"+File.separator+"notesSlides";
/**
* The presentaion.xml absolute path name.
*/
public static final String PRESENTATION_DIRECTORY=File.separator+"ppt"+File.separator+"presentation.xml";
/**
* The relationship directory that contains info about the duplicated media files in the presentation slides.
*/
public static final String RELATIONSHIP_DIRECTORY=File.separator+"ppt"+File.separator+"slides"+File.separator+"_rels";
/**
* The key name for maximum wait time to find target on the screen.
*/
public static final String MAX_WAIT_TIME_MS = "max_wait_time_ms";
/**
* The default key value for maximum wait time in milliseconds to find target on the screen.
*/
public static int MAX_WAIT_TIME_MS_DEFAULT = 15000;
/**
* The key name for the score value that controls how fuzzy the image search is. A value of 1 means the search
* is very precise and less fuzzy. This is defined as minscore in the API
*/
public static final String PRECISE_SEARCH_SCORE = "precise_search_score";
/**
* The default key value for the score value that controls how fuzzy the image search is
*/
public static final double PRECISE_SEARCH_SCORE_DEFAULT = 0.7;
/**
* The key name for the time to display a label on the screen.
*/
public static final String LABEL_DISPLAY_TIME_SEC = "label_display_time_sec";
/**
* The default key value for the time, in seconds, to display a label on the screen.
*/
public static final int LABEL_DISPLAY_TIME_SEC_DEFAULT = 3;
/**
* The key name for the instruction hint (tooltip) font size.
*/
public static final String INSTRUCTION_HINT_FONT_SIZE="instruction_hint_font_size";
/**
* The default key value of the instruction hint (tooltip) font size.
*/
public static int INSTRUCTION_HINT_FONT_SIZE_DEFAULT=18;
/**
* The key name for the canvas width size.
*/
public static final String CANVAS_WIDTH_SIZE="canvas_width_size";
/**
* The default key value of the canvas width size.
*/
public static int CANVAS_WIDTH_SIZE_DEFAULT=5;
/**
* The key name for the display id.
*/
public static final String DISPLAY_ID="display_id";
/**
* The default key value of the canvas width size.
*/
public static int DISPLAY_ID_DEFAULT = 0;
/**
* Screen id. Use this constant to run the test on a secondary monitor,
* 0 means the default monitor and 1 means the secondary monitor.
*/
public static int ScreenId = 0;
/**
* Flag for the old syntax. Prior to version 1.2.0, we use special shapes to represent each action.
*/
public static boolean UseOldSyntax=false;
/**
* Desktop input events
*/
public enum DesktopEvent {
LEFT_CLICK, RIGHT_CLICK, DOUBLE_CLICK, DRAG_N_DROP, KEYBOARD_TYPING, LAUNCH_BROWSER,
EXIST, NOT_EXIST, WAIT
}
/**
* Running modes
*/
public static boolean AUTOMATION_MODE=false;
public static boolean HELP_MODE=false;
public static boolean TUTORIAL_MODE=false;
public static boolean DEVELOPMENT_MODE=false;
/**
* Execution start time in milliseconds.
*/
public static long Execution_Start_Time;
/**
* Tutorial mode previous step.
*/
public static boolean IsPreviousStep=false;
/**
* Tutorial mode next step.
*/
public static boolean IsNextStep=false;
/**
* Wait action.
*/
public static boolean IsWaitAction=false;
/**
* Total steps in the tutorial mode
*/
public static int Steps_Total=0;
/**
* Tutorial mode navigation status
*/
public enum NavigationStatus {
NEXT, PREVIOUS
}
/**
* The total screen width of the connected screens. This value is used by the global mouse listeners to
* find the location of the x mouse events.
*/
public static int Total_Screen_Width = 0;
}
| src/main/java/org/sikuli/slides/utils/Constants.java | /**
* @author Khalid Alharbi
*/
package org.sikuli.slides.utils;
import java.io.File;
/**
* This class contains constants.
*/
public class Constants {
/**
* The working directory absolute path.
* This holds the sikuli slides working directory in the operating system's temp directory.
*/
public static String workingDirectoryPath;
/**
* The current project directory name that contains the imported and extracted .pptx file.
*/
public static String projectDirectory;
/**
* The relative directory path to the embedding resources icons for the GUIs.
*/
public static final String RESOURCES_ICON_DIR="/org/sikuli/slides/gui/icons/";
/**
* The name of the directory that sikuli-slides creates in the operating system's tmp directory.
*/
public static final String SIKULI_SLIDES_ROOT_DIRECTORY="org.sikuli.SikuliSlides";
/**
* The name of the directory that contains all sikuli related files in the .pptx file.
*/
public static final String SIKULI_DIRECTORY=File.separator+"sikuli";
/**
* The name of the directory that contains the downloaded files.
*/
public static final String SIKULI_DOWNLOAD_DIRECTORY=File.separator+"download";
/**
* The name of the images directory that contains the cropped target images.
*/
public static final String IMAGES_DIRECTORY=File.separator+"images";
/**
* The slides directory that contains the XML files for each slide in the .pptx file.
*/
public static final String SLIDES_DIRECTORY=File.separator+"ppt"+File.separator+"slides";
/**
* The slides directory that contains the media files for each slide in the .pptx file.
*/
public static final String MEDIA_DIRECTORY=File.separator+"ppt"+File.separator+"media";
/**
* The slides directory that contains the slide notes.
*/
public static final String SLIDE_NOTES_DIRECTORY=File.separator+"ppt"+File.separator+"notesSlides";
/**
* The presentaion.xml absolute path name.
*/
public static final String PRESENTATION_DIRECTORY=File.separator+"ppt"+File.separator+"presentation.xml";
/**
* The relationship directory that contains info about the duplicated media files in the presentation slides.
*/
public static final String RELATIONSHIP_DIRECTORY=File.separator+"ppt"+File.separator+"slides"+File.separator+"_rels";
/**
* The key name for maximum wait time to find target on the screen.
*/
public static final String MAX_WAIT_TIME_MS = "max_wait_time_ms";
/**
* The default key value for maximum wait time in milliseconds to find target on the screen.
*/
public static int MAX_WAIT_TIME_MS_DEFAULT = 15000;
/**
* The key name for the score value that controls how fuzzy the image search is. A value of 1 means the search
* is very precise and less fuzzy. This is defined as minscore in the API
*/
public static final String PRECISE_SEARCH_SCORE = "precise_search_score";
/**
* The default key value for the score value that controls how fuzzy the image search is
*/
public static final double PRECISE_SEARCH_SCORE_DEFAULT = 0.7;
/**
* The key name for the time to display a label on the screen.
*/
public static final String LABEL_DISPLAY_TIME_SEC = "label_display_time_sec";
/**
* The default key value for the time, in seconds, to display a label on the screen.
*/
public static final int LABEL_DISPLAY_TIME_SEC_DEFAULT = 3;
/**
* The key name for the instruction hint (tooltip) font size.
*/
public static final String INSTRUCTION_HINT_FONT_SIZE="instruction_hint_font_size";
/**
* The default key value of the instruction hint (tooltip) font size.
*/
public static int INSTRUCTION_HINT_FONT_SIZE_DEFAULT=18;
/**
* The key name for the canvas width size.
*/
public static final String CANVAS_WIDTH_SIZE="canvas_width_size";
/**
* The default key value of the canvas width size.
*/
public static int CANVAS_WIDTH_SIZE_DEFAULT=5;
/**
* The key name for the display id.
*/
public static final String DISPLAY_ID="display_id";
/**
* The default key value of the canvas width size.
*/
public static int DISPLAY_ID_DEFAULT = 0;
/**
* Screen id. Use this constant to run the test on a secondary monitor,
* 0 means the default monitor and 1 means the secondary monitor.
*/
public static int ScreenId = 0;
/**
* Flag for the old syntax. Prior to version 1.2.0, we use special shapes to represent each action.
*/
public static boolean UseOldSyntax=false;
/**
* Desktop input events
*/
public enum DesktopEvent {
LEFT_CLICK, RIGHT_CLICK, DOUBLE_CLICK, DRAG_N_DROP, KEYBOARD_TYPING, LAUNCH_BROWSER,
EXIST, NOT_EXIST, WAIT
}
/**
* Running modes
*/
public static boolean ACTION_MODE=false;
public static boolean HELP_MODE=false;
public static boolean TUTORIAL_MODE=false;
public static boolean DEVELOPMENT_MODE=false;
/**
* Execution start time in milliseconds.
*/
public static long Execution_Start_Time;
/**
* Tutorial mode previous step.
*/
public static boolean IsPreviousStep=false;
/**
* Tutorial mode next step.
*/
public static boolean IsNextStep=false;
/**
* Wait action.
*/
public static boolean IsWaitAction=false;
/**
* Total steps in the tutorial mode
*/
public static int Steps_Total=0;
/**
* Tutorial mode navigation status
*/
public enum NavigationStatus {
NEXT, PREVIOUS
}
}
| add a constant for the total width of all connected screens
| src/main/java/org/sikuli/slides/utils/Constants.java | add a constant for the total width of all connected screens | <ide><path>rc/main/java/org/sikuli/slides/utils/Constants.java
<ide> /**
<ide> * Running modes
<ide> */
<del> public static boolean ACTION_MODE=false;
<add> public static boolean AUTOMATION_MODE=false;
<ide> public static boolean HELP_MODE=false;
<ide> public static boolean TUTORIAL_MODE=false;
<ide> public static boolean DEVELOPMENT_MODE=false;
<ide> public enum NavigationStatus {
<ide> NEXT, PREVIOUS
<ide> }
<add> /**
<add> * The total screen width of the connected screens. This value is used by the global mouse listeners to
<add> * find the location of the x mouse events.
<add> */
<add> public static int Total_Screen_Width = 0;
<ide> } |
|
Java | apache-2.0 | 66076b81056a00a8e9d20a6384413c46f1f6608d | 0 | kantega/Flyt-cms,kantega/Flyt-cms,kantega/Flyt-cms | package no.kantega.publishing.plugin.provider;
import no.kantega.publishing.api.plugin.OpenAksessPlugin;
import no.kantega.publishing.spring.RuntimeMode;
import org.apache.commons.io.IOUtils;
import org.kantega.jexmec.ClassLoaderProvider;
import org.kantega.jexmec.jarfiles.EmbeddedLibraryPluginClassLoader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.Characters;
import javax.xml.stream.events.EndElement;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;
import java.io.*;
import java.net.JarURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.*;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import static java.util.Collections.singleton;
/**
*
*/
public class PluginHotDeployProvider implements ClassLoaderProvider {
private static final Logger log = LoggerFactory.getLogger(PluginHotDeployProvider.class);
private ClassLoaderProvider.Registry registry;
private File pluginWorkDirectory;
private Map<String, DeployedPlugin> loaders = new HashMap<>();
private Logger logger = LoggerFactory.getLogger(getClass());
private ClassLoader parentClassLoader;
private File installedPluginsDirectory;
@Autowired
private RuntimeMode runtimeMode;
public void deploy(PluginInfo pluginInfo) throws IOException {
DeployedPlugin deployedPlugin = loaders.get(pluginInfo.getKey());
if (deployedPlugin != null) {
// Undeploy existing version first
undeployPlugin(deployedPlugin.getPluginInfo());
// Remove old plugin file if installed, but not if same file
if (isInstalled(deployedPlugin.getPluginInfo())
&& isInstalled(pluginInfo)
&& !deployedPlugin.getPluginInfo().getSource().equals(pluginInfo.getSource())) {
deployedPlugin.getPluginInfo().getSource().delete();
}
}
logger.info("Adding classloader for plugin " + pluginInfo.getKey() + " from source " + pluginInfo.getSource().getAbsolutePath());
ClassLoader parentClassLoader = getParentClassLoader(pluginInfo);
ClassLoader loader = createClassLoader(pluginInfo, parentClassLoader);
registry.add(singleton(loader));
loaders.put(pluginInfo.getKey(), new DeployedPlugin(loader, pluginInfo));
}
private ClassLoader createClassLoader(PluginInfo pluginInfo, ClassLoader parentClassLoader) {
if(runtimeMode == RuntimeMode.PRODUCTION || pluginInfo.getCompileClasspath() == null) {
ClassLoader loader = pluginInfo.getSource().isFile() ?
new EmbeddedLibraryPluginClassLoader(pluginInfo.getSource(), parentClassLoader, pluginWorkDirectory) :
new EmbeddedLibraryPluginClassLoader(pluginInfo.getSource(), parentClassLoader);
if (pluginInfo.getResourceDirectory() != null && pluginInfo.getResourceDirectory().exists() && pluginInfo.getResourceDirectory().isDirectory()) {
loader = new ResourceDirectoryPreferringClassLoader(loader, pluginInfo.getResourceDirectory());
}
return loader;
} else {
JavaCompilingPluginClassLoader loader = new JavaCompilingPluginClassLoader(pluginInfo, parentClassLoader);
loader.compileJava();
return loader;
}
}
private ClassLoader getParentClassLoader(PluginInfo pluginInfo) {
Set<ClassLoader> delegates = new HashSet<>();
for (String dep : pluginInfo.getDependencies()) {
if (loaders.containsKey(dep)) {
delegates.add(loaders.get(dep).getClassLoader());
}
}
if (delegates.isEmpty()) {
return parentClassLoader;
} else {
return new ResourceHidingClassLoader(new DelegateClassLoader(parentClassLoader, delegates), OpenAksessPlugin.class);
}
}
private boolean isInstalled(PluginInfo pluginInfo) {
return pluginInfo.getSource().getParentFile().equals(installedPluginsDirectory);
}
public void undeployPlugin(PluginInfo pluginInfo) {
logger.info("Undeploying plugin " + pluginInfo.getKey());
DeployedPlugin deployedPlugin = loaders.get(pluginInfo.getKey());
if(deployedPlugin == null) {
log.info("Can't undeploy plugin with key " + pluginInfo.getKey() +". No such plugin is currently deployed.");
} else {
ClassLoader classLoader = deployedPlugin.getClassLoader();
closeClassLoader(classLoader);
registry.remove(singleton(classLoader));
loaders.remove(pluginInfo.getKey());
}
}
private void closeClassLoader(ClassLoader classLoader) {
if(classLoader instanceof URLClassLoader) {
URL[] urls = ((URLClassLoader) classLoader).getURLs();
Set<JarFile> closables = new LinkedHashSet<>();
for(URL url : urls) {
if(url.getFile().endsWith(".jar")) {
try {
URL jarURL = new URL("jar:" + url.toExternalForm() + "!/");
JarURLConnection urlConnection = (JarURLConnection) jarURL.openConnection();
JarFile jarFile = urlConnection.getJarFile();
closables.add(jarFile);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
for(JarFile file : closables) {
try {
file.close();
} catch (IOException e) {
log.error("", e);
}
}
}
}
public void start(Registry registry, ClassLoader parentClassLoader) {
this.registry = registry;
this.parentClassLoader = parentClassLoader;
deployInstalledPlugins();
}
public SortedMap<String, PluginInfo> getDeployedPluginKeys() {
TreeMap<String, PluginInfo> map = new TreeMap<>();
for (Map.Entry<String, DeployedPlugin> entry : this.loaders.entrySet()) {
map.put(entry.getKey(), entry.getValue().getPluginInfo());
}
return map;
}
private void deployInstalledPlugins() {
List<PluginInfo> plugins = sortByDependencies(findInstalledPlugins());
if (plugins.size() > 0) {
logger.info("About to deploy " + plugins.size() + " plugins in the following order:");
for (int i = 0; i < plugins.size(); i++) {
PluginInfo pluginInfo = plugins.get(i);
logger.info(i +": " + pluginInfo.getKey() + " '" + pluginInfo.getName() +"'");
}
for (PluginInfo info : plugins) {
try {
deploy(info);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
private List<PluginInfo> sortByDependencies(Map<String, PluginInfo> plugins) {
Map<String, Boolean> colors = new HashMap<>();
List<PluginInfo> sorted = new LinkedList<>();
for (PluginInfo info : plugins.values()) {
if (!colors.containsKey(info.getKey()))
dfs(info, plugins, colors, sorted);
}
return sorted;
}
private void dfs(PluginInfo info, Map<String, PluginInfo> plugins, Map<String, Boolean> colors, List<PluginInfo> sorted) {
colors.put(info.getKey(), Boolean.FALSE);
for (String dep : info.getDependencies()) {
if (plugins.containsKey(dep) && !colors.containsKey(dep)) {
dfs(plugins.get(dep), plugins, colors, sorted);
}
}
colors.put(info.getKey(), Boolean.TRUE);
sorted.add(info);
}
public void uninstallPlugin(String key) {
DeployedPlugin deployedPlugin = loaders.get(key);
if (deployedPlugin != null) {
PluginInfo pluginInfo = deployedPlugin.getPluginInfo();
logger.info("Removing plugin " + key);
undeployPlugin(pluginInfo);
logger.info("Uninstalling plugin " + key);
if (pluginInfo.getSource().getParentFile().equals(installedPluginsDirectory)) {
pluginInfo.getSource().delete();
}
}
}
public File installPlugin(String filename, InputStream inputStream) {
installedPluginsDirectory.mkdirs();
try {
File file = new File(installedPluginsDirectory, filename);
FileOutputStream output = new FileOutputStream(file);
IOUtils.copy(inputStream, output);
output.close();
return file;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private Map<String, PluginInfo> findInstalledPlugins() {
Map<String, PluginInfo> pluginFiles = new HashMap<>();
if (installedPluginsDirectory.exists()) {
File[] jars = installedPluginsDirectory.listFiles(new FileFilter() {
public boolean accept(File file) {
return file.getName().endsWith(".jar");
}
});
if (jars != null) {
for (File jar : jars) {
PluginInfo info = parsePluginInfo(jar);
pluginFiles.put(info.getKey(), info);
}
}
}
return pluginFiles;
}
public PluginInfo parsePluginInfo(File jar) {
try {
PluginInfo pluginInfo = null;
String name = null;
String description = null;
Set<String> dependencies = new HashSet<>();
JarFile jarFile = new JarFile(jar);
try {
Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
String prefix = "META-INF/maven/";
String propSuffix = "/pom.properties";
String xmlSuffix = "/pom.xml";
if (entry.getName().startsWith(prefix) && entry.getName().endsWith(propSuffix)) {
Properties props = new Properties();
InputStream inputStream = jarFile.getInputStream(entry);
props.load(inputStream);
inputStream.close();
pluginInfo = new PluginInfo(jar, props.getProperty("groupId"),
props.getProperty("artifactId"),
props.getProperty("version"));
break;
} else if (entry.getName().startsWith(prefix) && entry.getName().endsWith(xmlSuffix)) {
XMLInputFactory xmlInput = XMLInputFactory.newFactory();
try {
InputStream inputStream = jarFile.getInputStream(entry);
XMLEventReader reader = xmlInput.createXMLEventReader(inputStream);
int level = 0;
boolean inDependencies = false;
boolean inDependency = false;
String groupId = null;
String artifactId = null;
while (reader.hasNext()) {
XMLEvent xmlEvent = reader.nextEvent();
if (xmlEvent.getEventType() == XMLEvent.START_ELEMENT) {
level++;
StartElement e = (StartElement) xmlEvent;
String localPart = e.getName().getLocalPart();
if (level == 2 && "name".equals(localPart)) {
name = readTextContent(reader);
} else if (level == 2 && "description".equals(localPart)) {
description = readTextContent(reader);
} else if (level == 2 && "dependencies".equals(localPart)) {
inDependencies = true;
} else if (level == 3 && inDependencies && "dependency".equals(localPart)) {
inDependency = true;
} else if (level == 4 && inDependency && "groupId".equals(localPart)) {
groupId = readTextContent(reader);
} else if (level == 4 && inDependency && "artifactId".equals(localPart)) {
artifactId = readTextContent(reader);
}
if (pluginInfo != null && pluginInfo.getName() != null && pluginInfo.getDescription() != null) {
break;
}
}
if (xmlEvent.getEventType() == XMLEvent.END_ELEMENT) {
EndElement e = (EndElement) xmlEvent;
String localPart = e.getName().getLocalPart();
if (level == 2 && "dependencies".equals(localPart)) {
inDependencies = false;
} else if (level == 3 && "dependency".equals(localPart)) {
inDependency = false;
dependencies.add(groupId + ":" + artifactId);
}
level--;
}
}
inputStream.close();
} catch (XMLStreamException e) {
throw new RuntimeException(e);
}
}
}
if (pluginInfo == null) {
throw new IllegalArgumentException("Plugin file " + jar.getAbsolutePath() + " did not contain expected file META-INF/maven/groupId/artifactId/pom.properties");
}
pluginInfo.setName(name);
pluginInfo.setDescription(description);
pluginInfo.setDependencies(dependencies);
} finally {
jarFile.close();
}
return pluginInfo;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private String readTextContent(XMLEventReader reader) throws XMLStreamException {
StringBuilder sb = new StringBuilder();
while (reader.hasNext()) {
XMLEvent next = reader.peek();
if (next.getEventType() == XMLEvent.CHARACTERS) {
next = reader.nextEvent();
sb.append(((Characters) next).getData());
} else if (next.getEventType() == XMLEvent.END_ELEMENT) {
break;
}
}
return sb.toString();
}
public void stop() {
Set<ClassLoader> classLoaders = new HashSet<ClassLoader>();
for (DeployedPlugin plugin : loaders.values()) {
classLoaders.add(plugin.getClassLoader());
}
registry.remove(classLoaders);
loaders.clear();
}
public void setPluginWorkDirectory(File pluginWorkDirectory) {
this.pluginWorkDirectory = pluginWorkDirectory;
}
public void setInstalledPluginsDirectory(File installedPluginsDirectory) {
this.installedPluginsDirectory = installedPluginsDirectory;
}
private class ResourceDirectoryPreferringClassLoader extends ClassLoader {
private final File resourceDirectory;
public ResourceDirectoryPreferringClassLoader(ClassLoader parentClassLoader, File resourceDirectory) {
super(parentClassLoader);
this.resourceDirectory = resourceDirectory;
}
@Override
public URL getResource(String path) {
File local = new File(resourceDirectory, path);
if (local.exists()) {
try {
return local.toURI().toURL();
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
return super.getResource(path);
}
@Override
public InputStream getResourceAsStream(String path) {
File local = new File(resourceDirectory, path);
if (local.exists()) {
try {
return local.toURI().toURL().openStream();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return super.getResourceAsStream(path);
}
}
private class DeployedPlugin {
private PluginInfo pluginInfo;
private ClassLoader classLoader;
DeployedPlugin(ClassLoader classLoader, PluginInfo pluginInfo) {
this.classLoader = classLoader;
this.pluginInfo = pluginInfo;
}
public ClassLoader getClassLoader() {
return classLoader;
}
public PluginInfo getPluginInfo() {
return pluginInfo;
}
}
private class DelegateClassLoader extends ClassLoader {
private final Set<ClassLoader> delegates;
public DelegateClassLoader(ClassLoader parentClassLoader, Set<ClassLoader> delegates) {
super(parentClassLoader);
this.delegates = delegates;
}
@Override
public Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
try {
return getParent().loadClass(name);
} catch (ClassNotFoundException e) {
for (ClassLoader delegate : delegates) {
try {
return delegate.loadClass(name);
} catch (ClassNotFoundException e1) {
}
}
throw new ClassNotFoundException(name);
}
}
@Override
protected URL findResource(String name) {
URL resource = getParent().getResource(name);
if (resource != null) {
return resource;
}
for (ClassLoader delegate : delegates) {
resource = delegate.getResource(name);
if (resource != null) {
return resource;
}
}
return null;
}
@Override
protected Enumeration<URL> findResources(String name) throws IOException {
Enumeration<URL> parentResources = getParent().getResources(name);
List<URL> delegateResources = null;
for (ClassLoader delegate : delegates) {
Enumeration<URL> resources = delegate.getResources(name);
if(resources != null ) {
if(delegateResources == null) {
delegateResources = new LinkedList<>();
}
delegateResources.addAll(Collections.list(resources));
}
}
if(delegateResources == null) {
return parentResources;
} else {
LinkedList<URL> urls = new LinkedList<>();
if(parentResources != null) {
urls.addAll(Collections.list(parentResources));
}
urls.addAll(delegateResources);
return Collections.enumeration(urls);
}
}
}
class ResourceHidingClassLoader extends ClassLoader {
private final String[] localResourcePrefixes;
/**
* Creates a ResourceHidingClassLoader hiding resources in <code>META-INF/services/PluginName/</code> and
* <code>META-INF/services/com.example.PluginName/</code>.
*
* @param parent the parent class loader
* @param pluginClass the plugin class to hide resources for.
*/
public ResourceHidingClassLoader(ClassLoader parent, Class pluginClass) {
super(parent);
localResourcePrefixes = new String[]{"META-INF/services/" + pluginClass.getSimpleName() + "/",
"META-INF/services/" + pluginClass.getName() + "/"};
}
@Override
public InputStream getResourceAsStream(String name) {
final URL resource = getResource(name);
try {
return resource == null ? null : resource.openStream();
} catch (IOException e) {
return null;
}
}
@Override
public URL getResource(String name) {
if (isLocalResource(name)) {
return super.findResource(name);
} else {
return super.getResource(name);
}
}
@Override
public Enumeration<URL> getResources(String name) throws IOException {
if (isLocalResource(name)) {
return super.findResources(name);
} else {
return super.getResources(name);
}
}
protected boolean isLocalResource(String name) {
for (String localResourcePrefix : localResourcePrefixes) {
if (name.startsWith(localResourcePrefix)) {
return true;
}
}
return false;
}
}
}
| modules/core/src/java/no/kantega/publishing/plugin/provider/PluginHotDeployProvider.java | package no.kantega.publishing.plugin.provider;
import no.kantega.publishing.api.plugin.OpenAksessPlugin;
import no.kantega.publishing.spring.RuntimeMode;
import org.apache.commons.io.IOUtils;
import org.kantega.jexmec.ClassLoaderProvider;
import org.kantega.jexmec.jarfiles.EmbeddedLibraryPluginClassLoader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.Characters;
import javax.xml.stream.events.EndElement;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;
import java.io.*;
import java.net.JarURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.*;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import static java.util.Collections.singleton;
/**
*
*/
public class PluginHotDeployProvider implements ClassLoaderProvider {
private static final Logger log = LoggerFactory.getLogger(PluginHotDeployProvider.class);
private ClassLoaderProvider.Registry registry;
private File pluginWorkDirectory;
private Map<String, DeployedPlugin> loaders = new HashMap<String, DeployedPlugin>();
private Logger logger = LoggerFactory.getLogger(getClass());
private ClassLoader parentClassLoader;
private File installedPluginsDirectory;
@Autowired
private RuntimeMode runtimeMode;
public void deploy(PluginInfo pluginInfo) throws IOException {
DeployedPlugin deployedPlugin = loaders.get(pluginInfo.getKey());
if (deployedPlugin != null) {
// Undeploy existing version first
undeployPlugin(deployedPlugin.getPluginInfo());
// Remove old plugin file if installed, but not if same file
if (isInstalled(deployedPlugin.getPluginInfo())
&& isInstalled(pluginInfo)
&& !deployedPlugin.getPluginInfo().getSource().equals(pluginInfo.getSource())) {
deployedPlugin.getPluginInfo().getSource().delete();
}
}
logger.info("Adding classloader for plugin " + pluginInfo.getKey() + " from source " + pluginInfo.getSource().getAbsolutePath());
ClassLoader parentClassLoader = getParentClassLoader(pluginInfo);
ClassLoader loader = createClassLoader(pluginInfo, parentClassLoader);
registry.add(singleton(loader));
loaders.put(pluginInfo.getKey(), new DeployedPlugin(loader, pluginInfo));
}
private ClassLoader createClassLoader(PluginInfo pluginInfo, ClassLoader parentClassLoader) {
if(runtimeMode == RuntimeMode.PRODUCTION || pluginInfo.getCompileClasspath() == null) {
ClassLoader loader = pluginInfo.getSource().isFile() ?
new EmbeddedLibraryPluginClassLoader(pluginInfo.getSource(), parentClassLoader, pluginWorkDirectory) :
new EmbeddedLibraryPluginClassLoader(pluginInfo.getSource(), parentClassLoader);
if (pluginInfo.getResourceDirectory() != null && pluginInfo.getResourceDirectory().exists() && pluginInfo.getResourceDirectory().isDirectory()) {
loader = new ResourceDirectoryPreferringClassLoader(loader, pluginInfo.getResourceDirectory());
}
return loader;
} else {
JavaCompilingPluginClassLoader loader = new JavaCompilingPluginClassLoader(pluginInfo, parentClassLoader);
loader.compileJava();
return loader;
}
}
private ClassLoader getParentClassLoader(PluginInfo pluginInfo) {
Set<ClassLoader> delegates = new HashSet<ClassLoader>();
for (String dep : pluginInfo.getDependencies()) {
if (loaders.containsKey(dep)) {
delegates.add(loaders.get(dep).getClassLoader());
}
}
if (delegates.isEmpty()) {
return parentClassLoader;
} else {
return new ResourceHidingClassLoader(new DelegateClassLoader(parentClassLoader, delegates), OpenAksessPlugin.class);
}
}
private boolean isInstalled(PluginInfo pluginInfo) {
return pluginInfo.getSource().getParentFile().equals(installedPluginsDirectory);
}
public void undeployPlugin(PluginInfo pluginInfo) {
logger.info("Undeploying plugin " + pluginInfo.getKey());
DeployedPlugin deployedPlugin = loaders.get(pluginInfo.getKey());
if(deployedPlugin == null) {
log.info("Can't undeploy plugin with key " + pluginInfo.getKey() +". No such plugin is currently deployed.");
} else {
ClassLoader classLoader = deployedPlugin.getClassLoader();
closeClassLoader(classLoader);
registry.remove(singleton(classLoader));
loaders.remove(pluginInfo.getKey());
}
}
private void closeClassLoader(ClassLoader classLoader) {
if(classLoader instanceof URLClassLoader) {
URL[] urls = ((URLClassLoader) classLoader).getURLs();
Set<JarFile> closables = new LinkedHashSet<JarFile>();
for(URL url : urls) {
if(url.getFile().endsWith(".jar")) {
try {
URL jarURL = new URL("jar:" + url.toExternalForm() + "!/");
JarURLConnection urlConnection = (JarURLConnection) jarURL.openConnection();
JarFile jarFile = urlConnection.getJarFile();
closables.add(jarFile);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
for(JarFile file : closables) {
try {
file.close();
} catch (IOException e) {
log.error("", e);
}
}
}
}
public void start(Registry registry, ClassLoader parentClassLoader) {
this.registry = registry;
this.parentClassLoader = parentClassLoader;
deployInstalledPlugins();
}
public SortedMap<String, PluginInfo> getDeployedPluginKeys() {
TreeMap<String, PluginInfo> map = new TreeMap<String, PluginInfo>();
for (Map.Entry<String, DeployedPlugin> entry : this.loaders.entrySet()) {
map.put(entry.getKey(), entry.getValue().getPluginInfo());
}
return map;
}
private void deployInstalledPlugins() {
List<PluginInfo> plugins = sortByDependencies(findInstalledPlugins());
logger.info("About to deploy " + plugins.size() + " plugins in the following order:");
for (int i = 0; i < plugins.size(); i++) {
PluginInfo pluginInfo = plugins.get(i);
logger.info(i +": " + pluginInfo.getKey() + " '" + pluginInfo.getName() +"'");
}
for (PluginInfo info : plugins) {
try {
deploy(info);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
private List<PluginInfo> sortByDependencies(Map<String, PluginInfo> plugins) {
Map<String, Boolean> colors = new HashMap<String, Boolean>();
List<PluginInfo> sorted = new LinkedList<PluginInfo>();
for (PluginInfo info : plugins.values()) {
if (!colors.containsKey(info.getKey()))
dfs(info, plugins, colors, sorted);
}
return sorted;
}
private void dfs(PluginInfo info, Map<String, PluginInfo> plugins, Map<String, Boolean> colors, List<PluginInfo> sorted) {
colors.put(info.getKey(), Boolean.FALSE);
for (String dep : info.getDependencies()) {
if (plugins.containsKey(dep) && !colors.containsKey(dep)) {
dfs(plugins.get(dep), plugins, colors, sorted);
}
}
colors.put(info.getKey(), Boolean.TRUE);
sorted.add(info);
}
public void uninstallPlugin(String key) {
DeployedPlugin deployedPlugin = loaders.get(key);
if (deployedPlugin != null) {
PluginInfo pluginInfo = deployedPlugin.getPluginInfo();
logger.info("Removing plugin " + key);
undeployPlugin(pluginInfo);
logger.info("Uninstalling plugin " + key);
if (pluginInfo.getSource().getParentFile().equals(installedPluginsDirectory)) {
pluginInfo.getSource().delete();
}
}
}
public File installPlugin(String filename, InputStream inputStream) {
installedPluginsDirectory.mkdirs();
try {
File file = new File(installedPluginsDirectory, filename);
FileOutputStream output = new FileOutputStream(file);
IOUtils.copy(inputStream, output);
output.close();
return file;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private Map<String, PluginInfo> findInstalledPlugins() {
Map<String, PluginInfo> pluginFiles = new HashMap<String, PluginInfo>();
if (installedPluginsDirectory.exists()) {
File[] jars = installedPluginsDirectory.listFiles(new FileFilter() {
public boolean accept(File file) {
return file.getName().endsWith(".jar");
}
});
if (jars != null) {
for (File jar : jars) {
PluginInfo info = parsePluginInfo(jar);
pluginFiles.put(info.getKey(), info);
}
}
}
return pluginFiles;
}
public PluginInfo parsePluginInfo(File jar) {
try {
PluginInfo pluginInfo = null;
String name = null;
String description = null;
Set<String> dependencies = new HashSet<String>();
JarFile jarFile = new JarFile(jar);
try {
Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
String prefix = "META-INF/maven/";
String propSuffix = "/pom.properties";
String xmlSuffix = "/pom.xml";
if (entry.getName().startsWith(prefix) && entry.getName().endsWith(propSuffix)) {
Properties props = new Properties();
InputStream inputStream = jarFile.getInputStream(entry);
props.load(inputStream);
inputStream.close();
pluginInfo = new PluginInfo(jar, props.getProperty("groupId"),
props.getProperty("artifactId"),
props.getProperty("version"));
break;
} else if (entry.getName().startsWith(prefix) && entry.getName().endsWith(xmlSuffix)) {
XMLInputFactory xmlInput = XMLInputFactory.newFactory();
try {
InputStream inputStream = jarFile.getInputStream(entry);
XMLEventReader reader = xmlInput.createXMLEventReader(inputStream);
int level = 0;
boolean inDependencies = false;
boolean inDependency = false;
String groupId = null;
String artifactId = null;
while (reader.hasNext()) {
XMLEvent xmlEvent = reader.nextEvent();
if (xmlEvent.getEventType() == XMLEvent.START_ELEMENT) {
level++;
StartElement e = (StartElement) xmlEvent;
String localPart = e.getName().getLocalPart();
if (level == 2 && "name".equals(localPart)) {
name = readTextContent(reader);
} else if (level == 2 && "description".equals(localPart)) {
description = readTextContent(reader);
} else if (level == 2 && "dependencies".equals(localPart)) {
inDependencies = true;
} else if (level == 3 && inDependencies && "dependency".equals(localPart)) {
inDependency = true;
} else if (level == 4 && inDependency && "groupId".equals(localPart)) {
groupId = readTextContent(reader);
} else if (level == 4 && inDependency && "artifactId".equals(localPart)) {
artifactId = readTextContent(reader);
}
if (pluginInfo != null && pluginInfo.getName() != null && pluginInfo.getDescription() != null) {
break;
}
}
if (xmlEvent.getEventType() == XMLEvent.END_ELEMENT) {
EndElement e = (EndElement) xmlEvent;
String localPart = e.getName().getLocalPart();
if (level == 2 && "dependencies".equals(localPart)) {
inDependencies = false;
} else if (level == 3 && "dependency".equals(localPart)) {
inDependency = false;
dependencies.add(groupId + ":" + artifactId);
}
level--;
}
}
inputStream.close();
} catch (XMLStreamException e) {
throw new RuntimeException(e);
}
}
}
if (pluginInfo == null) {
throw new IllegalArgumentException("Plugin file " + jar.getAbsolutePath() + " did not contain expected file META-INF/maven/groupId/artifactId/pom.properties");
}
pluginInfo.setName(name);
pluginInfo.setDescription(description);
pluginInfo.setDependencies(dependencies);
} finally {
jarFile.close();
}
return pluginInfo;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private String readTextContent(XMLEventReader reader) throws XMLStreamException {
StringBuilder sb = new StringBuilder();
while (reader.hasNext()) {
XMLEvent next = reader.peek();
if (next.getEventType() == XMLEvent.CHARACTERS) {
next = reader.nextEvent();
sb.append(((Characters) next).getData());
} else if (next.getEventType() == XMLEvent.END_ELEMENT) {
break;
}
}
return sb.toString();
}
public void stop() {
Set<ClassLoader> classLoaders = new HashSet<ClassLoader>();
for (DeployedPlugin plugin : loaders.values()) {
classLoaders.add(plugin.getClassLoader());
}
registry.remove(classLoaders);
loaders.clear();
}
public void setPluginWorkDirectory(File pluginWorkDirectory) {
this.pluginWorkDirectory = pluginWorkDirectory;
}
public void setInstalledPluginsDirectory(File installedPluginsDirectory) {
this.installedPluginsDirectory = installedPluginsDirectory;
}
private class ResourceDirectoryPreferringClassLoader extends ClassLoader {
private final File resourceDirectory;
public ResourceDirectoryPreferringClassLoader(ClassLoader parentClassLoader, File resourceDirectory) {
super(parentClassLoader);
this.resourceDirectory = resourceDirectory;
}
@Override
public URL getResource(String path) {
File local = new File(resourceDirectory, path);
if (local.exists()) {
try {
return local.toURI().toURL();
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
return super.getResource(path);
}
@Override
public InputStream getResourceAsStream(String path) {
File local = new File(resourceDirectory, path);
if (local.exists()) {
try {
return local.toURI().toURL().openStream();
} catch (MalformedURLException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return super.getResourceAsStream(path);
}
}
private class DeployedPlugin {
private PluginInfo pluginInfo;
private ClassLoader classLoader;
DeployedPlugin(ClassLoader classLoader, PluginInfo pluginInfo) {
this.classLoader = classLoader;
this.pluginInfo = pluginInfo;
}
public ClassLoader getClassLoader() {
return classLoader;
}
public PluginInfo getPluginInfo() {
return pluginInfo;
}
}
private class DelegateClassLoader extends ClassLoader {
private final Set<ClassLoader> delegates;
public DelegateClassLoader(ClassLoader parentClassLoader, Set<ClassLoader> delegates) {
super(parentClassLoader);
this.delegates = delegates;
}
@Override
public Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
try {
return getParent().loadClass(name);
} catch (ClassNotFoundException e) {
for (ClassLoader delegate : delegates) {
try {
return delegate.loadClass(name);
} catch (ClassNotFoundException e1) {
}
}
throw new ClassNotFoundException(name);
}
}
@Override
protected URL findResource(String name) {
URL resource = getParent().getResource(name);
if (resource != null) {
return resource;
}
for (ClassLoader delegate : delegates) {
resource = delegate.getResource(name);
if (resource != null) {
return resource;
}
}
return null;
}
@Override
protected Enumeration<URL> findResources(String name) throws IOException {
Enumeration<URL> parentResources = getParent().getResources(name);
List<URL> delegateResources = null;
for (ClassLoader delegate : delegates) {
Enumeration<URL> resources = delegate.getResources(name);
if(resources != null ) {
if(delegateResources == null) {
delegateResources = new LinkedList<URL>();
}
delegateResources.addAll(Collections.list(resources));
}
}
if(delegateResources == null) {
return parentResources;
} else {
LinkedList<URL> urls = new LinkedList<URL>();
if(parentResources != null) {
urls.addAll(Collections.list(parentResources));
}
urls.addAll(delegateResources);
return Collections.enumeration(urls);
}
}
}
class ResourceHidingClassLoader extends ClassLoader {
private final String[] localResourcePrefixes;
/**
* Creates a ResourceHidingClassLoader hiding resources in <code>META-INF/services/PluginName/</code> and
* <code>META-INF/services/com.example.PluginName/</code>.
*
* @param parent the parent class loader
* @param pluginClass the plugin class to hide resources for.
*/
public ResourceHidingClassLoader(ClassLoader parent, Class pluginClass) {
super(parent);
localResourcePrefixes = new String[]{"META-INF/services/" + pluginClass.getSimpleName() + "/",
"META-INF/services/" + pluginClass.getName() + "/"};
}
@Override
public InputStream getResourceAsStream(String name) {
final URL resource = getResource(name);
try {
return resource == null ? null : resource.openStream();
} catch (IOException e) {
return null;
}
}
@Override
public URL getResource(String name) {
if (isLocalResource(name)) {
return super.findResource(name);
} else {
return super.getResource(name);
}
}
@Override
public Enumeration<URL> getResources(String name) throws IOException {
if (isLocalResource(name)) {
return super.findResources(name);
} else {
return super.getResources(name);
}
}
protected boolean isLocalResource(String name) {
for (String localResourcePrefix : localResourcePrefixes) {
if (name.startsWith(localResourcePrefix)) {
return true;
}
}
return false;
}
}
}
| Do not log "About to deploy 0 plugins in the following order:"
git-svn-id: 8def386c603904b39326d3fc08add479b8279298@5461 fd808399-8219-4f14-9d4c-37719d9ec93d
| modules/core/src/java/no/kantega/publishing/plugin/provider/PluginHotDeployProvider.java | Do not log "About to deploy 0 plugins in the following order:" | <ide><path>odules/core/src/java/no/kantega/publishing/plugin/provider/PluginHotDeployProvider.java
<ide>
<ide> private ClassLoaderProvider.Registry registry;
<ide> private File pluginWorkDirectory;
<del> private Map<String, DeployedPlugin> loaders = new HashMap<String, DeployedPlugin>();
<add> private Map<String, DeployedPlugin> loaders = new HashMap<>();
<ide> private Logger logger = LoggerFactory.getLogger(getClass());
<ide> private ClassLoader parentClassLoader;
<ide> private File installedPluginsDirectory;
<ide> }
<ide>
<ide> private ClassLoader getParentClassLoader(PluginInfo pluginInfo) {
<del> Set<ClassLoader> delegates = new HashSet<ClassLoader>();
<add> Set<ClassLoader> delegates = new HashSet<>();
<ide>
<ide> for (String dep : pluginInfo.getDependencies()) {
<ide> if (loaders.containsKey(dep)) {
<ide> if(classLoader instanceof URLClassLoader) {
<ide> URL[] urls = ((URLClassLoader) classLoader).getURLs();
<ide>
<del> Set<JarFile> closables = new LinkedHashSet<JarFile>();
<add> Set<JarFile> closables = new LinkedHashSet<>();
<ide>
<ide> for(URL url : urls) {
<ide> if(url.getFile().endsWith(".jar")) {
<ide> }
<ide>
<ide> public SortedMap<String, PluginInfo> getDeployedPluginKeys() {
<del> TreeMap<String, PluginInfo> map = new TreeMap<String, PluginInfo>();
<add> TreeMap<String, PluginInfo> map = new TreeMap<>();
<ide> for (Map.Entry<String, DeployedPlugin> entry : this.loaders.entrySet()) {
<ide> map.put(entry.getKey(), entry.getValue().getPluginInfo());
<ide> }
<ide> private void deployInstalledPlugins() {
<ide> List<PluginInfo> plugins = sortByDependencies(findInstalledPlugins());
<ide>
<del> logger.info("About to deploy " + plugins.size() + " plugins in the following order:");
<del> for (int i = 0; i < plugins.size(); i++) {
<del> PluginInfo pluginInfo = plugins.get(i);
<del> logger.info(i +": " + pluginInfo.getKey() + " '" + pluginInfo.getName() +"'");
<del> }
<del>
<del> for (PluginInfo info : plugins) {
<del> try {
<del> deploy(info);
<del> } catch (IOException e) {
<del> throw new RuntimeException(e);
<add> if (plugins.size() > 0) {
<add> logger.info("About to deploy " + plugins.size() + " plugins in the following order:");
<add> for (int i = 0; i < plugins.size(); i++) {
<add> PluginInfo pluginInfo = plugins.get(i);
<add> logger.info(i +": " + pluginInfo.getKey() + " '" + pluginInfo.getName() +"'");
<add> }
<add>
<add> for (PluginInfo info : plugins) {
<add> try {
<add> deploy(info);
<add> } catch (IOException e) {
<add> throw new RuntimeException(e);
<add> }
<ide> }
<ide> }
<ide> }
<ide>
<ide> private List<PluginInfo> sortByDependencies(Map<String, PluginInfo> plugins) {
<ide>
<del> Map<String, Boolean> colors = new HashMap<String, Boolean>();
<del> List<PluginInfo> sorted = new LinkedList<PluginInfo>();
<add> Map<String, Boolean> colors = new HashMap<>();
<add> List<PluginInfo> sorted = new LinkedList<>();
<ide>
<ide> for (PluginInfo info : plugins.values()) {
<ide> if (!colors.containsKey(info.getKey()))
<ide> }
<ide>
<ide> private Map<String, PluginInfo> findInstalledPlugins() {
<del> Map<String, PluginInfo> pluginFiles = new HashMap<String, PluginInfo>();
<add> Map<String, PluginInfo> pluginFiles = new HashMap<>();
<ide>
<ide> if (installedPluginsDirectory.exists()) {
<ide> File[] jars = installedPluginsDirectory.listFiles(new FileFilter() {
<ide>
<ide> String name = null;
<ide> String description = null;
<del> Set<String> dependencies = new HashSet<String>();
<add> Set<String> dependencies = new HashSet<>();
<ide>
<ide> JarFile jarFile = new JarFile(jar);
<ide> try {
<ide> if (local.exists()) {
<ide> try {
<ide> return local.toURI().toURL().openStream();
<del> } catch (MalformedURLException e) {
<del> throw new RuntimeException(e);
<ide> } catch (IOException e) {
<ide> throw new RuntimeException(e);
<ide> }
<ide> Enumeration<URL> resources = delegate.getResources(name);
<ide> if(resources != null ) {
<ide> if(delegateResources == null) {
<del> delegateResources = new LinkedList<URL>();
<add> delegateResources = new LinkedList<>();
<ide> }
<ide> delegateResources.addAll(Collections.list(resources));
<ide> }
<ide> if(delegateResources == null) {
<ide> return parentResources;
<ide> } else {
<del> LinkedList<URL> urls = new LinkedList<URL>();
<add> LinkedList<URL> urls = new LinkedList<>();
<ide> if(parentResources != null) {
<ide> urls.addAll(Collections.list(parentResources));
<ide> } |
|
Java | mit | efe509844731263199fc9415e878ff7702575024 | 0 | longbai/android-netdiag,qiniu/android-netdiag | package com.qiniu.android.netdiag;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.Locale;
import java.util.Random;
/**
* Created by bailong on 16/2/24.
*/
public final class RtmpPing implements Task{
public static final int TimeOut = -3;
public static final int NotReach = -2;
public static final int UnkownHost = -4;
public static final int HandshakeFail = -5;
public static final int Stopped = -1;
public static final int ServerVersionError = -20001;
public static final int ServerSignatureError = -20002;
public static final int ServerTimeError = -20003;
public static final int RTMP_SIG_SIZE = 1536;
private final String host;
private final int port;
private final int count;
private final Callback complete;
private boolean stopped;
private Output output;
public RtmpPing(String host, int port, int count, Output output, Callback complete) {
this.host = host;
this.port = port;
this.count = count;
this.complete = complete;
this.output = output;
}
public static Task start(String host, Output output, Callback complete){
return start(host, 1935, 2, output, complete);
}
public static Task start(String host, int port, int count
, Output output, Callback complete){
final RtmpPing t = new RtmpPing(host, port, count,output, complete);
Util.runInBack(new Runnable() {
@Override
public void run() {
t.run();
}
});
return t;
}
private void run(){
InetAddress[] addrs = null;
try {
addrs = InetAddress.getAllByName(host);
} catch (UnknownHostException e) {
e.printStackTrace();
output.write("Unknown host: " + host);
Util.runInMain(new Runnable() {
@Override
public void run() {
complete.complete(new Result(UnkownHost, "", 0, 0, 0, 0));
}
});
return;
}
final String ip = addrs[0].getHostAddress();
InetSocketAddress server = new InetSocketAddress(ip, port);
output.write("connect to " + ip + ":" + port);
int[] times = new int[count];
int index = -1;
for (int i = 0; i < count && !stopped; i++) {
long start = System.currentTimeMillis();
Socket sock;
try {
sock = connect(server, 20*1000);
} catch (IOException e) {
e.printStackTrace();
int code = NotReach;
if (e instanceof SocketTimeoutException){
code = TimeOut;
}
final int code2 = code;
Util.runInMain(new Runnable() {
@Override
public void run() {
complete.complete(new Result(code2, ip, 0, 0, 0, 0));
}
});
return;
}
long connEnd = System.currentTimeMillis();
int connect_time = (int)(connEnd -start);
try {
handshake(sock);
} catch (IOException e) {
e.printStackTrace();
Util.runInMain(new Runnable() {
@Override
public void run() {
complete.complete(new Result(HandshakeFail, ip, 0, 0, 0, 0));
}
});
return;
}finally {
try {
sock.close();
} catch (IOException e) {
e.printStackTrace();
}
}
long end = System.currentTimeMillis();
times[i] = (int)(end -start);
index = i;
output.write(String.format(Locale.getDefault(), "%d: conn:%d handshake:%d",
index, connect_time, (int)(end-start)));
try {
if (!stopped && i!=count-1 && 100>(end - start)){
Thread.sleep(100 - (end - start));
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (index == -1){
complete.complete(new Result(Stopped, ip, 0, 0, 0, 0));
return;
}
complete.complete(buildResult(times, index, ip));
}
private Result buildResult(int[] times, int index, String ip){
int sum = 0;
int min = 1000000;
int max = 0;
for (int i = 0; i <= index; i++) {
int t = times[i];
if (t > max){
max = t;
}
if (t< min){
min = t;
}
sum += t;
}
return new Result(0, ip, max, min, sum/(index+1), index+1);
}
private Socket connect(InetSocketAddress socketAddress, int timeOut) throws IOException{
Socket socket = new Socket();
socket.setTcpNoDelay(true);
socket.setSoTimeout(30*1000);
try {
socket.connect(socketAddress, timeOut);
} catch (Exception e){
socket.close();
throw e;
}
return socket;
}
private int handshake(Socket socket) throws IOException {
OutputStream out = socket.getOutputStream();
InputStream input = socket.getInputStream();
byte[] c0_c1 = c0_c1();
send_c0_c1(out, c0_c1);
byte[] s0_s1 = new byte[RTMP_SIG_SIZE+1];
boolean b = verify_s0_s1(input, s0_s1);
if (!b){
return ServerVersionError;
}
send_c2(out, s0_s1, 1);
b = verify_s2(input, s0_s1, c0_c1);
if (!b){
return ServerSignatureError;
}
return 0;
}
private static int readAll(InputStream in, byte[]buffer, int offset, int size) throws IOException {
int pos = 0;
while (pos < size) {
int ret = in.read(buffer, offset+pos, size-pos);
if (ret < 0){
return pos;
}
pos += ret;
}
return pos;
}
private static void writeAll(OutputStream outputStream, byte[] buffer, int offset, int n) throws IOException {
outputStream.write(buffer, offset, n);
outputStream.flush();
}
private static byte[] c0_c1() throws IOException {
byte[] data = new byte[RTMP_SIG_SIZE+1];
int i = 0;
data[i++] = 0x03; /* not encrypted */
//time
for (;i<5;i++){
data[i] = 0;
}
//zero
for (;i<9;i++){
data[i] = 0;
}
Random r = new Random();
for (; i < data.length; i++) {
data[i] = (byte)r.nextInt(256);
}
return data;
}
private static void send_c0_c1(OutputStream outputStream, byte[]c0_c1) throws IOException {
writeAll(outputStream, c0_c1, 0, c0_c1.length);
}
private static void send_c2(OutputStream outputStream, byte[] c2, int offset) throws IOException {
writeAll(outputStream, c2, offset, c2.length-offset);
}
private static boolean verify_s0_s1(InputStream inputStream, byte[]s0_s1) throws IOException {
int r = readAll(inputStream, s0_s1, 0, s0_s1.length);
if (r != s0_s1.length){
throw new IOException("read not complete, read "+ r);
}
byte s0 = s0_s1[0];
return s0 == 0x03;
}
private static boolean verify_s2(InputStream inputStream,
byte[] server_sig, byte[] client_sig) throws IOException {
int n = readAll(inputStream, server_sig, 1, server_sig.length-1);
if (n != server_sig.length-1) {
throw new IOException("read not complete");
}
for (int i = 1; i < server_sig.length; i++) {
if (server_sig[i] != client_sig[i]){
return false;
}
}
return true;
}
@Override
public void stop() {
stopped = true;
}
public static final class Result{
public final int code;
public final String ip;
public final int maxTime;
public final int minTime;
public final int avgTime;
public final int count;
public Result(int code, String ip, int maxTime, int minTime, int avgTime,
int count) {
this.code = code;
this.ip = ip;
this.maxTime = maxTime;
this.minTime = minTime;
this.avgTime = avgTime;
this.count = count;
}
}
public interface Callback{
void complete(Result r);
}
}
| netdiag/src/main/java/com/qiniu/android/netdiag/RtmpPing.java | package com.qiniu.android.netdiag;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.Locale;
import java.util.Random;
/**
* Created by bailong on 16/2/24.
*/
public final class RtmpPing implements Task{
public static final int TimeOut = -3;
public static final int NotReach = -2;
public static final int UnkownHost = -4;
public static final int HandshakeFail = -5;
public static final int Stopped = -1;
public static final int ServerVersionError = -20001;
public static final int ServerSignatureError = -20002;
public static final int ServerTimeError = -20003;
public static final int RTMP_SIG_SIZE = 1536;
private final String host;
private final int port;
private final int count;
private final Callback complete;
private boolean stopped;
private Output output;
public RtmpPing(String host, int port, int count, Output output, Callback complete) {
this.host = host;
this.port = port;
this.count = count;
this.complete = complete;
this.output = output;
}
public static Task start(String host, Output output, Callback complete){
return start(host, 1935, 2, output, complete);
}
public static Task start(String host, int port, int count
, Output output, Callback complete){
final RtmpPing t = new RtmpPing(host, port, count,output, complete);
Util.runInBack(new Runnable() {
@Override
public void run() {
t.run();
}
});
return t;
}
private void run(){
InetAddress[] addrs = null;
try {
addrs = InetAddress.getAllByName(host);
} catch (UnknownHostException e) {
e.printStackTrace();
output.write("Unknown host: " + host);
Util.runInMain(new Runnable() {
@Override
public void run() {
complete.complete(new Result(UnkownHost, "", 0, 0, 0, 0));
}
});
return;
}
final String ip = addrs[0].getHostAddress();
InetSocketAddress server = new InetSocketAddress(ip, port);
output.write("connect to " + ip + ":" + port);
int[] times = new int[count];
int index = -1;
for (int i = 0; i < count && !stopped; i++) {
long start = System.currentTimeMillis();
Socket sock;
try {
sock = connect(server, 20*1000);
} catch (IOException e) {
e.printStackTrace();
int code = NotReach;
if (e instanceof SocketTimeoutException){
code = TimeOut;
}
final int code2 = code;
Util.runInMain(new Runnable() {
@Override
public void run() {
complete.complete(new Result(code2, ip, 0, 0, 0, 0));
}
});
return;
}
long connEnd = System.currentTimeMillis();
int connect_time = (int)(connEnd -start);
long end = System.currentTimeMillis();
try {
handshake(sock);
} catch (IOException e) {
e.printStackTrace();
Util.runInMain(new Runnable() {
@Override
public void run() {
complete.complete(new Result(HandshakeFail, ip, 0, 0, 0, 0));
}
});
return;
}finally {
try {
sock.close();
} catch (IOException e) {
e.printStackTrace();
}
}
times[i] = (int)(end -start);
index = i;
output.write(String.format(Locale.getDefault(), "%d: conn:%d handshake:%d",
index, connect_time, (int)(end-start)));
try {
if (!stopped && i!=count-1 && 100>(end - start)){
Thread.sleep(100 - (end - start));
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (index == -1){
complete.complete(new Result(Stopped, ip, 0, 0, 0, 0));
return;
}
complete.complete(buildResult(times, index, ip));
}
private Result buildResult(int[] times, int index, String ip){
int sum = 0;
int min = 1000000;
int max = 0;
for (int i = 0; i <= index; i++) {
int t = times[i];
if (t > max){
max = t;
}
if (t< min){
min = t;
}
sum += t;
}
return new Result(0, ip, max, min, sum/(index+1), index+1);
}
private Socket connect(InetSocketAddress socketAddress, int timeOut) throws IOException{
Socket socket = new Socket();
socket.setTcpNoDelay(true);
socket.setSoTimeout(30*1000);
try {
socket.connect(socketAddress, timeOut);
} catch (Exception e){
socket.close();
throw e;
}
return socket;
}
private int handshake(Socket socket) throws IOException {
OutputStream out = socket.getOutputStream();
InputStream input = socket.getInputStream();
byte[] c0_c1 = c0_c1();
send_c0_c1(out, c0_c1);
byte[] s0_s1 = new byte[RTMP_SIG_SIZE+1];
boolean b = verify_s0_s1(input, s0_s1);
if (!b){
return ServerVersionError;
}
send_c2(out, s0_s1, 1);
b = verify_s2(input, s0_s1, c0_c1);
if (!b){
return ServerSignatureError;
}
return 0;
}
private static int readAll(InputStream in, byte[]buffer, int offset, int size) throws IOException {
int pos = 0;
while (pos < size) {
int ret = in.read(buffer, offset+pos, size-pos);
if (ret < 0){
return pos;
}
pos += ret;
}
return pos;
}
private static void writeAll(OutputStream outputStream, byte[] buffer, int offset, int n) throws IOException {
outputStream.write(buffer, offset, n);
outputStream.flush();
}
private static byte[] c0_c1() throws IOException {
byte[] data = new byte[RTMP_SIG_SIZE+1];
int i = 0;
data[i++] = 0x03; /* not encrypted */
//time
for (;i<5;i++){
data[i] = 0;
}
//zero
for (;i<9;i++){
data[i] = 0;
}
Random r = new Random();
for (; i < data.length; i++) {
data[i] = (byte)r.nextInt(256);
}
return data;
}
private static void send_c0_c1(OutputStream outputStream, byte[]c0_c1) throws IOException {
writeAll(outputStream, c0_c1, 0, c0_c1.length);
}
private static void send_c2(OutputStream outputStream, byte[] c2, int offset) throws IOException {
writeAll(outputStream, c2, offset, c2.length-offset);
}
private static boolean verify_s0_s1(InputStream inputStream, byte[]s0_s1) throws IOException {
int r = readAll(inputStream, s0_s1, 0, s0_s1.length);
if (r != s0_s1.length){
throw new IOException("read not complete, read "+ r);
}
byte s0 = s0_s1[0];
return s0 == 0x03;
}
private static boolean verify_s2(InputStream inputStream,
byte[] server_sig, byte[] client_sig) throws IOException {
int n = readAll(inputStream, server_sig, 1, server_sig.length-1);
if (n != server_sig.length-1) {
throw new IOException("read not complete");
}
for (int i = 1; i < server_sig.length; i++) {
if (server_sig[i] != client_sig[i]){
return false;
}
}
return true;
}
@Override
public void stop() {
stopped = true;
}
public static final class Result{
public final int code;
public final String ip;
public final int maxTime;
public final int minTime;
public final int avgTime;
public final int count;
public Result(int code, String ip, int maxTime, int minTime, int avgTime,
int count) {
this.code = code;
this.ip = ip;
this.maxTime = maxTime;
this.minTime = minTime;
this.avgTime = avgTime;
this.count = count;
}
}
public interface Callback{
void complete(Result r);
}
}
| rtmp ping handshaketime fixed
| netdiag/src/main/java/com/qiniu/android/netdiag/RtmpPing.java | rtmp ping handshaketime fixed | <ide><path>etdiag/src/main/java/com/qiniu/android/netdiag/RtmpPing.java
<ide> long connEnd = System.currentTimeMillis();
<ide> int connect_time = (int)(connEnd -start);
<ide>
<del> long end = System.currentTimeMillis();
<del>
<ide> try {
<ide> handshake(sock);
<ide> } catch (IOException e) {
<ide> e.printStackTrace();
<ide> }
<ide> }
<del>
<add> long end = System.currentTimeMillis();
<ide> times[i] = (int)(end -start);
<ide> index = i;
<ide> output.write(String.format(Locale.getDefault(), "%d: conn:%d handshake:%d", |
|
Java | mit | 03be0fb986543494cd19dc9ec6dec5b2f1244204 | 0 | wizzardo/Tools,wizzardo/Tools | package com.wizzardo.tools.http;
/**
* @author: wizzardo
* Date: 3/1/14
*/
public enum ContentType {
BINARY("application/octet-stream"),
JSON("application/json"),
XML("application/xml"),
JPG("image/jpeg"),
PNG("image/png"),
GIF("image/gif"),;
public final String text;
ContentType(String text) {
this.text = text;
}
}
| src/com/wizzardo/tools/http/ContentType.java | package com.wizzardo.tools.http;
/**
* @author: wizzardo
* Date: 3/1/14
*/
public enum ContentType {
BINARY("application/octet-stream"),
JSON("application/json; charset=utf-8"),
XML("text/xml; charset=utf-8"),
JPG("image/jpeg"),
PNG("image/png"),
GIF("image/gif"),;
public final String text;
ContentType(String text) {
this.text = text;
}
}
| fix content types
| src/com/wizzardo/tools/http/ContentType.java | fix content types | <ide><path>rc/com/wizzardo/tools/http/ContentType.java
<ide> */
<ide> public enum ContentType {
<ide> BINARY("application/octet-stream"),
<del> JSON("application/json; charset=utf-8"),
<del> XML("text/xml; charset=utf-8"),
<add> JSON("application/json"),
<add> XML("application/xml"),
<ide> JPG("image/jpeg"),
<ide> PNG("image/png"),
<ide> GIF("image/gif"),; |
|
Java | mit | 596193a27c43f44e1c905cb41db3ec0dcaf4d764 | 0 | ktisha/TheRPlugin,ktisha/TheRPlugin,ktisha/TheRPlugin | package com.jetbrains.ther.xdebugger;
import com.intellij.execution.ui.ConsoleView;
import com.intellij.execution.ui.ConsoleViewContentType;
import com.intellij.execution.ui.ExecutionConsole;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.xdebugger.XDebugProcess;
import com.intellij.xdebugger.XDebugSession;
import com.intellij.xdebugger.XSourcePosition;
import com.intellij.xdebugger.breakpoints.XBreakpointHandler;
import com.intellij.xdebugger.breakpoints.XBreakpointProperties;
import com.intellij.xdebugger.breakpoints.XLineBreakpoint;
import com.intellij.xdebugger.evaluation.XDebuggerEditorsProvider;
import com.jetbrains.ther.debugger.TheRDebugger;
import com.jetbrains.ther.debugger.data.TheRDebugConstants;
import com.jetbrains.ther.debugger.data.TheRStackFrame;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.util.*;
// TODO [xdbg][test]
class TheRXDebugProcess extends XDebugProcess {
@NotNull
private static final Logger LOGGER = Logger.getInstance(TheRXDebugProcess.class);
@NotNull
private final TheRDebugger myDebugger;
@NotNull
private final TheRLocationResolver myLocationResolver;
@NotNull
private final TheROutputBuffer myOutputBuffer;
@NotNull
private final Map<XSourcePositionWrapper, XLineBreakpoint<XBreakpointProperties>> myBreakpoints;
@NotNull
private final Set<XSourcePositionWrapper> myTempBreakpoints;
@NotNull
private final ConsoleView myConsole;
public TheRXDebugProcess(@NotNull final XDebugSession session,
@NotNull final TheRDebugger debugger,
@NotNull final TheRLocationResolver locationResolver,
@NotNull final TheROutputBuffer outputBuffer) {
super(session);
myDebugger = debugger;
myLocationResolver = locationResolver;
myOutputBuffer = outputBuffer;
myBreakpoints = new HashMap<XSourcePositionWrapper, XLineBreakpoint<XBreakpointProperties>>();
myTempBreakpoints = new HashSet<XSourcePositionWrapper>();
myConsole = (ConsoleView)super.createConsole();
}
@NotNull
@Override
public ExecutionConsole createConsole() {
return myConsole;
}
@NotNull
@Override
public XDebuggerEditorsProvider getEditorsProvider() {
return new TheRXDebuggerEditorsProvider();
}
@NotNull
@Override
public XBreakpointHandler<?>[] getBreakpointHandlers() {
return new XBreakpointHandler[]{new TheRXLineBreakpointHandler(this)};
}
@Override
public void sessionInitialized() {
resume();
}
@Override
public void startStepOver() {
try {
final int targetDepth = myDebugger.getStack().size();
do {
if (!advance()) return;
}
while (!isBreakpoint() && myDebugger.getStack().size() > targetDepth);
updateDebugInformation();
}
catch (final IOException e) {
LOGGER.error(e);
}
catch (final InterruptedException e) {
LOGGER.error(e);
}
}
@Override
public void startStepInto() {
try {
if (!advance()) return;
updateDebugInformation();
}
catch (final IOException e) {
LOGGER.error(e);
}
catch (final InterruptedException e) {
LOGGER.error(e);
}
}
@Override
public void startStepOut() {
try {
final int targetDepth = myDebugger.getStack().size() - 1;
do {
if (!advance()) return;
}
while (!isBreakpoint() && myDebugger.getStack().size() != targetDepth);
updateDebugInformation();
}
catch (final IOException e) {
LOGGER.error(e);
}
catch (final InterruptedException e) {
LOGGER.error(e);
}
}
@Override
public void resume() {
try {
do {
if (!advance()) return;
}
while (!isBreakpoint());
updateDebugInformation();
}
catch (final IOException e) {
LOGGER.error(e);
}
catch (final InterruptedException e) {
LOGGER.error(e);
}
}
@Override
public void runToPosition(@NotNull final XSourcePosition position) {
myTempBreakpoints.add(new XSourcePositionWrapper(position));
resume();
}
@Override
public void stop() {
myDebugger.stop();
}
public void registerBreakpoint(@NotNull final XLineBreakpoint<XBreakpointProperties> breakpoint) {
myBreakpoints.put(
new XSourcePositionWrapper(breakpoint.getSourcePosition()),
breakpoint
);
}
public void unregisterBreakpoint(@NotNull final XLineBreakpoint<XBreakpointProperties> breakpoint) {
myBreakpoints.remove(
new XSourcePositionWrapper(breakpoint.getSourcePosition())
);
}
private boolean advance() throws IOException, InterruptedException {
final boolean executed = myDebugger.advance();
printInterpreterOutput();
if (!executed) {
getSession().stop();
}
return executed;
}
private void updateDebugInformation() {
final XSourcePositionWrapper wrapper = new XSourcePositionWrapper(getCurrentDebuggerLocation());
final XLineBreakpoint<XBreakpointProperties> breakpoint = myBreakpoints.get(wrapper);
final XDebugSession session = getSession();
final TheRXSuspendContext suspendContext = new TheRXSuspendContext(myDebugger.getStack(), myLocationResolver);
if (breakpoint != null) {
if (!session
.breakpointReached(breakpoint, null, suspendContext)) { // second argument is printed to console when breakpoint is reached
resume();
}
}
else {
session.positionReached(suspendContext);
myTempBreakpoints.remove(wrapper);
}
}
private boolean isBreakpoint() {
final XSourcePositionWrapper wrapper = new XSourcePositionWrapper(getCurrentDebuggerLocation());
return myBreakpoints.containsKey(wrapper) || myTempBreakpoints.contains(wrapper);
}
private void printInterpreterOutput() {
final Queue<String> messages = myOutputBuffer.getMessages();
while (!messages.isEmpty()) {
final String message = messages.poll();
if (message != null) {
myConsole.print(message, ConsoleViewContentType.NORMAL_OUTPUT);
myConsole.print(
TheRDebugConstants.LINE_SEPARATOR,
ConsoleViewContentType.NORMAL_OUTPUT
);
}
}
}
@NotNull
private XSourcePosition getCurrentDebuggerLocation() {
final List<TheRStackFrame> stack = myDebugger.getStack();
return myLocationResolver.resolve(stack.get(stack.size() - 1).getLocation());
}
private static class XSourcePositionWrapper {
@NotNull
private final XSourcePosition myPosition;
private XSourcePositionWrapper(@NotNull final XSourcePosition position) {
myPosition = position;
}
@Override
public boolean equals(@Nullable final Object o) {
if (o == this) return true;
if (o == null || getClass() != o.getClass()) return false;
final XSourcePositionWrapper wrapper = (XSourcePositionWrapper)o;
return myPosition.getLine() == wrapper.myPosition.getLine() &&
myPosition.getFile().getPath().equals(wrapper.myPosition.getFile().getPath());
}
@Override
public int hashCode() {
return 31 * myPosition.getLine() + myPosition.getFile().getPath().hashCode();
}
}
}
| src/com/jetbrains/ther/xdebugger/TheRXDebugProcess.java | package com.jetbrains.ther.xdebugger;
import com.intellij.execution.ui.ConsoleView;
import com.intellij.execution.ui.ConsoleViewContentType;
import com.intellij.execution.ui.ExecutionConsole;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.xdebugger.XDebugProcess;
import com.intellij.xdebugger.XDebugSession;
import com.intellij.xdebugger.XSourcePosition;
import com.intellij.xdebugger.breakpoints.XBreakpointHandler;
import com.intellij.xdebugger.breakpoints.XBreakpointProperties;
import com.intellij.xdebugger.breakpoints.XLineBreakpoint;
import com.intellij.xdebugger.evaluation.XDebuggerEditorsProvider;
import com.jetbrains.ther.debugger.TheRDebugger;
import com.jetbrains.ther.debugger.data.TheRDebugConstants;
import com.jetbrains.ther.debugger.data.TheRStackFrame;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.util.*;
// TODO [xdbg][test]
class TheRXDebugProcess extends XDebugProcess {
@NotNull
private static final Logger LOGGER = Logger.getInstance(TheRXDebugProcess.class);
@NotNull
private final TheRDebugger myDebugger;
@NotNull
private final TheRLocationResolver myLocationResolver;
@NotNull
private final TheROutputBuffer myOutputBuffer;
@NotNull
private final Map<XSourcePositionWrapper, XLineBreakpoint<XBreakpointProperties>> myBreakpoints;
@NotNull
private final Set<XSourcePositionWrapper> myTempBreakpoints;
@NotNull
private final ConsoleView myConsole;
public TheRXDebugProcess(@NotNull final XDebugSession session,
@NotNull final TheRDebugger debugger,
@NotNull final TheRLocationResolver locationResolver,
@NotNull final TheROutputBuffer outputBuffer) {
super(session);
myDebugger = debugger;
myLocationResolver = locationResolver;
myOutputBuffer = outputBuffer;
myBreakpoints = new HashMap<XSourcePositionWrapper, XLineBreakpoint<XBreakpointProperties>>();
myTempBreakpoints = new HashSet<XSourcePositionWrapper>();
myConsole = (ConsoleView)super.createConsole();
}
@NotNull
@Override
public ExecutionConsole createConsole() {
return myConsole;
}
@NotNull
@Override
public XDebuggerEditorsProvider getEditorsProvider() {
return new TheRXDebuggerEditorsProvider();
}
@NotNull
@Override
public XBreakpointHandler<?>[] getBreakpointHandlers() {
return new XBreakpointHandler[]{new TheRXLineBreakpointHandler(this)};
}
@Override
public void sessionInitialized() {
resume();
}
@Override
public void startStepOver() {
try {
final int targetDepth = myDebugger.getStack().size();
do {
if (!advance()) return;
}
while (!isBreakpoint() && myDebugger.getStack().size() != targetDepth);
updateDebugInformation();
}
catch (final IOException e) {
LOGGER.error(e);
}
catch (final InterruptedException e) {
LOGGER.error(e);
}
}
@Override
public void startStepInto() {
try {
if (!advance()) return;
updateDebugInformation();
}
catch (final IOException e) {
LOGGER.error(e);
}
catch (final InterruptedException e) {
LOGGER.error(e);
}
}
@Override
public void startStepOut() {
try {
final int targetDepth = myDebugger.getStack().size() - 1;
do {
if (!advance()) return;
}
while (!isBreakpoint() && myDebugger.getStack().size() != targetDepth);
updateDebugInformation();
}
catch (final IOException e) {
LOGGER.error(e);
}
catch (final InterruptedException e) {
LOGGER.error(e);
}
}
@Override
public void resume() {
try {
do {
if (!advance()) return;
}
while (!isBreakpoint());
updateDebugInformation();
}
catch (final IOException e) {
LOGGER.error(e);
}
catch (final InterruptedException e) {
LOGGER.error(e);
}
}
@Override
public void runToPosition(@NotNull final XSourcePosition position) {
myTempBreakpoints.add(new XSourcePositionWrapper(position));
resume();
}
@Override
public void stop() {
myDebugger.stop();
}
public void registerBreakpoint(@NotNull final XLineBreakpoint<XBreakpointProperties> breakpoint) {
myBreakpoints.put(
new XSourcePositionWrapper(breakpoint.getSourcePosition()),
breakpoint
);
}
public void unregisterBreakpoint(@NotNull final XLineBreakpoint<XBreakpointProperties> breakpoint) {
myBreakpoints.remove(
new XSourcePositionWrapper(breakpoint.getSourcePosition())
);
}
private boolean advance() throws IOException, InterruptedException {
final boolean executed = myDebugger.advance();
printInterpreterOutput();
if (!executed) {
getSession().stop();
}
return executed;
}
private void updateDebugInformation() {
final XSourcePositionWrapper wrapper = new XSourcePositionWrapper(getCurrentDebuggerLocation());
final XLineBreakpoint<XBreakpointProperties> breakpoint = myBreakpoints.get(wrapper);
final XDebugSession session = getSession();
final TheRXSuspendContext suspendContext = new TheRXSuspendContext(myDebugger.getStack(), myLocationResolver);
if (breakpoint != null) {
if (!session
.breakpointReached(breakpoint, null, suspendContext)) { // second argument is printed to console when breakpoint is reached
resume();
}
}
else {
session.positionReached(suspendContext);
myTempBreakpoints.remove(wrapper);
}
}
private boolean isBreakpoint() {
final XSourcePositionWrapper wrapper = new XSourcePositionWrapper(getCurrentDebuggerLocation());
return myBreakpoints.containsKey(wrapper) || myTempBreakpoints.contains(wrapper);
}
private void printInterpreterOutput() {
final Queue<String> messages = myOutputBuffer.getMessages();
while (!messages.isEmpty()) {
final String message = messages.poll();
if (message != null) {
myConsole.print(message, ConsoleViewContentType.NORMAL_OUTPUT);
myConsole.print(
TheRDebugConstants.LINE_SEPARATOR,
ConsoleViewContentType.NORMAL_OUTPUT
);
}
}
}
@NotNull
private XSourcePosition getCurrentDebuggerLocation() {
final List<TheRStackFrame> stack = myDebugger.getStack();
return myLocationResolver.resolve(stack.get(stack.size() - 1).getLocation());
}
private static class XSourcePositionWrapper {
@NotNull
private final XSourcePosition myPosition;
private XSourcePositionWrapper(@NotNull final XSourcePosition position) {
myPosition = position;
}
@Override
public boolean equals(@Nullable final Object o) {
if (o == this) return true;
if (o == null || getClass() != o.getClass()) return false;
final XSourcePositionWrapper wrapper = (XSourcePositionWrapper)o;
return myPosition.getLine() == wrapper.myPosition.getLine() &&
myPosition.getFile().getPath().equals(wrapper.myPosition.getFile().getPath());
}
@Override
public int hashCode() {
return 31 * myPosition.getLine() + myPosition.getFile().getPath().hashCode();
}
}
}
| Debugger: stack could decrease its size while stepOver
| src/com/jetbrains/ther/xdebugger/TheRXDebugProcess.java | Debugger: stack could decrease its size while stepOver | <ide><path>rc/com/jetbrains/ther/xdebugger/TheRXDebugProcess.java
<ide> do {
<ide> if (!advance()) return;
<ide> }
<del> while (!isBreakpoint() && myDebugger.getStack().size() != targetDepth);
<add> while (!isBreakpoint() && myDebugger.getStack().size() > targetDepth);
<ide>
<ide> updateDebugInformation();
<ide> } |
|
Java | apache-2.0 | 64dc95161301e171ed606915feabb0e3ceeac82a | 0 | lxbzmy/gnucash-android,lxbzmy/gnucash-android,codinguser/gnucash-android,pnemonic78/gnucash-android | /*
* Copyright (c) 2016 Felipe Morato <[email protected]>
*
* 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.gnucash.android.test.ui;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.support.test.espresso.contrib.DrawerActions;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import android.test.ActivityInstrumentationTestCase2;
import android.util.Log;
import org.gnucash.android.R;
import org.gnucash.android.app.GnuCashApplication;
import org.gnucash.android.db.DatabaseHelper;
import org.gnucash.android.db.adapter.*;
import org.gnucash.android.model.Account;
import org.gnucash.android.model.Money;
import org.gnucash.android.model.Split;
import org.gnucash.android.model.Transaction;
import org.gnucash.android.ui.account.AccountsActivity;
import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import java.util.Currency;
import static android.support.test.InstrumentationRegistry.getInstrumentation;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.*;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.RootMatchers.withDecorView;
import static android.support.test.espresso.matcher.ViewMatchers.*;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertTrue;
import static org.gnucash.android.test.ui.AccountsActivityTest.preventFirstRunDialogs;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
@RunWith(AndroidJUnit4.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class OwnCloudExportTest {
private AccountsActivity mAccountsActivity;
private SharedPreferences mPrefs;
private String OC_SERVER = "https://demo.owncloud.org";
private String OC_USERNAME = "test";
private String OC_PASSWORD = "test";
private String OC_DIR = "gc_test";
/**
* A JUnit {@link Rule @Rule} to launch your activity under test. This is a replacement
* for {@link ActivityInstrumentationTestCase2}.
* <p>
* Rules are interceptors which are executed for each test method and will run before
* any of your setup code in the {@link Before @Before} method.
* <p>
* {@link ActivityTestRule} will create and launch of the activity for you and also expose
* the activity under test. To get a reference to the activity you can use
* the {@link ActivityTestRule#getActivity()} method.
*/
@Rule
public ActivityTestRule<AccountsActivity> mActivityRule = new ActivityTestRule<>(
AccountsActivity.class);
@Before
public void setUp() throws Exception {
mAccountsActivity = mActivityRule.getActivity();
mPrefs = mAccountsActivity.getSharedPreferences(
mAccountsActivity.getString(R.string.owncloud_pref), Context.MODE_PRIVATE);
preventFirstRunDialogs(getInstrumentation().getTargetContext());
// creates Account and transaction
String activeBookUID = BooksDbAdapter.getInstance().getActiveBookUID();
DatabaseHelper mDbHelper = new DatabaseHelper(mAccountsActivity, activeBookUID);
SQLiteDatabase mDb;
try {
mDb = mDbHelper.getWritableDatabase();
} catch (SQLException e) {
Log.e(getClass().getName(), "Error getting database: " + e.getMessage());
mDb = mDbHelper.getReadableDatabase();
}
SplitsDbAdapter mSplitsDbAdapter;
mSplitsDbAdapter = new SplitsDbAdapter(mDb);
TransactionsDbAdapter mTransactionsDbAdapter = new TransactionsDbAdapter(mDb, mSplitsDbAdapter);
AccountsDbAdapter mAccountsDbAdapter = new AccountsDbAdapter(mDb, mTransactionsDbAdapter);
mAccountsDbAdapter.deleteAllRecords();
String currencyCode = GnuCashApplication.getDefaultCurrencyCode();
Account account = new Account("ownCloud", new CommoditiesDbAdapter(mDb).getCommodity(currencyCode));
Transaction transaction = new Transaction("birds");
transaction.setTime(System.currentTimeMillis());
Split split = new Split(new Money("11.11", currencyCode), account.getUID());
transaction.addSplit(split);
transaction.addSplit(split.createPair(
mAccountsDbAdapter.getOrCreateImbalanceAccountUID(Currency.getInstance(currencyCode))));
account.addTransaction(transaction);
mAccountsDbAdapter.addRecord(account, DatabaseAdapter.UpdateMethod.insert);
SharedPreferences.Editor editor = mPrefs.edit();
editor.putBoolean(mAccountsActivity.getString(R.string.key_owncloud_sync), false).apply();
editor.putInt(mAccountsActivity.getString(R.string.key_last_export_destination), 0);
editor.apply();
}
/**
* It might fail if it takes too long to connect to the server or if there is no network
*/
@Test
public void OwnCloudCredentials() {
onView(withId(R.id.drawer_layout)).perform(DrawerActions.open());
onView(withId(R.id.nav_view)).perform(swipeUp());
onView(withText(R.string.title_settings)).perform(click());
onView(withText(R.string.header_backup_and_export_settings)).perform(click());
onView(withText("ownCloud Sync")).perform(click());
onView(withId(R.id.owncloud_hostname)).check(matches(isDisplayed()));
onView(withId(R.id.owncloud_hostname)).perform(clearText()).perform(typeText(OC_SERVER), closeSoftKeyboard());
onView(withId(R.id.owncloud_username)).perform(clearText()).perform(typeText(OC_USERNAME), closeSoftKeyboard());
onView(withId(R.id.owncloud_password)).perform(clearText()).perform(typeText(OC_PASSWORD), closeSoftKeyboard());
onView(withId(R.id.owncloud_dir)).perform(clearText()).perform(typeText(OC_DIR), closeSoftKeyboard());
onView(withId(R.id.btn_save)).perform(click());
sleep(5000);
onView(withId(R.id.btn_save)).perform(click());
assertEquals(mPrefs.getString(mAccountsActivity.getString(R.string.key_owncloud_server), null), OC_SERVER);
assertEquals(mPrefs.getString(mAccountsActivity.getString(R.string.key_owncloud_username), null), OC_USERNAME);
assertEquals(mPrefs.getString(mAccountsActivity.getString(R.string.key_owncloud_password), null), OC_PASSWORD);
assertEquals(mPrefs.getString(mAccountsActivity.getString(R.string.key_owncloud_dir), null), OC_DIR);
assertTrue(mPrefs.getBoolean(mAccountsActivity.getString(R.string.key_owncloud_sync), false));
}
@Test
public void OwnCloudExport() {
mPrefs.edit().putBoolean(mAccountsActivity.getString(R.string.key_owncloud_sync), true).commit();
onView(withId(R.id.drawer_layout)).perform(DrawerActions.open());
onView(withText(R.string.nav_menu_export)).perform(click());
onView(withId(R.id.spinner_export_destination)).perform(click());
String[] destinations = mAccountsActivity.getResources().getStringArray(R.array.export_destinations);
onView(withText(destinations[3])).perform(click());
onView(withId(R.id.menu_save)).perform(click());
// onView(withSpinnerText(
// mAccountsActivity.getResources().getStringArray(R.array.export_destinations)[3]))
// .perform(click());
assertToastDisplayed(String.format(mAccountsActivity.getString(R.string.toast_exported_to), "ownCloud -> " + OC_DIR));
}
/**
* Checks that a specific toast message is displayed
* @param toastString String that should be displayed
*/
private void assertToastDisplayed(String toastString) {
onView(withText(toastString))
.inRoot(withDecorView(not(is(mActivityRule.getActivity().getWindow().getDecorView()))))
.check(matches(isDisplayed()));
}
/**
* Sleep the thread for a specified period
* @param millis Duration to sleep in milliseconds
*/
private void sleep(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
| app/src/androidTest/java/org/gnucash/android/test/ui/OwnCloudExportTest.java | /*
* Copyright (c) 2016 Felipe Morato <[email protected]>
*
* 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.gnucash.android.test.ui;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import android.test.ActivityInstrumentationTestCase2;
import android.util.Log;
import org.gnucash.android.R;
import org.gnucash.android.app.GnuCashApplication;
import org.gnucash.android.db.DatabaseHelper;
import org.gnucash.android.db.adapter.*;
import org.gnucash.android.model.Account;
import org.gnucash.android.model.Money;
import org.gnucash.android.model.Split;
import org.gnucash.android.model.Transaction;
import org.gnucash.android.ui.settings.PreferenceActivity;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.Currency;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.Espresso.pressBack;
import static android.support.test.espresso.action.ViewActions.*;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.*;
@RunWith(AndroidJUnit4.class)
public class OwnCloudExportTest extends ActivityInstrumentationTestCase2<PreferenceActivity> {
private PreferenceActivity mPreferenceActivity;
private SharedPreferences mPrefs;
public OwnCloudExportTest() { super(PreferenceActivity.class); }
@Override
@Before
public void setUp() throws Exception {
super.setUp();
injectInstrumentation(InstrumentationRegistry.getInstrumentation());
AccountsActivityTest.preventFirstRunDialogs(getInstrumentation().getTargetContext());
mPreferenceActivity = getActivity();
// creates Account and transaction
String activeBookUID = BooksDbAdapter.getInstance().getActiveBookUID();
DatabaseHelper mDbHelper = new DatabaseHelper(getActivity(), activeBookUID);
SQLiteDatabase mDb;
try {
mDb = mDbHelper.getWritableDatabase();
} catch (SQLException e) {
Log.e(getClass().getName(), "Error getting database: " + e.getMessage());
mDb = mDbHelper.getReadableDatabase();
}
SplitsDbAdapter mSplitsDbAdapter;
mSplitsDbAdapter = new SplitsDbAdapter(mDb);
TransactionsDbAdapter mTransactionsDbAdapter = new TransactionsDbAdapter(mDb, mSplitsDbAdapter);
AccountsDbAdapter mAccountsDbAdapter = new AccountsDbAdapter(mDb, mTransactionsDbAdapter);
mAccountsDbAdapter.deleteAllRecords();
String currencyCode = GnuCashApplication.getDefaultCurrencyCode();
Account account = new Account("ownCloud", new CommoditiesDbAdapter(mDb).getCommodity(currencyCode));
Transaction transaction = new Transaction("birds");
transaction.setTime(System.currentTimeMillis());
Split split = new Split(new Money("11.11", currencyCode), account.getUID());
transaction.addSplit(split);
transaction.addSplit(split.createPair(mAccountsDbAdapter.getOrCreateImbalanceAccountUID(Currency.getInstance(currencyCode))));
account.addTransaction(transaction);
mAccountsDbAdapter.addRecord(account, DatabaseAdapter.UpdateMethod.insert);
}
@Test
public void OpenOwnCloudDialog() {
pressBack(); // The activity automatically opens General Settings. . let's go back first
onView(withText("Backup & export")).perform(click());
onView(withText("ownCloud Sync")).perform(click());
onView(withId(R.id.owncloud_hostname)).check(matches(isDisplayed()));
}
@Test
public void SetOwnCloudCredentials() {
pressBack(); // The activity automatically opens General Settings. . let's go back first
onView(withText("Backup & export")).perform(click());
onView(withText("ownCloud Sync")).perform(click());
onView(withId(R.id.owncloud_hostname)).check(matches(isDisplayed()));
String OC_SERVER = "https://demo.owncloud.org";
String OC_USERNAME = "test";
String OC_PASSWORD = "test";
String OC_DIR = "gc_test";
onView(withId(R.id.owncloud_hostname)).perform(clearText()).perform(typeText(OC_SERVER), closeSoftKeyboard());
onView(withId(R.id.owncloud_username)).perform(clearText()).perform(typeText(OC_USERNAME), closeSoftKeyboard());
onView(withId(R.id.owncloud_password)).perform(clearText()).perform(typeText(OC_PASSWORD), closeSoftKeyboard());
onView(withId(R.id.owncloud_dir)).perform(clearText()).perform(typeText(OC_DIR), closeSoftKeyboard());
onView(withId(R.id.btn_save)).perform(click());
sleep(5000);
onView(withId(R.id.btn_save)).perform(click());
mPrefs = mPreferenceActivity.getSharedPreferences(mPreferenceActivity.getString(R.string.owncloud_pref), Context.MODE_PRIVATE);
assertEquals(mPrefs.getString(mPreferenceActivity.getString(R.string.key_owncloud_server), null), OC_SERVER);
assertEquals(mPrefs.getString(mPreferenceActivity.getString(R.string.key_owncloud_username), null), OC_USERNAME);
assertEquals(mPrefs.getString(mPreferenceActivity.getString(R.string.key_owncloud_password), null), OC_PASSWORD);
assertEquals(mPrefs.getString(mPreferenceActivity.getString(R.string.key_owncloud_dir), null), OC_DIR);
}
@After
public void tearDown() throws Exception {
mPreferenceActivity.finish();
super.tearDown();
}
/**
* Sleep the thread for a specified period
* @param millis Duration to sleep in milliseconds
*/
private void sleep(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
| Tests Export to ownCloud. | app/src/androidTest/java/org/gnucash/android/test/ui/OwnCloudExportTest.java | Tests Export to ownCloud. | <ide><path>pp/src/androidTest/java/org/gnucash/android/test/ui/OwnCloudExportTest.java
<ide> import android.content.SharedPreferences;
<ide> import android.database.SQLException;
<ide> import android.database.sqlite.SQLiteDatabase;
<del>import android.support.test.InstrumentationRegistry;
<add>import android.support.test.espresso.contrib.DrawerActions;
<add>import android.support.test.rule.ActivityTestRule;
<ide> import android.support.test.runner.AndroidJUnit4;
<ide> import android.test.ActivityInstrumentationTestCase2;
<ide> import android.util.Log;
<ide> import org.gnucash.android.model.Money;
<ide> import org.gnucash.android.model.Split;
<ide> import org.gnucash.android.model.Transaction;
<del>import org.gnucash.android.ui.settings.PreferenceActivity;
<del>import org.junit.After;
<add>import org.gnucash.android.ui.account.AccountsActivity;
<ide> import org.junit.Before;
<add>import org.junit.FixMethodOrder;
<add>import org.junit.Rule;
<ide> import org.junit.Test;
<ide> import org.junit.runner.RunWith;
<add>import org.junit.runners.MethodSorters;
<ide>
<ide> import java.util.Currency;
<ide>
<add>import static android.support.test.InstrumentationRegistry.getInstrumentation;
<ide> import static android.support.test.espresso.Espresso.onView;
<del>import static android.support.test.espresso.Espresso.pressBack;
<ide> import static android.support.test.espresso.action.ViewActions.*;
<ide> import static android.support.test.espresso.assertion.ViewAssertions.matches;
<add>import static android.support.test.espresso.matcher.RootMatchers.withDecorView;
<ide> import static android.support.test.espresso.matcher.ViewMatchers.*;
<add>import static junit.framework.Assert.assertEquals;
<add>import static junit.framework.Assert.assertTrue;
<add>import static org.gnucash.android.test.ui.AccountsActivityTest.preventFirstRunDialogs;
<add>import static org.hamcrest.Matchers.is;
<add>import static org.hamcrest.Matchers.not;
<ide>
<ide>
<ide> @RunWith(AndroidJUnit4.class)
<del>public class OwnCloudExportTest extends ActivityInstrumentationTestCase2<PreferenceActivity> {
<add>@FixMethodOrder(MethodSorters.NAME_ASCENDING)
<add>public class OwnCloudExportTest {
<ide>
<del> private PreferenceActivity mPreferenceActivity;
<add> private AccountsActivity mAccountsActivity;
<ide> private SharedPreferences mPrefs;
<ide>
<del> public OwnCloudExportTest() { super(PreferenceActivity.class); }
<add> private String OC_SERVER = "https://demo.owncloud.org";
<add> private String OC_USERNAME = "test";
<add> private String OC_PASSWORD = "test";
<add> private String OC_DIR = "gc_test";
<ide>
<del> @Override
<del> @Before
<del> public void setUp() throws Exception {
<del> super.setUp();
<del> injectInstrumentation(InstrumentationRegistry.getInstrumentation());
<del> AccountsActivityTest.preventFirstRunDialogs(getInstrumentation().getTargetContext());
<add> /**
<add> * A JUnit {@link Rule @Rule} to launch your activity under test. This is a replacement
<add> * for {@link ActivityInstrumentationTestCase2}.
<add> * <p>
<add> * Rules are interceptors which are executed for each test method and will run before
<add> * any of your setup code in the {@link Before @Before} method.
<add> * <p>
<add> * {@link ActivityTestRule} will create and launch of the activity for you and also expose
<add> * the activity under test. To get a reference to the activity you can use
<add> * the {@link ActivityTestRule#getActivity()} method.
<add> */
<add> @Rule
<add> public ActivityTestRule<AccountsActivity> mActivityRule = new ActivityTestRule<>(
<add> AccountsActivity.class);
<ide>
<del> mPreferenceActivity = getActivity();
<add> @Before
<add> public void setUp() throws Exception {
<add>
<add> mAccountsActivity = mActivityRule.getActivity();
<add> mPrefs = mAccountsActivity.getSharedPreferences(
<add> mAccountsActivity.getString(R.string.owncloud_pref), Context.MODE_PRIVATE);
<add>
<add> preventFirstRunDialogs(getInstrumentation().getTargetContext());
<ide>
<ide> // creates Account and transaction
<ide> String activeBookUID = BooksDbAdapter.getInstance().getActiveBookUID();
<del> DatabaseHelper mDbHelper = new DatabaseHelper(getActivity(), activeBookUID);
<add> DatabaseHelper mDbHelper = new DatabaseHelper(mAccountsActivity, activeBookUID);
<ide> SQLiteDatabase mDb;
<ide> try {
<ide> mDb = mDbHelper.getWritableDatabase();
<ide> transaction.setTime(System.currentTimeMillis());
<ide> Split split = new Split(new Money("11.11", currencyCode), account.getUID());
<ide> transaction.addSplit(split);
<del> transaction.addSplit(split.createPair(mAccountsDbAdapter.getOrCreateImbalanceAccountUID(Currency.getInstance(currencyCode))));
<add> transaction.addSplit(split.createPair(
<add> mAccountsDbAdapter.getOrCreateImbalanceAccountUID(Currency.getInstance(currencyCode))));
<ide> account.addTransaction(transaction);
<ide>
<ide> mAccountsDbAdapter.addRecord(account, DatabaseAdapter.UpdateMethod.insert);
<ide>
<add>
<add> SharedPreferences.Editor editor = mPrefs.edit();
<add>
<add> editor.putBoolean(mAccountsActivity.getString(R.string.key_owncloud_sync), false).apply();
<add> editor.putInt(mAccountsActivity.getString(R.string.key_last_export_destination), 0);
<add> editor.apply();
<ide> }
<ide>
<add> /**
<add> * It might fail if it takes too long to connect to the server or if there is no network
<add> */
<ide> @Test
<del> public void OpenOwnCloudDialog() {
<del> pressBack(); // The activity automatically opens General Settings. . let's go back first
<del> onView(withText("Backup & export")).perform(click());
<add> public void OwnCloudCredentials() {
<add> onView(withId(R.id.drawer_layout)).perform(DrawerActions.open());
<add> onView(withId(R.id.nav_view)).perform(swipeUp());
<add> onView(withText(R.string.title_settings)).perform(click());
<add> onView(withText(R.string.header_backup_and_export_settings)).perform(click());
<ide> onView(withText("ownCloud Sync")).perform(click());
<ide> onView(withId(R.id.owncloud_hostname)).check(matches(isDisplayed()));
<del> }
<del>
<del> @Test
<del> public void SetOwnCloudCredentials() {
<del> pressBack(); // The activity automatically opens General Settings. . let's go back first
<del> onView(withText("Backup & export")).perform(click());
<del> onView(withText("ownCloud Sync")).perform(click());
<del> onView(withId(R.id.owncloud_hostname)).check(matches(isDisplayed()));
<del>
<del> String OC_SERVER = "https://demo.owncloud.org";
<del> String OC_USERNAME = "test";
<del> String OC_PASSWORD = "test";
<del> String OC_DIR = "gc_test";
<ide>
<ide> onView(withId(R.id.owncloud_hostname)).perform(clearText()).perform(typeText(OC_SERVER), closeSoftKeyboard());
<ide> onView(withId(R.id.owncloud_username)).perform(clearText()).perform(typeText(OC_USERNAME), closeSoftKeyboard());
<ide> sleep(5000);
<ide> onView(withId(R.id.btn_save)).perform(click());
<ide>
<del> mPrefs = mPreferenceActivity.getSharedPreferences(mPreferenceActivity.getString(R.string.owncloud_pref), Context.MODE_PRIVATE);
<del> assertEquals(mPrefs.getString(mPreferenceActivity.getString(R.string.key_owncloud_server), null), OC_SERVER);
<del> assertEquals(mPrefs.getString(mPreferenceActivity.getString(R.string.key_owncloud_username), null), OC_USERNAME);
<del> assertEquals(mPrefs.getString(mPreferenceActivity.getString(R.string.key_owncloud_password), null), OC_PASSWORD);
<del> assertEquals(mPrefs.getString(mPreferenceActivity.getString(R.string.key_owncloud_dir), null), OC_DIR);
<add> assertEquals(mPrefs.getString(mAccountsActivity.getString(R.string.key_owncloud_server), null), OC_SERVER);
<add> assertEquals(mPrefs.getString(mAccountsActivity.getString(R.string.key_owncloud_username), null), OC_USERNAME);
<add> assertEquals(mPrefs.getString(mAccountsActivity.getString(R.string.key_owncloud_password), null), OC_PASSWORD);
<add> assertEquals(mPrefs.getString(mAccountsActivity.getString(R.string.key_owncloud_dir), null), OC_DIR);
<ide>
<add> assertTrue(mPrefs.getBoolean(mAccountsActivity.getString(R.string.key_owncloud_sync), false));
<ide> }
<ide>
<del> @After
<del> public void tearDown() throws Exception {
<del> mPreferenceActivity.finish();
<del> super.tearDown();
<add> @Test
<add> public void OwnCloudExport() {
<add>
<add> mPrefs.edit().putBoolean(mAccountsActivity.getString(R.string.key_owncloud_sync), true).commit();
<add>
<add> onView(withId(R.id.drawer_layout)).perform(DrawerActions.open());
<add> onView(withText(R.string.nav_menu_export)).perform(click());
<add> onView(withId(R.id.spinner_export_destination)).perform(click());
<add> String[] destinations = mAccountsActivity.getResources().getStringArray(R.array.export_destinations);
<add> onView(withText(destinations[3])).perform(click());
<add> onView(withId(R.id.menu_save)).perform(click());
<add>// onView(withSpinnerText(
<add>// mAccountsActivity.getResources().getStringArray(R.array.export_destinations)[3]))
<add>// .perform(click());
<add> assertToastDisplayed(String.format(mAccountsActivity.getString(R.string.toast_exported_to), "ownCloud -> " + OC_DIR));
<add> }
<add>
<add> /**
<add> * Checks that a specific toast message is displayed
<add> * @param toastString String that should be displayed
<add> */
<add> private void assertToastDisplayed(String toastString) {
<add> onView(withText(toastString))
<add> .inRoot(withDecorView(not(is(mActivityRule.getActivity().getWindow().getDecorView()))))
<add> .check(matches(isDisplayed()));
<ide> }
<ide> /**
<ide> * Sleep the thread for a specified period |
|
Java | apache-2.0 | 72b506e924c4805389266151f1f0f9fc4c7026f9 | 0 | JETs-JP/bbhelper | package com.oracle.poco.bbhelper;
import com.oracle.poco.bbhelper.exception.BbhelperBeehive4jParallelInvocationException;
import com.oracle.poco.bbhelper.exception.BbhelperException;
import com.oracle.poco.bbhelper.exception.BbhelperValidationFailureException;
import com.oracle.poco.bbhelper.log.BbhelperLogger;
import com.oracle.poco.bbhelper.log.ErrorMessage;
import com.oracle.poco.bbhelper.log.Operation;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import java.util.List;
import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR;
@ControllerAdvice
public class ExceptionControllerAdvice extends ResponseEntityExceptionHandler {
private static final BbhelperLogger logger =
BbhelperLogger.getLogger(ExceptionControllerAdvice.class);
/**
* このクラスで明示的にハンドリングしていない例外を処理する
* 明示的にハンドリングしていない例外は、システムエラーとして固定のレスポンスを返却する
*
* @param ex 発生した例外
* @param request リクエスト
* @return レスポンス
*/
@ExceptionHandler
public ResponseEntity<Object> handleSystemException(Exception ex, WebRequest request) {
ErrorResponse error = new ErrorResponse(
INTERNAL_SERVER_ERROR.value(), INTERNAL_SERVER_ERROR.getReasonPhrase(),
"System Error", "System error is occurred.");
return super.handleExceptionInternal(ex, error, null, null, request);
}
/**
* Beehiveサーバーへの複数回のアクセスを並列実行したときの例外をハンドリングする
*
* @param ex 発生した例外を束ねる例外クラス
* @param request リクエスト
* @return レスポンス
*/
@ExceptionHandler
public ResponseEntity<Object> handleBbhelperBeehive4jParallelInvocationException(
BbhelperBeehive4jParallelInvocationException ex,
WebRequest request) {
List<BbhelperException> causes = ex.getCauses();
if (causes.size() == 1) {
return handleBbhelperException(causes.get(0), request);
}
ErrorResponse error = new ErrorResponse(
ex.getStatus().value(), ex.getStatus().getReasonPhrase(),
ex.getClass().getName(), ex.getLocalizedMessage());
causes.forEach(e -> error.addDetail(e.getLocalizedMessage()));
return super.handleExceptionInternal(ex, error, null, ex.getStatus(), request);
}
/**
* このアプリケーションで定義しているカスタム例外をハンドリングする
*
* @param ex 発生した例外
* @param request リクエスト
* @return レスポンス
*/
@ExceptionHandler
public ResponseEntity<Object> handleBbhelperException(BbhelperException ex, WebRequest request) {
ErrorResponse error = new ErrorResponse(
ex.getStatus().value(), ex.getStatus().getReasonPhrase(),
ex.getClass().getName(), ex.getLocalizedMessage());
return super.handleExceptionInternal(ex, error, null, ex.getStatus(), request);
}
/*
* 入力チェック時の例外をハンドリングするためにこのメソッドをオーバーライドする
*/
@Override
protected ResponseEntity<Object> handleBindException(
BindException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
return handleValidationFailure(ex, ex.getBindingResult(), headers, status, request);
}
/*
* 入力チェック時の例外をハンドリングするためにこのメソッドをオーバーライドする
*/
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(
MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status,
WebRequest request) {
return handleValidationFailure(ex, ex.getBindingResult(), headers, status, request);
}
private ResponseEntity<Object> handleValidationFailure(
Throwable cause, BindingResult bindingResult, HttpHeaders headers, HttpStatus status,
WebRequest request) {
BbhelperValidationFailureException bbhe =
new BbhelperValidationFailureException(cause, bindingResult);
/*
* バリデーション時の例外の処理はこの例外ハンドラにに集約するので、ロギングもここで行う。
* 個別のControllerメソッドではバリデーションのロギングは記述しない。
*/
logger.info(new ErrorMessage(Operation.VALIDATION, bbhe));
ErrorResponse error = new ErrorResponse(status.value(), status.getReasonPhrase(),
bbhe.getClass().getName(), bbhe.getLocalizedMessage());
bindingResult.getGlobalErrors().stream().forEach(
e -> error.addDetail(e.getDefaultMessage()));
bindingResult.getFieldErrors().stream().forEach(
e -> error.addDetail(e.getDefaultMessage()));
return super.handleExceptionInternal(bbhe, error, headers, status, request);
}
}
| service/src/main/java/com/oracle/poco/bbhelper/ExceptionControllerAdvice.java | package com.oracle.poco.bbhelper;
import com.oracle.poco.bbhelper.exception.BbhelperBeehive4jParallelInvocationException;
import com.oracle.poco.bbhelper.exception.BbhelperException;
import com.oracle.poco.bbhelper.exception.BbhelperValidationFailureException;
import com.oracle.poco.bbhelper.log.BbhelperLogger;
import com.oracle.poco.bbhelper.log.ErrorMessage;
import com.oracle.poco.bbhelper.log.Operation;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import java.util.List;
@ControllerAdvice
public class ExceptionControllerAdvice extends ResponseEntityExceptionHandler {
private static final BbhelperLogger logger =
BbhelperLogger.getLogger(ExceptionControllerAdvice.class);
@ExceptionHandler
public ResponseEntity<Object> handleBbhelperBeehive4jParallelInvocationException(
BbhelperBeehive4jParallelInvocationException ex,
WebRequest request) {
List<BbhelperException> causes = ex.getCauses();
if (causes.size() == 1) {
return handleExceptionInternal(
causes.get(0), null, null, causes.get(0).getStatus(), request);
}
ErrorResponse error = new ErrorResponse(
ex.getStatus().value(), ex.getStatus().getReasonPhrase(),
ex.getClass().getName(), ex.getLocalizedMessage());
causes.forEach(e -> error.addDetail(e.getLocalizedMessage()));
return super.handleExceptionInternal(ex, error, null, ex.getStatus(), request);
}
@ExceptionHandler
public ResponseEntity<Object> handleBbhelperException(BbhelperException ex, WebRequest request) {
return handleExceptionInternal(ex, null, null, ex.getStatus(), request);
}
@Override
protected ResponseEntity<Object> handleExceptionInternal(
Exception ex, Object body, HttpHeaders headers, HttpStatus status, WebRequest request) {
ErrorResponse error = new ErrorResponse(status.value(), status.getReasonPhrase(),
ex.getClass().getName(), ex.getLocalizedMessage());
return super.handleExceptionInternal(ex, error, headers, status, request);
}
@Override
protected ResponseEntity<Object> handleBindException(
BindException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
return handleValidationFailure(ex, ex.getBindingResult(), headers, status, request);
}
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(
MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status,
WebRequest request) {
return handleValidationFailure(ex, ex.getBindingResult(), headers, status, request);
}
private ResponseEntity<Object> handleValidationFailure(
Throwable cause, BindingResult bindingResult, HttpHeaders headers, HttpStatus status,
WebRequest request) {
BbhelperValidationFailureException bbhe =
new BbhelperValidationFailureException(cause, bindingResult);
/*
* バリデーション時の例外の処理はこの例外ハンドラにに集約するので、ロギングもここで行う。
* 個別のControllerメソッドではバリデーションのロギングは記述しない。
*/
logger.info(new ErrorMessage(Operation.VALIDATION, bbhe));
ErrorResponse error = new ErrorResponse(status.value(), status.getReasonPhrase(),
bbhe.getClass().getName(), bbhe.getLocalizedMessage());
bindingResult.getGlobalErrors().stream().forEach(
e -> error.addDetail(e.getDefaultMessage()));
bindingResult.getFieldErrors().stream().forEach(
e -> error.addDetail(e.getDefaultMessage()));
return super.handleExceptionInternal(bbhe, error, headers, status, request);
}
}
| 明示的にハンドリングしていない例外が起きたときに、通常と形式が異なるレスポンスが返却される問題を修正
| service/src/main/java/com/oracle/poco/bbhelper/ExceptionControllerAdvice.java | 明示的にハンドリングしていない例外が起きたときに、通常と形式が異なるレスポンスが返却される問題を修正 | <ide><path>ervice/src/main/java/com/oracle/poco/bbhelper/ExceptionControllerAdvice.java
<ide>
<ide> import java.util.List;
<ide>
<add>import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR;
<add>
<ide> @ControllerAdvice
<ide> public class ExceptionControllerAdvice extends ResponseEntityExceptionHandler {
<ide>
<ide> private static final BbhelperLogger logger =
<ide> BbhelperLogger.getLogger(ExceptionControllerAdvice.class);
<ide>
<add> /**
<add> * このクラスで明示的にハンドリングしていない例外を処理する
<add> * 明示的にハンドリングしていない例外は、システムエラーとして固定のレスポンスを返却する
<add> *
<add> * @param ex 発生した例外
<add> * @param request リクエスト
<add> * @return レスポンス
<add> */
<add> @ExceptionHandler
<add> public ResponseEntity<Object> handleSystemException(Exception ex, WebRequest request) {
<add> ErrorResponse error = new ErrorResponse(
<add> INTERNAL_SERVER_ERROR.value(), INTERNAL_SERVER_ERROR.getReasonPhrase(),
<add> "System Error", "System error is occurred.");
<add> return super.handleExceptionInternal(ex, error, null, null, request);
<add> }
<add>
<add> /**
<add> * Beehiveサーバーへの複数回のアクセスを並列実行したときの例外をハンドリングする
<add> *
<add> * @param ex 発生した例外を束ねる例外クラス
<add> * @param request リクエスト
<add> * @return レスポンス
<add> */
<ide> @ExceptionHandler
<ide> public ResponseEntity<Object> handleBbhelperBeehive4jParallelInvocationException(
<ide> BbhelperBeehive4jParallelInvocationException ex,
<ide> WebRequest request) {
<ide> List<BbhelperException> causes = ex.getCauses();
<ide> if (causes.size() == 1) {
<del> return handleExceptionInternal(
<del> causes.get(0), null, null, causes.get(0).getStatus(), request);
<add> return handleBbhelperException(causes.get(0), request);
<ide> }
<ide> ErrorResponse error = new ErrorResponse(
<ide> ex.getStatus().value(), ex.getStatus().getReasonPhrase(),
<ide> return super.handleExceptionInternal(ex, error, null, ex.getStatus(), request);
<ide> }
<ide>
<add> /**
<add> * このアプリケーションで定義しているカスタム例外をハンドリングする
<add> *
<add> * @param ex 発生した例外
<add> * @param request リクエスト
<add> * @return レスポンス
<add> */
<ide> @ExceptionHandler
<ide> public ResponseEntity<Object> handleBbhelperException(BbhelperException ex, WebRequest request) {
<del> return handleExceptionInternal(ex, null, null, ex.getStatus(), request);
<add> ErrorResponse error = new ErrorResponse(
<add> ex.getStatus().value(), ex.getStatus().getReasonPhrase(),
<add> ex.getClass().getName(), ex.getLocalizedMessage());
<add> return super.handleExceptionInternal(ex, error, null, ex.getStatus(), request);
<ide> }
<ide>
<del> @Override
<del> protected ResponseEntity<Object> handleExceptionInternal(
<del> Exception ex, Object body, HttpHeaders headers, HttpStatus status, WebRequest request) {
<del> ErrorResponse error = new ErrorResponse(status.value(), status.getReasonPhrase(),
<del> ex.getClass().getName(), ex.getLocalizedMessage());
<del> return super.handleExceptionInternal(ex, error, headers, status, request);
<del> }
<del>
<add> /*
<add> * 入力チェック時の例外をハンドリングするためにこのメソッドをオーバーライドする
<add> */
<ide> @Override
<ide> protected ResponseEntity<Object> handleBindException(
<ide> BindException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
<ide> return handleValidationFailure(ex, ex.getBindingResult(), headers, status, request);
<ide> }
<ide>
<add> /*
<add> * 入力チェック時の例外をハンドリングするためにこのメソッドをオーバーライドする
<add> */
<ide> @Override
<ide> protected ResponseEntity<Object> handleMethodArgumentNotValid(
<ide> MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, |
|
Java | apache-2.0 | 99f6afef8eda666bb672e1789cda67440484604d | 0 | androidx/androidx,androidx/androidx,androidx/androidx,AndroidX/androidx,aosp-mirror/platform_frameworks_support,aosp-mirror/platform_frameworks_support,AndroidX/androidx,AndroidX/androidx,AndroidX/androidx,androidx/androidx,androidx/androidx,AndroidX/androidx,androidx/androidx,aosp-mirror/platform_frameworks_support,androidx/androidx,AndroidX/androidx,aosp-mirror/platform_frameworks_support,androidx/androidx,AndroidX/androidx,androidx/androidx,AndroidX/androidx,aosp-mirror/platform_frameworks_support,androidx/androidx,AndroidX/androidx,AndroidX/androidx | /*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.support.v4.app;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
/**
* Base class for activities that want to use the support-based
* {@link android.support.v4.app.Fragment} and
* {@link android.support.v4.content.Loader} APIs.
*
* <p>When using this class as opposed to new platform's built-in fragment
* and loader support, you must use the {@link #getSupportFragmentManager()}
* and {@link #getSupportLoaderManager()} methods respectively to access
* those features.
*
* <p>Known limitations:</p>
* <ul>
* <li> <p>When using the <fragment> tag, this implementation can not
* use the parent view's ID as the new fragment's ID. You must explicitly
* specify an ID (or tag) in the <fragment>.</p>
* <li> <p>Prior to Honeycomb (3.0), an activity's state was saved before pausing.
* Fragments are a significant amount of new state, and dynamic enough that one
* often wants them to change between pausing and stopping. These classes
* throw an exception if you try to change the fragment state after it has been
* saved, to avoid accidental loss of UI state. However this is too restrictive
* prior to Honeycomb, where the state is saved before pausing. To address this,
* when running on platforms prior to Honeycomb an exception will not be thrown
* if you change fragments between the state save and the activity being stopped.
* This means that in some cases if the activity is restored from its last saved
* state, this may be a snapshot slightly before what the user last saw.</p>
* </ul>
*/
public class FragmentActivity extends Activity {
private static final String TAG = "FragmentActivity";
static final String FRAGMENTS_TAG = "android:support:fragments";
// This is the SDK API version of Honeycomb (3.0).
private static final int HONEYCOMB = 11;
static final int MSG_REALLY_STOPPED = 1;
static final int MSG_RESUME_PENDING = 2;
final Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_REALLY_STOPPED:
if (mStopped) {
doReallyStop(false);
}
break;
case MSG_RESUME_PENDING:
onResumeFragments();
mFragments.execPendingActions();
break;
default:
super.handleMessage(msg);
}
}
};
final FragmentManagerImpl mFragments = new FragmentManagerImpl();
final FragmentContainer mContainer = new FragmentContainer() {
@Override
public View findViewById(int id) {
return FragmentActivity.this.findViewById(id);
}
};
boolean mCreated;
boolean mResumed;
boolean mStopped;
boolean mReallyStopped;
boolean mRetaining;
boolean mOptionsMenuInvalidated;
boolean mCheckedForLoaderManager;
boolean mLoadersStarted;
HashMap<String, LoaderManagerImpl> mAllLoaderManagers;
LoaderManagerImpl mLoaderManager;
static final class NonConfigurationInstances {
Object activity;
Object custom;
HashMap<String, Object> children;
ArrayList<Fragment> fragments;
HashMap<String, LoaderManagerImpl> loaders;
}
static class FragmentTag {
public static final int[] Fragment = {
0x01010003, 0x010100d0, 0x010100d1
};
public static final int Fragment_id = 1;
public static final int Fragment_name = 0;
public static final int Fragment_tag = 2;
}
// ------------------------------------------------------------------------
// HOOKS INTO ACTIVITY
// ------------------------------------------------------------------------
/**
* Dispatch incoming result to the correct fragment.
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
mFragments.noteStateNotSaved();
int index = requestCode>>16;
if (index != 0) {
index--;
if (mFragments.mActive == null || index < 0 || index >= mFragments.mActive.size()) {
Log.w(TAG, "Activity result fragment index out of range: 0x"
+ Integer.toHexString(requestCode));
return;
}
Fragment frag = mFragments.mActive.get(index);
if (frag == null) {
Log.w(TAG, "Activity result no fragment exists for index: 0x"
+ Integer.toHexString(requestCode));
} else {
frag.onActivityResult(requestCode&0xffff, resultCode, data);
}
return;
}
super.onActivityResult(requestCode, resultCode, data);
}
/**
* Take care of popping the fragment back stack or finishing the activity
* as appropriate.
*/
public void onBackPressed() {
if (!mFragments.popBackStackImmediate()) {
finish();
}
}
/**
* Dispatch configuration change to all fragments.
*/
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mFragments.dispatchConfigurationChanged(newConfig);
}
/**
* Perform initialization of all fragments and loaders.
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
mFragments.attachActivity(this, mContainer, null);
// Old versions of the platform didn't do this!
if (getLayoutInflater().getFactory() == null) {
getLayoutInflater().setFactory(this);
}
super.onCreate(savedInstanceState);
NonConfigurationInstances nc = (NonConfigurationInstances)
getLastNonConfigurationInstance();
if (nc != null) {
mAllLoaderManagers = nc.loaders;
}
if (savedInstanceState != null) {
Parcelable p = savedInstanceState.getParcelable(FRAGMENTS_TAG);
mFragments.restoreAllState(p, nc != null ? nc.fragments : null);
}
mFragments.dispatchCreate();
}
/**
* Dispatch to Fragment.onCreateOptionsMenu().
*/
@Override
public boolean onCreatePanelMenu(int featureId, Menu menu) {
if (featureId == Window.FEATURE_OPTIONS_PANEL) {
boolean show = super.onCreatePanelMenu(featureId, menu);
show |= mFragments.dispatchCreateOptionsMenu(menu, getMenuInflater());
if (android.os.Build.VERSION.SDK_INT >= HONEYCOMB) {
return show;
}
// Prior to Honeycomb, the framework can't invalidate the options
// menu, so we must always say we have one in case the app later
// invalidates it and needs to have it shown.
return true;
}
return super.onCreatePanelMenu(featureId, menu);
}
/**
* Add support for inflating the <fragment> tag.
*/
@Override
public View onCreateView(String name, Context context, AttributeSet attrs) {
if (!"fragment".equals(name)) {
return super.onCreateView(name, context, attrs);
}
String fname = attrs.getAttributeValue(null, "class");
TypedArray a = context.obtainStyledAttributes(attrs, FragmentTag.Fragment);
if (fname == null) {
fname = a.getString(FragmentTag.Fragment_name);
}
int id = a.getResourceId(FragmentTag.Fragment_id, View.NO_ID);
String tag = a.getString(FragmentTag.Fragment_tag);
a.recycle();
View parent = null; // NOTE: no way to get parent pre-Honeycomb.
int containerId = parent != null ? parent.getId() : 0;
if (containerId == View.NO_ID && id == View.NO_ID && tag == null) {
throw new IllegalArgumentException(attrs.getPositionDescription()
+ ": Must specify unique android:id, android:tag, or have a parent with an id for " + fname);
}
// If we restored from a previous state, we may already have
// instantiated this fragment from the state and should use
// that instance instead of making a new one.
Fragment fragment = id != View.NO_ID ? mFragments.findFragmentById(id) : null;
if (fragment == null && tag != null) {
fragment = mFragments.findFragmentByTag(tag);
}
if (fragment == null && containerId != View.NO_ID) {
fragment = mFragments.findFragmentById(containerId);
}
if (FragmentManagerImpl.DEBUG) Log.v(TAG, "onCreateView: id=0x"
+ Integer.toHexString(id) + " fname=" + fname
+ " existing=" + fragment);
if (fragment == null) {
fragment = Fragment.instantiate(this, fname);
fragment.mFromLayout = true;
fragment.mFragmentId = id != 0 ? id : containerId;
fragment.mContainerId = containerId;
fragment.mTag = tag;
fragment.mInLayout = true;
fragment.mFragmentManager = mFragments;
fragment.onInflate(this, attrs, fragment.mSavedFragmentState);
mFragments.addFragment(fragment, true);
} else if (fragment.mInLayout) {
// A fragment already exists and it is not one we restored from
// previous state.
throw new IllegalArgumentException(attrs.getPositionDescription()
+ ": Duplicate id 0x" + Integer.toHexString(id)
+ ", tag " + tag + ", or parent id 0x" + Integer.toHexString(containerId)
+ " with another fragment for " + fname);
} else {
// This fragment was retained from a previous instance; get it
// going now.
fragment.mInLayout = true;
// If this fragment is newly instantiated (either right now, or
// from last saved state), then give it the attributes to
// initialize itself.
if (!fragment.mRetaining) {
fragment.onInflate(this, attrs, fragment.mSavedFragmentState);
}
mFragments.moveToState(fragment);
}
if (fragment.mView == null) {
throw new IllegalStateException("Fragment " + fname
+ " did not create a view.");
}
if (id != 0) {
fragment.mView.setId(id);
}
if (fragment.mView.getTag() == null) {
fragment.mView.setTag(tag);
}
return fragment.mView;
}
/**
* Destroy all fragments and loaders.
*/
@Override
protected void onDestroy() {
super.onDestroy();
doReallyStop(false);
mFragments.dispatchDestroy();
if (mLoaderManager != null) {
mLoaderManager.doDestroy();
}
}
/**
* Take care of calling onBackPressed() for pre-Eclair platforms.
*/
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (android.os.Build.VERSION.SDK_INT < 5 /* ECLAIR */
&& keyCode == KeyEvent.KEYCODE_BACK
&& event.getRepeatCount() == 0) {
// Take care of calling this method on earlier versions of
// the platform where it doesn't exist.
onBackPressed();
return true;
}
return super.onKeyDown(keyCode, event);
}
/**
* Dispatch onLowMemory() to all fragments.
*/
@Override
public void onLowMemory() {
super.onLowMemory();
mFragments.dispatchLowMemory();
}
/**
* Dispatch context and options menu to fragments.
*/
@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
if (super.onMenuItemSelected(featureId, item)) {
return true;
}
switch (featureId) {
case Window.FEATURE_OPTIONS_PANEL:
return mFragments.dispatchOptionsItemSelected(item);
case Window.FEATURE_CONTEXT_MENU:
return mFragments.dispatchContextItemSelected(item);
default:
return false;
}
}
/**
* Call onOptionsMenuClosed() on fragments.
*/
@Override
public void onPanelClosed(int featureId, Menu menu) {
switch (featureId) {
case Window.FEATURE_OPTIONS_PANEL:
mFragments.dispatchOptionsMenuClosed(menu);
break;
}
super.onPanelClosed(featureId, menu);
}
/**
* Dispatch onPause() to fragments.
*/
@Override
protected void onPause() {
super.onPause();
mResumed = false;
if (mHandler.hasMessages(MSG_RESUME_PENDING)) {
mHandler.removeMessages(MSG_RESUME_PENDING);
onResumeFragments();
}
mFragments.dispatchPause();
}
/**
* Handle onNewIntent() to inform the fragment manager that the
* state is not saved. If you are handling new intents and may be
* making changes to the fragment state, you want to be sure to call
* through to the super-class here first. Otherwise, if your state
* is saved but the activity is not stopped, you could get an
* onNewIntent() call which happens before onResume() and trying to
* perform fragment operations at that point will throw IllegalStateException
* because the fragment manager thinks the state is still saved.
*/
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
mFragments.noteStateNotSaved();
}
/**
* Dispatch onResume() to fragments. Note that for better inter-operation
* with older versions of the platform, at the point of this call the
* fragments attached to the activity are <em>not</em> resumed. This means
* that in some cases the previous state may still be saved, not allowing
* fragment transactions that modify the state. To correctly interact
* with fragments in their proper state, you should instead override
* {@link #onResumeFragments()}.
*/
@Override
protected void onResume() {
super.onResume();
mHandler.sendEmptyMessage(MSG_RESUME_PENDING);
mResumed = true;
mFragments.execPendingActions();
}
/**
* Dispatch onResume() to fragments.
*/
@Override
protected void onPostResume() {
super.onPostResume();
mHandler.removeMessages(MSG_RESUME_PENDING);
onResumeFragments();
mFragments.execPendingActions();
}
/**
* This is the fragment-orientated version of {@link #onResume()} that you
* can override to perform operations in the Activity at the same point
* where its fragments are resumed. Be sure to always call through to
* the super-class.
*/
protected void onResumeFragments() {
mFragments.dispatchResume();
}
/**
* Dispatch onPrepareOptionsMenu() to fragments.
*/
@Override
public boolean onPreparePanel(int featureId, View view, Menu menu) {
if (featureId == Window.FEATURE_OPTIONS_PANEL && menu != null) {
if (mOptionsMenuInvalidated) {
mOptionsMenuInvalidated = false;
menu.clear();
onCreatePanelMenu(featureId, menu);
}
boolean goforit = super.onPreparePanel(featureId, view, menu);
goforit |= mFragments.dispatchPrepareOptionsMenu(menu);
return goforit;
}
return super.onPreparePanel(featureId, view, menu);
}
/**
* Retain all appropriate fragment and loader state. You can NOT
* override this yourself! Use {@link #onRetainCustomNonConfigurationInstance()}
* if you want to retain your own state.
*/
@Override
public final Object onRetainNonConfigurationInstance() {
if (mStopped) {
doReallyStop(true);
}
Object custom = onRetainCustomNonConfigurationInstance();
ArrayList<Fragment> fragments = mFragments.retainNonConfig();
boolean retainLoaders = false;
if (mAllLoaderManagers != null) {
// prune out any loader managers that were already stopped and so
// have nothing useful to retain.
LoaderManagerImpl loaders[] = new LoaderManagerImpl[mAllLoaderManagers.size()];
mAllLoaderManagers.values().toArray(loaders);
if (loaders != null) {
for (int i=0; i<loaders.length; i++) {
LoaderManagerImpl lm = loaders[i];
if (lm.mRetaining) {
retainLoaders = true;
} else {
lm.doDestroy();
mAllLoaderManagers.remove(lm.mWho);
}
}
}
}
if (fragments == null && !retainLoaders && custom == null) {
return null;
}
NonConfigurationInstances nci = new NonConfigurationInstances();
nci.activity = null;
nci.custom = custom;
nci.children = null;
nci.fragments = fragments;
nci.loaders = mAllLoaderManagers;
return nci;
}
/**
* Save all appropriate fragment state.
*/
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Parcelable p = mFragments.saveAllState();
if (p != null) {
outState.putParcelable(FRAGMENTS_TAG, p);
}
}
/**
* Dispatch onStart() to all fragments. Ensure any created loaders are
* now started.
*/
@Override
protected void onStart() {
super.onStart();
mStopped = false;
mReallyStopped = false;
mHandler.removeMessages(MSG_REALLY_STOPPED);
if (!mCreated) {
mCreated = true;
mFragments.dispatchActivityCreated();
}
mFragments.noteStateNotSaved();
mFragments.execPendingActions();
if (!mLoadersStarted) {
mLoadersStarted = true;
if (mLoaderManager != null) {
mLoaderManager.doStart();
} else if (!mCheckedForLoaderManager) {
mLoaderManager = getLoaderManager(null, mLoadersStarted, false);
// the returned loader manager may be a new one, so we have to start it
if ((mLoaderManager != null) && (!mLoaderManager.mStarted)) {
mLoaderManager.doStart();
}
}
mCheckedForLoaderManager = true;
}
// NOTE: HC onStart goes here.
mFragments.dispatchStart();
if (mAllLoaderManagers != null) {
LoaderManagerImpl loaders[] = new LoaderManagerImpl[mAllLoaderManagers.size()];
mAllLoaderManagers.values().toArray(loaders);
if (loaders != null) {
for (int i=0; i<loaders.length; i++) {
LoaderManagerImpl lm = loaders[i];
lm.finishRetain();
lm.doReportStart();
}
}
}
}
/**
* Dispatch onStop() to all fragments. Ensure all loaders are stopped.
*/
@Override
protected void onStop() {
super.onStop();
mStopped = true;
mHandler.sendEmptyMessage(MSG_REALLY_STOPPED);
mFragments.dispatchStop();
}
// ------------------------------------------------------------------------
// NEW METHODS
// ------------------------------------------------------------------------
/**
* Use this instead of {@link #onRetainNonConfigurationInstance()}.
* Retrieve later with {@link #getLastCustomNonConfigurationInstance()}.
*/
public Object onRetainCustomNonConfigurationInstance() {
return null;
}
/**
* Return the value previously returned from
* {@link #onRetainCustomNonConfigurationInstance()}.
*/
public Object getLastCustomNonConfigurationInstance() {
NonConfigurationInstances nc = (NonConfigurationInstances)
getLastNonConfigurationInstance();
return nc != null ? nc.custom : null;
}
/**
* Support library version of {@link Activity#invalidateOptionsMenu}.
*
* <p>Invalidate the activity's options menu. This will cause relevant presentations
* of the menu to fully update via calls to onCreateOptionsMenu and
* onPrepareOptionsMenu the next time the menu is requested.
*/
public void supportInvalidateOptionsMenu() {
if (android.os.Build.VERSION.SDK_INT >= HONEYCOMB) {
// If we are running on HC or greater, we can use the framework
// API to invalidate the options menu.
ActivityCompatHoneycomb.invalidateOptionsMenu(this);
return;
}
// Whoops, older platform... we'll use a hack, to manually rebuild
// the options menu the next time it is prepared.
mOptionsMenuInvalidated = true;
}
/**
* Print the Activity's state into the given stream. This gets invoked if
* you run "adb shell dumpsys activity <activity_component_name>".
*
* @param prefix Desired prefix to prepend at each line of output.
* @param fd The raw file descriptor that the dump is being sent to.
* @param writer The PrintWriter to which you should dump your state. This will be
* closed for you after you return.
* @param args additional arguments to the dump request.
*/
public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
if (android.os.Build.VERSION.SDK_INT >= HONEYCOMB) {
// XXX This can only work if we can call the super-class impl. :/
//ActivityCompatHoneycomb.dump(this, prefix, fd, writer, args);
}
writer.print(prefix); writer.print("Local FragmentActivity ");
writer.print(Integer.toHexString(System.identityHashCode(this)));
writer.println(" State:");
String innerPrefix = prefix + " ";
writer.print(innerPrefix); writer.print("mCreated=");
writer.print(mCreated); writer.print("mResumed=");
writer.print(mResumed); writer.print(" mStopped=");
writer.print(mStopped); writer.print(" mReallyStopped=");
writer.println(mReallyStopped);
writer.print(innerPrefix); writer.print("mLoadersStarted=");
writer.println(mLoadersStarted);
if (mLoaderManager != null) {
writer.print(prefix); writer.print("Loader Manager ");
writer.print(Integer.toHexString(System.identityHashCode(mLoaderManager)));
writer.println(":");
mLoaderManager.dump(prefix + " ", fd, writer, args);
}
mFragments.dump(prefix, fd, writer, args);
writer.print(prefix); writer.println("View Hierarchy:");
dumpViewHierarchy(prefix + " ", writer, getWindow().getDecorView());
}
private static String viewToString(View view) {
StringBuilder out = new StringBuilder(128);
out.append(view.getClass().getName());
out.append('{');
out.append(Integer.toHexString(System.identityHashCode(view)));
out.append(' ');
switch (view.getVisibility()) {
case View.VISIBLE: out.append('V'); break;
case View.INVISIBLE: out.append('I'); break;
case View.GONE: out.append('G'); break;
default: out.append('.'); break;
}
out.append(view.isFocusable() ? 'F' : '.');
out.append(view.isEnabled() ? 'E' : '.');
out.append(view.willNotDraw() ? '.' : 'D');
out.append(view.isHorizontalScrollBarEnabled()? 'H' : '.');
out.append(view.isVerticalScrollBarEnabled() ? 'V' : '.');
out.append(view.isClickable() ? 'C' : '.');
out.append(view.isLongClickable() ? 'L' : '.');
out.append(' ');
out.append(view.isFocused() ? 'F' : '.');
out.append(view.isSelected() ? 'S' : '.');
out.append(view.isPressed() ? 'P' : '.');
out.append(' ');
out.append(view.getLeft());
out.append(',');
out.append(view.getTop());
out.append('-');
out.append(view.getRight());
out.append(',');
out.append(view.getBottom());
final int id = view.getId();
if (id != View.NO_ID) {
out.append(" #");
out.append(Integer.toHexString(id));
final Resources r = view.getResources();
if (id != 0 && r != null) {
try {
String pkgname;
switch (id&0xff000000) {
case 0x7f000000:
pkgname="app";
break;
case 0x01000000:
pkgname="android";
break;
default:
pkgname = r.getResourcePackageName(id);
break;
}
String typename = r.getResourceTypeName(id);
String entryname = r.getResourceEntryName(id);
out.append(" ");
out.append(pkgname);
out.append(":");
out.append(typename);
out.append("/");
out.append(entryname);
} catch (Resources.NotFoundException e) {
}
}
}
out.append("}");
return out.toString();
}
private void dumpViewHierarchy(String prefix, PrintWriter writer, View view) {
writer.print(prefix);
if (view == null) {
writer.println("null");
return;
}
writer.println(viewToString(view));
if (!(view instanceof ViewGroup)) {
return;
}
ViewGroup grp = (ViewGroup)view;
final int N = grp.getChildCount();
if (N <= 0) {
return;
}
prefix = prefix + " ";
for (int i=0; i<N; i++) {
dumpViewHierarchy(prefix, writer, grp.getChildAt(i));
}
}
void doReallyStop(boolean retaining) {
if (!mReallyStopped) {
mReallyStopped = true;
mRetaining = retaining;
mHandler.removeMessages(MSG_REALLY_STOPPED);
onReallyStop();
}
}
/**
* Pre-HC, we didn't have a way to determine whether an activity was
* being stopped for a config change or not until we saw
* onRetainNonConfigurationInstance() called after onStop(). However
* we need to know this, to know whether to retain fragments. This will
* tell us what we need to know.
*/
void onReallyStop() {
if (mLoadersStarted) {
mLoadersStarted = false;
if (mLoaderManager != null) {
if (!mRetaining) {
mLoaderManager.doStop();
} else {
mLoaderManager.doRetain();
}
}
}
mFragments.dispatchReallyStop();
}
// ------------------------------------------------------------------------
// FRAGMENT SUPPORT
// ------------------------------------------------------------------------
/**
* Called when a fragment is attached to the activity.
*/
public void onAttachFragment(Fragment fragment) {
}
/**
* Return the FragmentManager for interacting with fragments associated
* with this activity.
*/
public FragmentManager getSupportFragmentManager() {
return mFragments;
}
/**
* Modifies the standard behavior to allow results to be delivered to fragments.
* This imposes a restriction that requestCode be <= 0xffff.
*/
@Override
public void startActivityForResult(Intent intent, int requestCode) {
if (requestCode != -1 && (requestCode&0xffff0000) != 0) {
throw new IllegalArgumentException("Can only use lower 16 bits for requestCode");
}
super.startActivityForResult(intent, requestCode);
}
/**
* Called by Fragment.startActivityForResult() to implement its behavior.
*/
public void startActivityFromFragment(Fragment fragment, Intent intent,
int requestCode) {
if (requestCode == -1) {
super.startActivityForResult(intent, -1);
return;
}
if ((requestCode&0xffff0000) != 0) {
throw new IllegalArgumentException("Can only use lower 16 bits for requestCode");
}
super.startActivityForResult(intent, ((fragment.mIndex+1)<<16) + (requestCode&0xffff));
}
void invalidateSupportFragment(String who) {
//Log.v(TAG, "invalidateSupportFragment: who=" + who);
if (mAllLoaderManagers != null) {
LoaderManagerImpl lm = mAllLoaderManagers.get(who);
if (lm != null && !lm.mRetaining) {
lm.doDestroy();
mAllLoaderManagers.remove(who);
}
}
}
// ------------------------------------------------------------------------
// LOADER SUPPORT
// ------------------------------------------------------------------------
/**
* Return the LoaderManager for this fragment, creating it if needed.
*/
public LoaderManager getSupportLoaderManager() {
if (mLoaderManager != null) {
return mLoaderManager;
}
mCheckedForLoaderManager = true;
mLoaderManager = getLoaderManager(null, mLoadersStarted, true);
return mLoaderManager;
}
LoaderManagerImpl getLoaderManager(String who, boolean started, boolean create) {
if (mAllLoaderManagers == null) {
mAllLoaderManagers = new HashMap<String, LoaderManagerImpl>();
}
LoaderManagerImpl lm = mAllLoaderManagers.get(who);
if (lm == null) {
if (create) {
lm = new LoaderManagerImpl(who, this, started);
mAllLoaderManagers.put(who, lm);
}
} else {
lm.updateActivity(this);
}
return lm;
}
}
| v4/java/android/support/v4/app/FragmentActivity.java | /*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.support.v4.app;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
/**
* Base class for activities that want to use the support-based
* {@link android.support.v4.app.Fragment} and
* {@link android.support.v4.content.Loader} APIs.
*
* <p>When using this class as opposed to new platform's built-in fragment
* and loader support, you must use the {@link #getSupportFragmentManager()}
* and {@link #getSupportLoaderManager()} methods respectively to access
* those features.
*
* <p>Known limitations:</p>
* <ul>
* <li> <p>When using the <fragment> tag, this implementation can not
* use the parent view's ID as the new fragment's ID. You must explicitly
* specify an ID (or tag) in the <fragment>.</p>
* <li> <p>Prior to Honeycomb (3.0), an activity's state was saved before pausing.
* Fragments are a significant amount of new state, and dynamic enough that one
* often wants them to change between pausing and stopping. These classes
* throw an exception if you try to change the fragment state after it has been
* saved, to avoid accidental loss of UI state. However this is too restrictive
* prior to Honeycomb, where the state is saved before pausing. To address this,
* when running on platforms prior to Honeycomb an exception will not be thrown
* if you change fragments between the state save and the activity being stopped.
* This means that in some cases if the activity is restored from its last saved
* state, this may be a snapshot slightly before what the user last saw.</p>
* </ul>
*/
public class FragmentActivity extends Activity {
private static final String TAG = "FragmentActivity";
static final String FRAGMENTS_TAG = "android:support:fragments";
// This is the SDK API version of Honeycomb (3.0).
private static final int HONEYCOMB = 11;
static final int MSG_REALLY_STOPPED = 1;
static final int MSG_RESUME_PENDING = 2;
final Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_REALLY_STOPPED:
if (mStopped) {
doReallyStop(false);
}
break;
case MSG_RESUME_PENDING:
onResumeFragments();
mFragments.execPendingActions();
break;
default:
super.handleMessage(msg);
}
}
};
final FragmentManagerImpl mFragments = new FragmentManagerImpl();
final FragmentContainer mContainer = new FragmentContainer() {
@Override
public View findViewById(int id) {
return FragmentActivity.this.findViewById(id);
}
};
boolean mCreated;
boolean mResumed;
boolean mStopped;
boolean mReallyStopped;
boolean mRetaining;
boolean mOptionsMenuInvalidated;
boolean mCheckedForLoaderManager;
boolean mLoadersStarted;
HashMap<String, LoaderManagerImpl> mAllLoaderManagers;
LoaderManagerImpl mLoaderManager;
static final class NonConfigurationInstances {
Object activity;
Object custom;
HashMap<String, Object> children;
ArrayList<Fragment> fragments;
HashMap<String, LoaderManagerImpl> loaders;
}
static class FragmentTag {
public static final int[] Fragment = {
0x01010003, 0x010100d0, 0x010100d1
};
public static final int Fragment_id = 1;
public static final int Fragment_name = 0;
public static final int Fragment_tag = 2;
}
// ------------------------------------------------------------------------
// HOOKS INTO ACTIVITY
// ------------------------------------------------------------------------
/**
* Dispatch incoming result to the correct fragment.
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
mFragments.noteStateNotSaved();
int index = requestCode>>16;
if (index != 0) {
index--;
if (mFragments.mActive == null || index < 0 || index >= mFragments.mActive.size()) {
Log.w(TAG, "Activity result fragment index out of range: 0x"
+ Integer.toHexString(requestCode));
return;
}
Fragment frag = mFragments.mActive.get(index);
if (frag == null) {
Log.w(TAG, "Activity result no fragment exists for index: 0x"
+ Integer.toHexString(requestCode));
} else {
frag.onActivityResult(requestCode&0xffff, resultCode, data);
}
return;
}
super.onActivityResult(requestCode, resultCode, data);
}
/**
* Take care of popping the fragment back stack or finishing the activity
* as appropriate.
*/
public void onBackPressed() {
if (!mFragments.popBackStackImmediate()) {
finish();
}
}
/**
* Dispatch configuration change to all fragments.
*/
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mFragments.dispatchConfigurationChanged(newConfig);
}
/**
* Perform initialization of all fragments and loaders.
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
mFragments.attachActivity(this, mContainer, null);
// Old versions of the platform didn't do this!
if (getLayoutInflater().getFactory() == null) {
getLayoutInflater().setFactory(this);
}
super.onCreate(savedInstanceState);
NonConfigurationInstances nc = (NonConfigurationInstances)
getLastNonConfigurationInstance();
if (nc != null) {
mAllLoaderManagers = nc.loaders;
}
if (savedInstanceState != null) {
Parcelable p = savedInstanceState.getParcelable(FRAGMENTS_TAG);
mFragments.restoreAllState(p, nc != null ? nc.fragments : null);
}
mFragments.dispatchCreate();
}
/**
* Dispatch to Fragment.onCreateOptionsMenu().
*/
@Override
public boolean onCreatePanelMenu(int featureId, Menu menu) {
if (featureId == Window.FEATURE_OPTIONS_PANEL) {
boolean show = super.onCreatePanelMenu(featureId, menu);
show |= mFragments.dispatchCreateOptionsMenu(menu, getMenuInflater());
if (android.os.Build.VERSION.SDK_INT >= HONEYCOMB) {
return show;
}
// Prior to Honeycomb, the framework can't invalidate the options
// menu, so we must always say we have one in case the app later
// invalidates it and needs to have it shown.
return true;
}
return super.onCreatePanelMenu(featureId, menu);
}
/**
* Add support for inflating the <fragment> tag.
*/
@Override
public View onCreateView(String name, Context context, AttributeSet attrs) {
if (!"fragment".equals(name)) {
return super.onCreateView(name, context, attrs);
}
String fname = attrs.getAttributeValue(null, "class");
TypedArray a = context.obtainStyledAttributes(attrs, FragmentTag.Fragment);
if (fname == null) {
fname = a.getString(FragmentTag.Fragment_name);
}
int id = a.getResourceId(FragmentTag.Fragment_id, View.NO_ID);
String tag = a.getString(FragmentTag.Fragment_tag);
a.recycle();
View parent = null; // NOTE: no way to get parent pre-Honeycomb.
int containerId = parent != null ? parent.getId() : 0;
if (containerId == View.NO_ID && id == View.NO_ID && tag == null) {
throw new IllegalArgumentException(attrs.getPositionDescription()
+ ": Must specify unique android:id, android:tag, or have a parent with an id for " + fname);
}
// If we restored from a previous state, we may already have
// instantiated this fragment from the state and should use
// that instance instead of making a new one.
Fragment fragment = id != View.NO_ID ? mFragments.findFragmentById(id) : null;
if (fragment == null && tag != null) {
fragment = mFragments.findFragmentByTag(tag);
}
if (fragment == null && containerId != View.NO_ID) {
fragment = mFragments.findFragmentById(containerId);
}
if (FragmentManagerImpl.DEBUG) Log.v(TAG, "onCreateView: id=0x"
+ Integer.toHexString(id) + " fname=" + fname
+ " existing=" + fragment);
if (fragment == null) {
fragment = Fragment.instantiate(this, fname);
fragment.mFromLayout = true;
fragment.mFragmentId = id != 0 ? id : containerId;
fragment.mContainerId = containerId;
fragment.mTag = tag;
fragment.mInLayout = true;
fragment.mFragmentManager = mFragments;
fragment.onInflate(this, attrs, fragment.mSavedFragmentState);
mFragments.addFragment(fragment, true);
} else if (fragment.mInLayout) {
// A fragment already exists and it is not one we restored from
// previous state.
throw new IllegalArgumentException(attrs.getPositionDescription()
+ ": Duplicate id 0x" + Integer.toHexString(id)
+ ", tag " + tag + ", or parent id 0x" + Integer.toHexString(containerId)
+ " with another fragment for " + fname);
} else {
// This fragment was retained from a previous instance; get it
// going now.
fragment.mInLayout = true;
// If this fragment is newly instantiated (either right now, or
// from last saved state), then give it the attributes to
// initialize itself.
if (!fragment.mRetaining) {
fragment.onInflate(this, attrs, fragment.mSavedFragmentState);
}
mFragments.moveToState(fragment);
}
if (fragment.mView == null) {
throw new IllegalStateException("Fragment " + fname
+ " did not create a view.");
}
if (id != 0) {
fragment.mView.setId(id);
}
if (fragment.mView.getTag() == null) {
fragment.mView.setTag(tag);
}
return fragment.mView;
}
/**
* Destroy all fragments and loaders.
*/
@Override
protected void onDestroy() {
super.onDestroy();
doReallyStop(false);
mFragments.dispatchDestroy();
if (mLoaderManager != null) {
mLoaderManager.doDestroy();
}
}
/**
* Take care of calling onBackPressed() for pre-Eclair platforms.
*/
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (android.os.Build.VERSION.SDK_INT < 5 /* ECLAIR */
&& keyCode == KeyEvent.KEYCODE_BACK
&& event.getRepeatCount() == 0) {
// Take care of calling this method on earlier versions of
// the platform where it doesn't exist.
onBackPressed();
return true;
}
return super.onKeyDown(keyCode, event);
}
/**
* Dispatch onLowMemory() to all fragments.
*/
@Override
public void onLowMemory() {
super.onLowMemory();
mFragments.dispatchLowMemory();
}
/**
* Dispatch context and options menu to fragments.
*/
@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
if (super.onMenuItemSelected(featureId, item)) {
return true;
}
switch (featureId) {
case Window.FEATURE_OPTIONS_PANEL:
return mFragments.dispatchOptionsItemSelected(item);
case Window.FEATURE_CONTEXT_MENU:
return mFragments.dispatchContextItemSelected(item);
default:
return false;
}
}
/**
* Call onOptionsMenuClosed() on fragments.
*/
@Override
public void onPanelClosed(int featureId, Menu menu) {
switch (featureId) {
case Window.FEATURE_OPTIONS_PANEL:
mFragments.dispatchOptionsMenuClosed(menu);
break;
}
super.onPanelClosed(featureId, menu);
}
/**
* Dispatch onPause() to fragments.
*/
@Override
protected void onPause() {
super.onPause();
mResumed = false;
if (mHandler.hasMessages(MSG_RESUME_PENDING)) {
mHandler.removeMessages(MSG_RESUME_PENDING);
onResumeFragments();
}
mFragments.dispatchPause();
}
/**
* Handle onNewIntent() to inform the fragment manager that the
* state is not saved. If you are handling new intents and may be
* making changes to the fragment state, you want to be sure to call
* through to the super-class here first. Otherwise, if your state
* is saved but the activity is not stopped, you could get an
* onNewIntent() call which happens before onResume() and trying to
* perform fragment operations at that point will throw IllegalStateException
* because the fragment manager thinks the state is still saved.
*/
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
mFragments.noteStateNotSaved();
}
/**
* Dispatch onResume() to fragments. Note that for better inter-operation
* with older versions of the platform, at the point of this call the
* fragments attached to the activity are <em>not</em> resumed. This means
* that in some cases the previous state may still be saved, not allowing
* fragment transactions that modify the state. To correctly interact
* with fragments in their proper state, you should instead override
* {@link #onResumeFragments()}.
*/
@Override
protected void onResume() {
super.onResume();
mHandler.sendEmptyMessage(MSG_RESUME_PENDING);
mResumed = true;
mFragments.execPendingActions();
}
/**
* Dispatch onResume() to fragments.
*/
@Override
protected void onPostResume() {
super.onPostResume();
mHandler.removeMessages(MSG_RESUME_PENDING);
onResumeFragments();
mFragments.execPendingActions();
}
/**
* This is the fragment-orientated version of {@link #onResume()} that you
* can override to perform operations in the Activity at the same point
* where its fragments are resumed. Be sure to always call through to
* the super-class.
*/
protected void onResumeFragments() {
mFragments.dispatchResume();
}
/**
* Dispatch onPrepareOptionsMenu() to fragments.
*/
@Override
public boolean onPreparePanel(int featureId, View view, Menu menu) {
if (featureId == Window.FEATURE_OPTIONS_PANEL && menu != null) {
if (mOptionsMenuInvalidated) {
mOptionsMenuInvalidated = false;
menu.clear();
onCreatePanelMenu(featureId, menu);
}
boolean goforit = super.onPreparePanel(featureId, view, menu);
goforit |= mFragments.dispatchPrepareOptionsMenu(menu);
return goforit && menu.hasVisibleItems();
}
return super.onPreparePanel(featureId, view, menu);
}
/**
* Retain all appropriate fragment and loader state. You can NOT
* override this yourself! Use {@link #onRetainCustomNonConfigurationInstance()}
* if you want to retain your own state.
*/
@Override
public final Object onRetainNonConfigurationInstance() {
if (mStopped) {
doReallyStop(true);
}
Object custom = onRetainCustomNonConfigurationInstance();
ArrayList<Fragment> fragments = mFragments.retainNonConfig();
boolean retainLoaders = false;
if (mAllLoaderManagers != null) {
// prune out any loader managers that were already stopped and so
// have nothing useful to retain.
LoaderManagerImpl loaders[] = new LoaderManagerImpl[mAllLoaderManagers.size()];
mAllLoaderManagers.values().toArray(loaders);
if (loaders != null) {
for (int i=0; i<loaders.length; i++) {
LoaderManagerImpl lm = loaders[i];
if (lm.mRetaining) {
retainLoaders = true;
} else {
lm.doDestroy();
mAllLoaderManagers.remove(lm.mWho);
}
}
}
}
if (fragments == null && !retainLoaders && custom == null) {
return null;
}
NonConfigurationInstances nci = new NonConfigurationInstances();
nci.activity = null;
nci.custom = custom;
nci.children = null;
nci.fragments = fragments;
nci.loaders = mAllLoaderManagers;
return nci;
}
/**
* Save all appropriate fragment state.
*/
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Parcelable p = mFragments.saveAllState();
if (p != null) {
outState.putParcelable(FRAGMENTS_TAG, p);
}
}
/**
* Dispatch onStart() to all fragments. Ensure any created loaders are
* now started.
*/
@Override
protected void onStart() {
super.onStart();
mStopped = false;
mReallyStopped = false;
mHandler.removeMessages(MSG_REALLY_STOPPED);
if (!mCreated) {
mCreated = true;
mFragments.dispatchActivityCreated();
}
mFragments.noteStateNotSaved();
mFragments.execPendingActions();
if (!mLoadersStarted) {
mLoadersStarted = true;
if (mLoaderManager != null) {
mLoaderManager.doStart();
} else if (!mCheckedForLoaderManager) {
mLoaderManager = getLoaderManager(null, mLoadersStarted, false);
// the returned loader manager may be a new one, so we have to start it
if ((mLoaderManager != null) && (!mLoaderManager.mStarted)) {
mLoaderManager.doStart();
}
}
mCheckedForLoaderManager = true;
}
// NOTE: HC onStart goes here.
mFragments.dispatchStart();
if (mAllLoaderManagers != null) {
LoaderManagerImpl loaders[] = new LoaderManagerImpl[mAllLoaderManagers.size()];
mAllLoaderManagers.values().toArray(loaders);
if (loaders != null) {
for (int i=0; i<loaders.length; i++) {
LoaderManagerImpl lm = loaders[i];
lm.finishRetain();
lm.doReportStart();
}
}
}
}
/**
* Dispatch onStop() to all fragments. Ensure all loaders are stopped.
*/
@Override
protected void onStop() {
super.onStop();
mStopped = true;
mHandler.sendEmptyMessage(MSG_REALLY_STOPPED);
mFragments.dispatchStop();
}
// ------------------------------------------------------------------------
// NEW METHODS
// ------------------------------------------------------------------------
/**
* Use this instead of {@link #onRetainNonConfigurationInstance()}.
* Retrieve later with {@link #getLastCustomNonConfigurationInstance()}.
*/
public Object onRetainCustomNonConfigurationInstance() {
return null;
}
/**
* Return the value previously returned from
* {@link #onRetainCustomNonConfigurationInstance()}.
*/
public Object getLastCustomNonConfigurationInstance() {
NonConfigurationInstances nc = (NonConfigurationInstances)
getLastNonConfigurationInstance();
return nc != null ? nc.custom : null;
}
/**
* Support library version of {@link Activity#invalidateOptionsMenu}.
*
* <p>Invalidate the activity's options menu. This will cause relevant presentations
* of the menu to fully update via calls to onCreateOptionsMenu and
* onPrepareOptionsMenu the next time the menu is requested.
*/
public void supportInvalidateOptionsMenu() {
if (android.os.Build.VERSION.SDK_INT >= HONEYCOMB) {
// If we are running on HC or greater, we can use the framework
// API to invalidate the options menu.
ActivityCompatHoneycomb.invalidateOptionsMenu(this);
return;
}
// Whoops, older platform... we'll use a hack, to manually rebuild
// the options menu the next time it is prepared.
mOptionsMenuInvalidated = true;
}
/**
* Print the Activity's state into the given stream. This gets invoked if
* you run "adb shell dumpsys activity <activity_component_name>".
*
* @param prefix Desired prefix to prepend at each line of output.
* @param fd The raw file descriptor that the dump is being sent to.
* @param writer The PrintWriter to which you should dump your state. This will be
* closed for you after you return.
* @param args additional arguments to the dump request.
*/
public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
if (android.os.Build.VERSION.SDK_INT >= HONEYCOMB) {
// XXX This can only work if we can call the super-class impl. :/
//ActivityCompatHoneycomb.dump(this, prefix, fd, writer, args);
}
writer.print(prefix); writer.print("Local FragmentActivity ");
writer.print(Integer.toHexString(System.identityHashCode(this)));
writer.println(" State:");
String innerPrefix = prefix + " ";
writer.print(innerPrefix); writer.print("mCreated=");
writer.print(mCreated); writer.print("mResumed=");
writer.print(mResumed); writer.print(" mStopped=");
writer.print(mStopped); writer.print(" mReallyStopped=");
writer.println(mReallyStopped);
writer.print(innerPrefix); writer.print("mLoadersStarted=");
writer.println(mLoadersStarted);
if (mLoaderManager != null) {
writer.print(prefix); writer.print("Loader Manager ");
writer.print(Integer.toHexString(System.identityHashCode(mLoaderManager)));
writer.println(":");
mLoaderManager.dump(prefix + " ", fd, writer, args);
}
mFragments.dump(prefix, fd, writer, args);
writer.print(prefix); writer.println("View Hierarchy:");
dumpViewHierarchy(prefix + " ", writer, getWindow().getDecorView());
}
private static String viewToString(View view) {
StringBuilder out = new StringBuilder(128);
out.append(view.getClass().getName());
out.append('{');
out.append(Integer.toHexString(System.identityHashCode(view)));
out.append(' ');
switch (view.getVisibility()) {
case View.VISIBLE: out.append('V'); break;
case View.INVISIBLE: out.append('I'); break;
case View.GONE: out.append('G'); break;
default: out.append('.'); break;
}
out.append(view.isFocusable() ? 'F' : '.');
out.append(view.isEnabled() ? 'E' : '.');
out.append(view.willNotDraw() ? '.' : 'D');
out.append(view.isHorizontalScrollBarEnabled()? 'H' : '.');
out.append(view.isVerticalScrollBarEnabled() ? 'V' : '.');
out.append(view.isClickable() ? 'C' : '.');
out.append(view.isLongClickable() ? 'L' : '.');
out.append(' ');
out.append(view.isFocused() ? 'F' : '.');
out.append(view.isSelected() ? 'S' : '.');
out.append(view.isPressed() ? 'P' : '.');
out.append(' ');
out.append(view.getLeft());
out.append(',');
out.append(view.getTop());
out.append('-');
out.append(view.getRight());
out.append(',');
out.append(view.getBottom());
final int id = view.getId();
if (id != View.NO_ID) {
out.append(" #");
out.append(Integer.toHexString(id));
final Resources r = view.getResources();
if (id != 0 && r != null) {
try {
String pkgname;
switch (id&0xff000000) {
case 0x7f000000:
pkgname="app";
break;
case 0x01000000:
pkgname="android";
break;
default:
pkgname = r.getResourcePackageName(id);
break;
}
String typename = r.getResourceTypeName(id);
String entryname = r.getResourceEntryName(id);
out.append(" ");
out.append(pkgname);
out.append(":");
out.append(typename);
out.append("/");
out.append(entryname);
} catch (Resources.NotFoundException e) {
}
}
}
out.append("}");
return out.toString();
}
private void dumpViewHierarchy(String prefix, PrintWriter writer, View view) {
writer.print(prefix);
if (view == null) {
writer.println("null");
return;
}
writer.println(viewToString(view));
if (!(view instanceof ViewGroup)) {
return;
}
ViewGroup grp = (ViewGroup)view;
final int N = grp.getChildCount();
if (N <= 0) {
return;
}
prefix = prefix + " ";
for (int i=0; i<N; i++) {
dumpViewHierarchy(prefix, writer, grp.getChildAt(i));
}
}
void doReallyStop(boolean retaining) {
if (!mReallyStopped) {
mReallyStopped = true;
mRetaining = retaining;
mHandler.removeMessages(MSG_REALLY_STOPPED);
onReallyStop();
}
}
/**
* Pre-HC, we didn't have a way to determine whether an activity was
* being stopped for a config change or not until we saw
* onRetainNonConfigurationInstance() called after onStop(). However
* we need to know this, to know whether to retain fragments. This will
* tell us what we need to know.
*/
void onReallyStop() {
if (mLoadersStarted) {
mLoadersStarted = false;
if (mLoaderManager != null) {
if (!mRetaining) {
mLoaderManager.doStop();
} else {
mLoaderManager.doRetain();
}
}
}
mFragments.dispatchReallyStop();
}
// ------------------------------------------------------------------------
// FRAGMENT SUPPORT
// ------------------------------------------------------------------------
/**
* Called when a fragment is attached to the activity.
*/
public void onAttachFragment(Fragment fragment) {
}
/**
* Return the FragmentManager for interacting with fragments associated
* with this activity.
*/
public FragmentManager getSupportFragmentManager() {
return mFragments;
}
/**
* Modifies the standard behavior to allow results to be delivered to fragments.
* This imposes a restriction that requestCode be <= 0xffff.
*/
@Override
public void startActivityForResult(Intent intent, int requestCode) {
if (requestCode != -1 && (requestCode&0xffff0000) != 0) {
throw new IllegalArgumentException("Can only use lower 16 bits for requestCode");
}
super.startActivityForResult(intent, requestCode);
}
/**
* Called by Fragment.startActivityForResult() to implement its behavior.
*/
public void startActivityFromFragment(Fragment fragment, Intent intent,
int requestCode) {
if (requestCode == -1) {
super.startActivityForResult(intent, -1);
return;
}
if ((requestCode&0xffff0000) != 0) {
throw new IllegalArgumentException("Can only use lower 16 bits for requestCode");
}
super.startActivityForResult(intent, ((fragment.mIndex+1)<<16) + (requestCode&0xffff));
}
void invalidateSupportFragment(String who) {
//Log.v(TAG, "invalidateSupportFragment: who=" + who);
if (mAllLoaderManagers != null) {
LoaderManagerImpl lm = mAllLoaderManagers.get(who);
if (lm != null && !lm.mRetaining) {
lm.doDestroy();
mAllLoaderManagers.remove(who);
}
}
}
// ------------------------------------------------------------------------
// LOADER SUPPORT
// ------------------------------------------------------------------------
/**
* Return the LoaderManager for this fragment, creating it if needed.
*/
public LoaderManager getSupportLoaderManager() {
if (mLoaderManager != null) {
return mLoaderManager;
}
mCheckedForLoaderManager = true;
mLoaderManager = getLoaderManager(null, mLoadersStarted, true);
return mLoaderManager;
}
LoaderManagerImpl getLoaderManager(String who, boolean started, boolean create) {
if (mAllLoaderManagers == null) {
mAllLoaderManagers = new HashMap<String, LoaderManagerImpl>();
}
LoaderManagerImpl lm = mAllLoaderManagers.get(who);
if (lm == null) {
if (create) {
lm = new LoaderManagerImpl(who, this, started);
mAllLoaderManagers.put(who, lm);
}
} else {
lm.updateActivity(this);
}
return lm;
}
}
| am e7200402: am d3de4f6d: Fix a bug in FragmentActivity menu panel preparation
* commit 'e7200402764bf29786dda9a77edac605cb0bf662':
Fix a bug in FragmentActivity menu panel preparation
| v4/java/android/support/v4/app/FragmentActivity.java | am e7200402: am d3de4f6d: Fix a bug in FragmentActivity menu panel preparation | <ide><path>4/java/android/support/v4/app/FragmentActivity.java
<ide> }
<ide> boolean goforit = super.onPreparePanel(featureId, view, menu);
<ide> goforit |= mFragments.dispatchPrepareOptionsMenu(menu);
<del> return goforit && menu.hasVisibleItems();
<add> return goforit;
<ide> }
<ide> return super.onPreparePanel(featureId, view, menu);
<ide> } |
|
JavaScript | mit | 8a22484352a49269e958d9579509259b1c6315a4 | 0 | brainshave/sharpvg,brainshave/sharpvg | "use strict";
module.exports = trace;
var I = require("ancient-oak");
function arr2d (h) {
var arr = I([]);
for (var i = 0; i < h; ++i) {
arr = arr.set(i, []);
}
return arr;
}
function trace (orientmap, w, h) {
var paths = lazy(function (state) {
var start = starting_point(orientmap,
state("coverage"),
points(w, h, state("start")));
return (start
? (trace_one(start, orientmap, state("coverage"))
.set("start", start))
: null);
}, {
start: { x: 0, y: 0 },
coverage: arr2d(h)
}).all().slice(1).map(function (state) {
return state("moves");
});
return flatten(paths);
}
function trace_one (start, orientmap, coverage) {
var result = lazy(function (state) {
var move = orientmap(state("y"))(state("x"));
// special case where we have to turn left from current
// direction.
if (move("next")) {
var moves = state("moves");
move = next_move_ccw(moves(moves.size - 1));
}
var x = state("x") + (move("h") || 0);
var y = state("y") + (move("v") || 0);
return (x === start("x") && y === start("y")
? null
: (state
.update("coverage", function (coverage) {
return deepset(coverage, y, x, true);
})
.update("moves", function (moves) {
return moves.push(move);
})
.set("x", x)
.set("y", y)));
}, {
x: start("x"),
y: start("y"),
moves: [{ x: start("x"), y: start("y") }],
coverage: deepset(coverage, start("y"), start("x"), true)
});
return result.last();
}
function deepset (object, key) {
var extra_path = Array.prototype.slice.call(arguments, 2, -1);
var value = arguments[arguments.length - 1];
return (extra_path.length === 0
? object.set(key, value)
: object.update(key, function (field) {
return deepset.apply(null, [field].concat(extra_path).concat([value]));
}));
}
function flatten(paths) {
return paths.reduce(function (agg, p) {
return p.reduce(function (agg, el) {
return agg.push(el);
}, agg);
}, I([]));
}
function inc (v) {
return v + 1;
}
function points (w, h, start) {
return lazy(function (point) {
return (point("x") < w - 1
? point.update("x", inc)
: point("y") < h - 1
? point.update("y", inc).set("x", 0)
: null);
}, start || {
x: 0, y: 0
});
}
function lazy (generator, value) {
value = I(value);
var list = Object.freeze({
value: value,
next: next,
find: find,
last: last,
all: all
});
return list;
function next () {
return lazy(generator, generator(value));
}
function find (condition) {
return lazy_find(list, condition);
}
function last (condition) {
return lazy_last(list);
}
function all () {
return lazy_all(list);
}
}
function lazy_last (list) {
var next = list;
while (next.value !== null) {
list = next;
next = next.next();
}
return list.value;
}
function lazy_all (list) {
var result = I([]);
while (list.value !== null) {
result = result.push(list.value);
list = list.next();
}
return result;
}
function lazy_find (list, condition) {
var head = list.value;
while (head !== null && condition(head)) {
list = list.next();
head = list.value;
}
return list;
}
function starting_point (orientmap, coverage, points) {
// find starting point that hasn't been covered yet.
return points.find(function (value) {
var x = value("x");
var y = value("y");
return !orientmap(y)(x) || coverage(y)(x);
}).value;
}
function next_move_ccw (move) {
return I(move("v") === -1
? { h: -1 }
: move("h") === -1
? { v: 1 }
: move("v") === 1
? { h: 1 }
: { v: -1 });
}
| lib/trace.js | "use strict";
module.exports = trace;
var I = require("ancient-oak");
function arr2d (h) {
var arr = I([]);
for (var i = 0; i < h; ++i) {
arr = arr.set(i, []);
}
return arr;
}
function trace (orientmap, w, h) {
var paths = lazy(function (state) {
var start = starting_point(orientmap, state("coverage"), points(w, h, state("start")));
return (start
? trace_one(start, orientmap, state("coverage")).set("start", start)
: null);
}, {
start: { x: 0, y: 0 },
coverage: arr2d(h)
}).all().slice(1).map(function (state) {
return state("moves");
});
return flatten(paths);
}
function flatten(paths) {
return paths.reduce(function (agg, p) {
return p.reduce(function (agg, el) {
return agg.push(el);
}, agg);
}, I([]));
}
function inc (v) {
return v + 1;
}
function points (w, h, start) {
return lazy(function (point) {
return (point("x") < w - 1
? point.update("x", inc)
: point("y") < h - 1
? point.update("y", inc).set("x", 0)
: null);
}, start || {
x: 0, y: 0
});
}
function lazy (generator, value) {
value = I(value);
var list = Object.freeze({
value: value,
next: next,
find: find,
all: all
});
return list;
function next () {
return lazy(generator, generator(value));
}
function find (condition) {
return lazy_find(list, condition);
}
function all () {
return lazy_all(list);
}
}
function lazy_all (list) {
var result = I([]);
while (list.value !== null) {
result = result.push(list.value);
list = list.next();
}
return result;
}
function lazy_find (list, condition) {
var head = list.value;
while (head !== null && condition(head)) {
list = list.next();
head = list.value;
}
return list;
}
function starting_point (orientmap, coverage, points) {
// find starting point that hasn't been covered yet.
return points.find(function (value) {
var x = value("x");
var y = value("y");
return !orientmap(y)(x) || coverage(y)(x);
}).value;
}
function trace_one (start, orientmap, coverage) {
var x = start("x");
var y = start("y");
var start_x = x;
var start_y = y;
var moves = I([{ x: x, y: y }]);
do {
coverage = coverage.update(y, function (row) {
return row.set(x, true);
});
var move = orientmap(y)(x);
// special case where we have to turn left from current
// direction.
if (move("next")) {
move = next_move_ccw(moves(moves.size - 1));
}
x += move("h") || 0;
y += move("v") || 0;
if (x === start_x && y === start_y) break;
moves = moves.push(move);
} while (true);
return I({
moves: moves,
coverage: coverage
})
}
function next_move_ccw (move) {
return I(move("v") === -1
? { h: -1 }
: move("h") === -1
? { v: 1 }
: move("v") === 1
? { h: 1 }
: { v: -1 });
}
| Functional trace_one.
| lib/trace.js | Functional trace_one. | <ide><path>ib/trace.js
<ide>
<ide> function trace (orientmap, w, h) {
<ide> var paths = lazy(function (state) {
<del> var start = starting_point(orientmap, state("coverage"), points(w, h, state("start")));
<add> var start = starting_point(orientmap,
<add> state("coverage"),
<add> points(w, h, state("start")));
<ide> return (start
<del> ? trace_one(start, orientmap, state("coverage")).set("start", start)
<add> ? (trace_one(start, orientmap, state("coverage"))
<add> .set("start", start))
<ide> : null);
<ide> }, {
<ide> start: { x: 0, y: 0 },
<ide> });
<ide>
<ide> return flatten(paths);
<add>}
<add>
<add>
<add>function trace_one (start, orientmap, coverage) {
<add> var result = lazy(function (state) {
<add> var move = orientmap(state("y"))(state("x"));
<add>
<add> // special case where we have to turn left from current
<add> // direction.
<add> if (move("next")) {
<add> var moves = state("moves");
<add> move = next_move_ccw(moves(moves.size - 1));
<add> }
<add>
<add> var x = state("x") + (move("h") || 0);
<add> var y = state("y") + (move("v") || 0);
<add>
<add> return (x === start("x") && y === start("y")
<add> ? null
<add> : (state
<add> .update("coverage", function (coverage) {
<add> return deepset(coverage, y, x, true);
<add> })
<add> .update("moves", function (moves) {
<add> return moves.push(move);
<add> })
<add> .set("x", x)
<add> .set("y", y)));
<add> }, {
<add> x: start("x"),
<add> y: start("y"),
<add> moves: [{ x: start("x"), y: start("y") }],
<add> coverage: deepset(coverage, start("y"), start("x"), true)
<add> });
<add>
<add> return result.last();
<add>}
<add>
<add>function deepset (object, key) {
<add> var extra_path = Array.prototype.slice.call(arguments, 2, -1);
<add> var value = arguments[arguments.length - 1];
<add>
<add> return (extra_path.length === 0
<add> ? object.set(key, value)
<add> : object.update(key, function (field) {
<add> return deepset.apply(null, [field].concat(extra_path).concat([value]));
<add> }));
<ide> }
<ide>
<ide> function flatten(paths) {
<ide> value: value,
<ide> next: next,
<ide> find: find,
<add> last: last,
<ide> all: all
<ide> });
<ide>
<ide> return lazy_find(list, condition);
<ide> }
<ide>
<add> function last (condition) {
<add> return lazy_last(list);
<add> }
<add>
<ide> function all () {
<ide> return lazy_all(list);
<ide> }
<add>}
<add>
<add>function lazy_last (list) {
<add> var next = list;
<add>
<add> while (next.value !== null) {
<add> list = next;
<add> next = next.next();
<add> }
<add>
<add> return list.value;
<ide> }
<ide>
<ide> function lazy_all (list) {
<ide> }).value;
<ide> }
<ide>
<del>function trace_one (start, orientmap, coverage) {
<del> var x = start("x");
<del> var y = start("y");
<del>
<del> var start_x = x;
<del> var start_y = y;
<del>
<del> var moves = I([{ x: x, y: y }]);
<del>
<del> do {
<del> coverage = coverage.update(y, function (row) {
<del> return row.set(x, true);
<del> });
<del>
<del> var move = orientmap(y)(x);
<del>
<del> // special case where we have to turn left from current
<del> // direction.
<del> if (move("next")) {
<del> move = next_move_ccw(moves(moves.size - 1));
<del> }
<del>
<del> x += move("h") || 0;
<del> y += move("v") || 0;
<del>
<del> if (x === start_x && y === start_y) break;
<del>
<del> moves = moves.push(move);
<del> } while (true);
<del>
<del> return I({
<del> moves: moves,
<del> coverage: coverage
<del> })
<del>}
<del>
<ide> function next_move_ccw (move) {
<ide> return I(move("v") === -1
<ide> ? { h: -1 } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.