repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
KDE/ocs-webserver
application/modules/default/models/Ocs/Gitlab/Exception.php
909
<?php /** * ocs-webserver * * Copyright 2016 by pling GmbH. * * This file is part of ocs-webserver. * * 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/>. * * Created: 19.06.2018 */ class Default_Model_Ocs_Gitlab_Exception extends Zend_Exception { }
agpl-3.0
HuntedHive/humhub-modules-questionanswer
views/answer/update.php
375
<?php /* @var $this AnswerController */ /* @var $model Answer */ ?> <div class="container"> <div class="row"> <div class="panel panel-default qanda-form"> <div class="panel-body"> <h1>Update Answer <?php echo $model->id; ?></h1> <?php $this->renderPartial('_form', array('model'=>$model)); ?> </div> </div> </div> </div>
agpl-3.0
KWZwickau/KREDA-Sphere
Library/Bootstrap/3.3.4/js/alert.js
2661
/* ======================================================================== * Bootstrap: alert.js v3.3.4 * http://getbootstrap.com/javascript/#alerts * ======================================================================== * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function( $ ) { 'use strict'; // ALERT CLASS DEFINITION // ====================== var dismiss = '[data-dismiss="alert"]'; var Alert = function( el ) { $( el ).on( 'click', dismiss, this.close ) }; Alert.VERSION = '3.3.4'; Alert.TRANSITION_DURATION = 150; Alert.prototype.close = function( e ) { var $this = $( this ); var selector = $this.attr( 'data-target' ); if (!selector) { selector = $this.attr( 'href' ); selector = selector && selector.replace( /.*(?=#[^\s]*$)/, '' ); // strip for ie7 } var $parent = $( selector ); if (e) { e.preventDefault(); } if (!$parent.length) { $parent = $this.closest( '.alert' ) } $parent.trigger( e = $.Event( 'close.bs.alert' ) ); if (e.isDefaultPrevented()) { return; } $parent.removeClass( 'in' ); function removeElement() { // detach from parent, fire event then clean up data $parent.detach().trigger( 'closed.bs.alert' ).remove() } $.support.transition && $parent.hasClass( 'fade' ) ? $parent .one( 'bsTransitionEnd', removeElement ) .emulateTransitionEnd( Alert.TRANSITION_DURATION ) : removeElement() }; // ALERT PLUGIN DEFINITION // ======================= function Plugin( option ) { return this.each( function() { var $this = $( this ); var data = $this.data( 'bs.alert' ); if (!data) { $this.data( 'bs.alert', (data = new Alert( this )) ); } if (typeof option == 'string') { data[option].call( $this ) } } ) } var old = $.fn.alert; $.fn.alert = Plugin; $.fn.alert.Constructor = Alert; // ALERT NO CONFLICT // ================= $.fn.alert.noConflict = function() { $.fn.alert = old; return this }; // ALERT DATA-API // ============== $( document ).on( 'click.bs.alert.data-api', dismiss, Alert.prototype.close ) }( jQuery );
agpl-3.0
doxel/doxel-website
data/tiger/pmvs_options.tiger.ply_converted/build/shaders/shaders.js
22298
Potree.Shaders["pointcloud.vs"] = [ "", "// the following is an incomplete list of attributes, uniforms and defines", "// which are automatically added through the THREE.ShaderMaterial", "", "//attribute vec3 position;", "//attribute vec3 color;", "//attribute vec3 normal;", "", "//uniform mat4 modelMatrix;", "//uniform mat4 modelViewMatrix;", "//uniform mat4 projectionMatrix;", "//uniform mat4 viewMatrix;", "//uniform mat3 normalMatrix;", "//uniform vec3 cameraPosition;", "", "//#define MAX_DIR_LIGHTS 0", "//#define MAX_POINT_LIGHTS 1", "//#define MAX_SPOT_LIGHTS 0", "//#define MAX_HEMI_LIGHTS 0", "//#define MAX_SHADOWS 0", "//#define MAX_BONES 58", "", "#define max_clip_boxes 30", "", "attribute float intensity;", "attribute float classification;", "attribute float returnNumber;", "attribute float pointSourceID;", "attribute vec4 indices;", "", "uniform float screenWidth;", "uniform float screenHeight;", "uniform float fov;", "uniform float spacing;", "uniform float near;", "uniform float far;", "", "#if defined use_clip_box", " uniform mat4 clipBoxes[max_clip_boxes];", "#endif", "", "", "uniform float heightMin;", "uniform float heightMax;", "uniform float intensityMin;", "uniform float intensityMax;", "uniform float size; // pixel size factor", "uniform float minSize; // minimum pixel size", "uniform float maxSize; // maximum pixel size", "uniform float octreeSize;", "uniform vec3 bbSize;", "uniform vec3 uColor;", "uniform float opacity;", "uniform float clipBoxCount;", "", "", "uniform sampler2D visibleNodes;", "uniform sampler2D gradient;", "uniform sampler2D classificationLUT;", "uniform sampler2D depthMap;", "", "varying float vOpacity;", "varying vec3 vColor;", "varying float vLinearDepth;", "varying float vLogDepth;", "varying vec3 vViewPosition;", "varying float vRadius;", "varying vec3 vWorldPosition;", "varying vec3 vNormal;", "", "", "// ---------------------", "// OCTREE", "// ---------------------", "", "#if (defined(adaptive_point_size) || defined(color_type_tree_depth)) && defined(tree_type_octree)", "/**", " * number of 1-bits up to inclusive index position", " * number is treated as if it were an integer in the range 0-255", " *", " */", "float numberOfOnes(float number, float index){", " float tmp = mod(number, pow(2.0, index + 1.0));", " float numOnes = 0.0;", " for(float i = 0.0; i < 8.0; i++){", " if(mod(tmp, 2.0) != 0.0){", " numOnes++;", " }", " tmp = floor(tmp / 2.0);", " }", " return numOnes;", "}", "", "", "/**", " * checks whether the bit at index is 1", " * number is treated as if it were an integer in the range 0-255", " *", " */", "bool isBitSet(float number, float index){", " return mod(floor(number / pow(2.0, index)), 2.0) != 0.0;", "}", "", "", "/**", " * find the tree depth at the point position", " */", "float getLocalTreeDepth(){", " vec3 offset = vec3(0.0, 0.0, 0.0);", " float iOffset = 0.0;", " float depth = 0.0;", " for(float i = 0.0; i <= 1000.0; i++){", " float nodeSizeAtLevel = octreeSize / pow(2.0, i);", " vec3 index3d = (position - offset) / nodeSizeAtLevel;", " index3d = floor(index3d + 0.5);", " float index = 4.0*index3d.x + 2.0*index3d.y + index3d.z;", " ", " vec4 value = texture2D(visibleNodes, vec2(iOffset / 2048.0, 0.0));", " float mask = value.r * 255.0;", " if(isBitSet(mask, index)){", " // there are more visible child nodes at this position", " iOffset = iOffset + value.g * 255.0 + numberOfOnes(mask, index - 1.0);", " depth++;", " }else{", " // no more visible child nodes at this position", " return depth;", " }", " offset = offset + (vec3(1.0, 1.0, 1.0) * nodeSizeAtLevel * 0.5) * index3d;", " }", " ", " return depth;", "}", "", "float getPointSizeAttenuation(){", " return pow(1.9, getLocalTreeDepth());", "}", "", "", "#endif", "", "", "// ---------------------", "// KD-TREE", "// ---------------------", "", "#if (defined(adaptive_point_size) || defined(color_type_tree_depth)) && defined(tree_type_kdtree)", "", "float getLocalTreeDepth(){", " vec3 offset = vec3(0.0, 0.0, 0.0);", " float iOffset = 0.0;", " float depth = 0.0;", " ", " ", " vec3 size = bbSize; ", " vec3 pos = position;", " ", " for(float i = 0.0; i <= 1000.0; i++){", " ", " vec4 value = texture2D(visibleNodes, vec2(iOffset / 2048.0, 0.0));", " ", " int children = int(value.r * 255.0);", " float next = value.g * 255.0;", " int split = int(value.b * 255.0);", " ", " if(next == 0.0){", " return depth;", " }", " ", " vec3 splitv = vec3(0.0, 0.0, 0.0);", " if(split == 1){", " splitv.x = 1.0;", " }else if(split == 2){", " splitv.y = 1.0;", " }else if(split == 4){", " splitv.z = 1.0;", " }", " ", " iOffset = iOffset + next;", " ", " float factor = length(pos * splitv / size);", " if(factor < 0.5){", " // left", " if(children == 0 || children == 2){", " return depth;", " }", " }else{", " // right", " pos = pos - size * splitv * 0.5;", " if(children == 0 || children == 1){", " return depth;", " }", " if(children == 3){", " iOffset = iOffset + 1.0;", " }", " }", " size = size * ((1.0 - (splitv + 1.0) / 2.0) + 0.5);", " ", " depth++;", " }", " ", " ", " return depth; ", "}", "", "float getPointSizeAttenuation(){", " return pow(1.3, getLocalTreeDepth());", "}", "", "#endif", "", "void main() {", " vec4 worldPosition = modelMatrix * vec4( position, 1.0 );", " vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );", " vViewPosition = -mvPosition.xyz;", " vWorldPosition = worldPosition.xyz;", " gl_Position = projectionMatrix * mvPosition;", " vOpacity = opacity;", " vLinearDepth = -mvPosition.z;", " vNormal = normalize(normalMatrix * normal);", " ", " #if defined(use_edl)", " vLogDepth = log2(gl_Position.w + 1.0) / log2(far + 1.0);", " #endif", " ", " //#if defined(use_logarithmic_depth_buffer)", " // float logarithmicZ = (2.0 * log2(gl_Position.w + 1.0) / log2(far + 1.0) - 1.0) * gl_Position.w;", " // gl_Position.z = logarithmicZ;", " //#endif", "", " // ---------------------", " // POINT COLOR", " // ---------------------", " ", " #ifdef color_type_rgb", " vColor = color;", " #elif defined color_type_height", " vec4 world = modelMatrix * vec4( position, 1.0 );", " float w = (world.y - heightMin) / (heightMax-heightMin);", " vColor = texture2D(gradient, vec2(w,1.0-w)).rgb;", " #elif defined color_type_depth", " float linearDepth = -mvPosition.z ;", " float expDepth = (gl_Position.z / gl_Position.w) * 0.5 + 0.5;", " vColor = vec3(linearDepth, expDepth, 0.0);", " #elif defined color_type_intensity", " float w = (intensity - intensityMin) / (intensityMax - intensityMin);", " vColor = vec3(w, w, w);", " #elif defined color_type_intensity_gradient", " float w = (intensity - intensityMin) / intensityMax;", " vColor = texture2D(gradient, vec2(w,1.0-w)).rgb;", " #elif defined color_type_color", " vColor = uColor;", " #elif defined color_type_tree_depth", " float depth = getLocalTreeDepth();", " float w = depth / 10.0;", " vColor = texture2D(gradient, vec2(w,1.0-w)).rgb;", " #elif defined color_type_point_index", " vColor = indices.rgb;", " #elif defined color_type_classification", " float c = mod(classification, 16.0);", " vec2 uv = vec2(c / 255.0, 0.5);", " vColor = texture2D(classificationLUT, uv).rgb;", " ", " // TODO only for testing - removing points with class 7", " if(classification == 7.0){", " gl_Position = vec4(100.0, 100.0, 100.0, 0.0);", " }", " #elif defined color_type_return_number", " float w = (returnNumber - 1.0) / 4.0 + 0.1;", " vColor = texture2D(gradient, vec2(w, 1.0 - w)).rgb;", " #elif defined color_type_source", " float w = mod(pointSourceID, 10.0) / 10.0;", " vColor = texture2D(gradient, vec2(w,1.0 - w)).rgb;", " #elif defined color_type_normal", " vColor = (modelMatrix * vec4(normal, 0.0)).xyz;", " #elif defined color_type_phong", " vColor = color;", " #endif", " ", " //if(vNormal.z < 0.0){", " // gl_Position = vec4(1000.0, 1000.0, 1000.0, 1.0);", " //}", " ", " // ---------------------", " // POINT SIZE", " // ---------------------", " float pointSize = 1.0;", " ", " float projFactor = 1.0 / tan(fov / 2.0);", " projFactor /= vViewPosition.z;", " projFactor *= screenHeight / 2.0;", " float r = spacing * 1.5;", " vRadius = r;", " #if defined fixed_point_size", " pointSize = size;", " #elif defined attenuated_point_size", " pointSize = size * projFactor;", " #elif defined adaptive_point_size", " float worldSpaceSize = size * r / getPointSizeAttenuation();", " pointSize = worldSpaceSize * projFactor;", " #endif", "", " pointSize = max(minSize, pointSize);", " pointSize = min(maxSize, pointSize);", " ", " vRadius = pointSize / projFactor;", " ", " gl_PointSize = pointSize;", " ", " ", " // ---------------------", " // CLIPPING", " // ---------------------", " ", " #if defined use_clip_box", " bool insideAny = false;", " for(int i = 0; i < max_clip_boxes; i++){", " if(i == int(clipBoxCount)){", " break;", " }", " ", " vec4 clipPosition = clipBoxes[i] * modelMatrix * vec4( position, 1.0 );", " bool inside = -0.5 <= clipPosition.x && clipPosition.x <= 0.5;", " inside = inside && -0.5 <= clipPosition.y && clipPosition.y <= 0.5;", " inside = inside && -0.5 <= clipPosition.z && clipPosition.z <= 0.5;", " insideAny = insideAny || inside;", " }", " if(!insideAny){", " ", " #if defined clip_outside", " gl_Position = vec4(1000.0, 1000.0, 1000.0, 1.0);", " #elif defined clip_highlight_inside && !defined(color_type_depth)", " float c = (vColor.r + vColor.g + vColor.b) / 6.0;", " #endif", " }else{", " #if defined clip_highlight_inside", " vColor.r += 0.5;", " #endif", " }", " ", " #endif", " ", "}", "", ].join("\n"); Potree.Shaders["pointcloud.fs"] = [ "", "#if defined use_interpolation", " #extension GL_EXT_frag_depth : enable", "#endif", "", "", "// the following is an incomplete list of attributes, uniforms and defines", "// which are automatically added through the THREE.ShaderMaterial", "", "// #define USE_COLOR", "// ", "// uniform mat4 viewMatrix;", "// uniform vec3 cameraPosition;", "", "", "uniform mat4 projectionMatrix;", "uniform float opacity;", "", "", "#if defined(color_type_phong)", "", " uniform vec3 diffuse;", " uniform vec3 ambient;", " uniform vec3 emissive;", " uniform vec3 specular;", " uniform float shininess;", " uniform vec3 ambientLightColor;", "", " #if MAX_POINT_LIGHTS > 0", "", " uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];", " uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];", " uniform float pointLightDistance[ MAX_POINT_LIGHTS ];", "", " #endif", "", " #if MAX_DIR_LIGHTS > 0", "", " uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];", " uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];", "", " #endif", "", "#endif", "", "//#if MAX_SPOT_LIGHTS > 0", "//", "// uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];", "// uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];", "// uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];", "// uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];", "// uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];", "//", "// uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];", "//", "//#endif", "", "uniform float fov;", "uniform float spacing;", "uniform float near;", "uniform float far;", "uniform float pcIndex;", "uniform float screenWidth;", "uniform float screenHeight;", "", "uniform sampler2D depthMap;", "", "varying vec3 vColor;", "varying float vOpacity;", "varying float vLinearDepth;", "varying float vLogDepth;", "varying vec3 vViewPosition;", "varying float vRadius;", "varying vec3 vWorldPosition;", "varying vec3 vNormal;", "", "float specularStrength = 1.0;", "", "void main() {", "", " vec3 color = vColor;", " float depth = gl_FragCoord.z;", "", " #if defined(circle_point_shape) || defined(use_interpolation) || defined (weighted_splats)", " float u = 2.0 * gl_PointCoord.x - 1.0;", " float v = 2.0 * gl_PointCoord.y - 1.0;", " #endif", " ", " #if defined(circle_point_shape) || defined (weighted_splats)", " float cc = u*u + v*v;", " if(cc > 1.0){", " discard;", " }", " #endif", " ", " #if defined weighted_splats", " vec2 uv = gl_FragCoord.xy / vec2(screenWidth, screenHeight);", " float sDepth = texture2D(depthMap, uv).r;", " if(vLinearDepth > sDepth + vRadius){", " discard;", " }", " #endif", " ", " #if defined use_interpolation", " float wi = 0.0 - ( u*u + v*v);", " vec4 pos = vec4(-vViewPosition, 1.0);", " pos.z += wi * vRadius;", " float linearDepth = pos.z;", " pos = projectionMatrix * pos;", " pos = pos / pos.w;", " float expDepth = pos.z;", " depth = (pos.z + 1.0) / 2.0;", " gl_FragDepthEXT = depth;", " ", " #if defined(color_type_depth)", " color.r = linearDepth;", " color.g = expDepth;", " #endif", " ", " #endif", " ", " #if defined color_type_point_index", " gl_FragColor = vec4(color, pcIndex / 255.0);", " #else", " gl_FragColor = vec4(color, vOpacity);", " #endif", " ", " #if defined weighted_splats", " float w = pow(1.0 - (u*u + v*v), 2.0);", " gl_FragColor.rgb = gl_FragColor.rgb * w;", " gl_FragColor.a = w;", " #endif", " ", " vec3 normal = normalize( vNormal );", " normal.z = abs(normal.z);", " vec3 viewPosition = normalize( vViewPosition );", " ", " #if defined(color_type_phong)", "", " // code taken from three.js phong light fragment shader", " ", " #if MAX_POINT_LIGHTS > 0", "", " vec3 pointDiffuse = vec3( 0.0 );", " vec3 pointSpecular = vec3( 0.0 );", "", " for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {", "", " vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );", " vec3 lVector = lPosition.xyz + vViewPosition.xyz;", "", " float lDistance = 1.0;", " if ( pointLightDistance[ i ] > 0.0 )", " lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );", "", " lVector = normalize( lVector );", "", " // diffuse", "", " float dotProduct = dot( normal, lVector );", "", " #ifdef WRAP_AROUND", "", " float pointDiffuseWeightFull = max( dotProduct, 0.0 );", " float pointDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );", "", " vec3 pointDiffuseWeight = mix( vec3( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );", "", " #else", "", " float pointDiffuseWeight = max( dotProduct, 0.0 );", "", " #endif", "", " pointDiffuse += diffuse * pointLightColor[ i ] * pointDiffuseWeight * lDistance;", "", " // specular", "", " vec3 pointHalfVector = normalize( lVector + viewPosition );", " float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );", " float pointSpecularWeight = specularStrength * max( pow( pointDotNormalHalf, shininess ), 0.0 );", "", " float specularNormalization = ( shininess + 2.0 ) / 8.0;", "", " vec3 schlick = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVector, pointHalfVector ), 0.0 ), 5.0 );", " pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance * specularNormalization;", " pointSpecular = vec3(0.0, 0.0, 0.0);", " }", " ", " #endif", " ", " #if MAX_DIR_LIGHTS > 0", "", " vec3 dirDiffuse = vec3( 0.0 );", " vec3 dirSpecular = vec3( 0.0 );", "", " for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {", "", " vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );", " vec3 dirVector = normalize( lDirection.xyz );", "", " // diffuse", "", " float dotProduct = dot( normal, dirVector );", "", " #ifdef WRAP_AROUND", "", " float dirDiffuseWeightFull = max( dotProduct, 0.0 );", " float dirDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );", "", " vec3 dirDiffuseWeight = mix( vec3( dirDiffuseWeightFull ), vec3( dirDiffuseWeightHalf ), wrapRGB );", "", " #else", "", " float dirDiffuseWeight = max( dotProduct, 0.0 );", "", " #endif", "", " dirDiffuse += diffuse * directionalLightColor[ i ] * dirDiffuseWeight;", "", " // specular", "", " vec3 dirHalfVector = normalize( dirVector + viewPosition );", " float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );", " float dirSpecularWeight = specularStrength * max( pow( dirDotNormalHalf, shininess ), 0.0 );", "", " float specularNormalization = ( shininess + 2.0 ) / 8.0;", "", " vec3 schlick = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( dirVector, dirHalfVector ), 0.0 ), 5.0 );", " dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;", " }", "", " #endif", " ", " vec3 totalDiffuse = vec3( 0.0 );", " vec3 totalSpecular = vec3( 0.0 );", " ", " #if MAX_POINT_LIGHTS > 0", "", " totalDiffuse += pointDiffuse;", " totalSpecular += pointSpecular;", "", " #endif", " ", " #if MAX_DIR_LIGHTS > 0", "", " totalDiffuse += dirDiffuse;", " totalSpecular += dirSpecular;", "", " #endif", " ", " gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient ) + totalSpecular;", "", " #endif", " ", " ", " #if defined(use_edl)", " gl_FragColor.a = vLogDepth;", " #endif", " ", "}", "", "", "", ].join("\n"); Potree.Shaders["normalize.vs"] = [ "", "varying vec2 vUv;", "", "void main() {", " vUv = uv;", "", " gl_Position = projectionMatrix * modelViewMatrix * vec4(position,1.0);", "}", ].join("\n"); Potree.Shaders["normalize.fs"] = [ "", "#extension GL_EXT_frag_depth : enable", "", "uniform sampler2D depthMap;", "uniform sampler2D texture;", "", "varying vec2 vUv;", "", "void main() {", " float depth = texture2D(depthMap, vUv).g; ", " ", " if(depth <= 0.0){", " discard;", " }", " ", " vec4 color = texture2D(texture, vUv); ", " color = color / color.w;", " ", " gl_FragColor = vec4(color.xyz, 1.0); ", " ", " gl_FragDepthEXT = depth;", "}", ].join("\n"); Potree.Shaders["edl.vs"] = [ "", "", "varying vec2 vUv;", "", "void main() {", " vUv = uv;", " ", " vec4 mvPosition = modelViewMatrix * vec4(position,1.0);", "", " gl_Position = projectionMatrix * mvPosition;", "}", ].join("\n"); Potree.Shaders["edl.fs"] = [ "", "// ", "// adapted from the EDL shader code from Christian Boucheny in cloud compare:", "// https://github.com/cloudcompare/trunk/tree/master/plugins/qEDL/shaders/EDL", "//", "", "#define NEIGHBOUR_COUNT 8", "", "uniform mat4 projectionMatrix;", "", "uniform float screenWidth;", "uniform float screenHeight;", "uniform float near;", "uniform float far;", "uniform vec2 neighbours[NEIGHBOUR_COUNT];", "uniform vec3 lightDir;", "uniform float expScale;", "uniform float radius;", "", "//uniform sampler2D depthMap;", "uniform sampler2D colorMap;", "", "varying vec2 vUv;", "", "/**", " * transform linear depth to [0,1] interval with 1 beeing closest to the camera.", " */", "float ztransform(float linearDepth){", " return 1.0 - (linearDepth - near) / (far - near);", "}", "", "float expToLinear(float z){", " z = 2.0 * z - 1.0;", " float linear = (2.0 * near * far) / (far + near - z * (far - near));", "", " return linear;", "}", "", "// this actually only returns linear depth values if LOG_BIAS is 1.0", "// lower values work out more nicely, though.", "#define LOG_BIAS 0.01", "float logToLinear(float z){", " return (pow((1.0 + LOG_BIAS * far), z) - 1.0) / LOG_BIAS;", "}", "", "float obscurance(float z, float dist){", " return max(0.0, z) / dist;", "}", "", "float computeObscurance(float linearDepth){", " vec4 P = vec4(0, 0, 1, -ztransform(linearDepth));", " vec2 uvRadius = radius / vec2(screenWidth, screenHeight);", " ", " float sum = 0.0;", " ", " for(int c = 0; c < NEIGHBOUR_COUNT; c++){", " vec2 N_rel_pos = uvRadius * neighbours[c];", " vec2 N_abs_pos = vUv + N_rel_pos;", " ", " float neighbourDepth = logToLinear(texture2D(colorMap, N_abs_pos).a);", " ", " if(neighbourDepth != 0.0){", " float Zn = ztransform(neighbourDepth);", " float Znp = dot( vec4( N_rel_pos, Zn, 1.0), P );", " ", " sum += obscurance( Znp, 0.05 * linearDepth );", " }", " }", " ", " return sum;", "}", "", "void main(){", " float linearDepth = logToLinear(texture2D(colorMap, vUv).a);", " ", " float f = computeObscurance(linearDepth);", " f = exp(-expScale * f);", " ", " vec4 color = texture2D(colorMap, vUv);", " if(color.a == 0.0 && f >= 1.0){", " discard;", " }", " ", " gl_FragColor = vec4(color.rgb * f, 1.0);", "}", "", ].join("\n"); Potree.Shaders["blur.vs"] = [ "", "varying vec2 vUv;", "", "void main() {", " vUv = uv;", "", " gl_Position = projectionMatrix * modelViewMatrix * vec4(position,1.0);", "}", ].join("\n"); Potree.Shaders["blur.fs"] = [ "", "uniform mat4 projectionMatrix;", "", "uniform float screenWidth;", "uniform float screenHeight;", "uniform float near;", "uniform float far;", "", "uniform sampler2D map;", "", "varying vec2 vUv;", "", "void main() {", "", " float dx = 1.0 / screenWidth;", " float dy = 1.0 / screenHeight;", "", " vec3 color = vec3(0.0, 0.0, 0.0);", " color += texture2D(map, vUv + vec2(-dx, -dy)).rgb;", " color += texture2D(map, vUv + vec2( 0, -dy)).rgb;", " color += texture2D(map, vUv + vec2(+dx, -dy)).rgb;", " color += texture2D(map, vUv + vec2(-dx, 0)).rgb;", " color += texture2D(map, vUv + vec2( 0, 0)).rgb;", " color += texture2D(map, vUv + vec2(+dx, 0)).rgb;", " color += texture2D(map, vUv + vec2(-dx, dy)).rgb;", " color += texture2D(map, vUv + vec2( 0, dy)).rgb;", " color += texture2D(map, vUv + vec2(+dx, dy)).rgb;", " ", " color = color / 9.0;", " ", " gl_FragColor = vec4(color, 1.0);", " ", " ", "}", ].join("\n");
agpl-3.0
bheisig/phonesync
lib/lang.php
566
<?php namespace org\benjaminheisig\phonesync; /** * Translates a value and replaces placeholders. This is a combination of * gettext() and sprintf(). * * @param string $value Value * @param array $args (optional) Replacements * * @return string * * @see gettext() * @see sprintf() */ function gettextf($value, $args = null) { assert('is_string($value)'); $numArgs = func_num_args(); assert('$numArgs >= 2'); $argList = func_get_args(); $value = gettext($value); return call_user_func_array('sprintf', $argList); } //function ?>
agpl-3.0
Seldaiendil/meyeOS
devtools/qooxdoo-1.5-sdk/framework/source/class/qx/ui/layout/Grid.js
40317
/* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Fabian Jakobs (fjakobs) ************************************************************************ */ /** * The grid layout manager arranges the items in a two dimensional * grid. Widgets can be placed into the grid's cells and may span multiple rows * and columns. * * *Features* * * * Flex values for rows and columns * * Minimal and maximal column and row sizes * * Manually setting of column and row sizes * * Horizontal and vertical alignment * * Horizontal and vertical spacing * * Column and row spans * * Auto-sizing * * *Item Properties* * * <ul> * <li><strong>row</strong> <em>(Integer)</em>: The row of the cell the * widget should occupy. Each cell can only contain one widget. This layout * property is mandatory. * </li> * <li><strong>column</strong> <em>(Integer)</em>: The column of the cell the * widget should occupy. Each cell can only contain one widget. This layout * property is mandatory. * </li> * <li><strong>rowSpan</strong> <em>(Integer)</em>: The number of rows, the * widget should span, starting from the row specified in the <code>row</code> * property. The cells in the spanned rows must be empty as well. * </li> * <li><strong>colSpan</strong> <em>(Integer)</em>: The number of columns, the * widget should span, starting from the column specified in the <code>column</code> * property. The cells in the spanned columns must be empty as well. * </li> * </ul> * * *Example* * * Here is a little example of how to use the grid layout. * * <pre class="javascript"> * var layout = new qx.ui.layout.Grid(); * layout.setRowFlex(0, 1); // make row 0 flexible * layout.setColumnWidth(1, 200); // set with of column 1 to 200 pixel * * var container = new qx.ui.container.Composite(layout); * container.add(new qx.ui.core.Widget(), {row: 0, column: 0}); * container.add(new qx.ui.core.Widget(), {row: 0, column: 1}); * container.add(new qx.ui.core.Widget(), {row: 1, column: 0, rowSpan: 2}); * </pre> * * *External Documentation* * * <a href='http://manual.qooxdoo.org/1.4/pages/layout/grid.html'> * Extended documentation</a> and links to demos of this layout in the qooxdoo manual. */ qx.Class.define("qx.ui.layout.Grid", { extend : qx.ui.layout.Abstract, /* ***************************************************************************** CONSTRUCTOR ***************************************************************************** */ /** * @param spacingX {Integer?0} The horizontal spacing between grid cells. * Sets {@link #spacingX}. * @param spacingY {Integer?0} The vertical spacing between grid cells. * Sets {@link #spacingY}. */ construct : function(spacingX, spacingY) { this.base(arguments); this.__rowData = []; this.__colData = []; if (spacingX) { this.setSpacingX(spacingX); } if (spacingY) { this.setSpacingY(spacingY); } }, /* ***************************************************************************** PROPERTIES ***************************************************************************** */ properties : { /** * The horizontal spacing between grid cells. */ spacingX : { check : "Integer", init : 0, apply : "_applyLayoutChange" }, /** * The vertical spacing between grid cells. */ spacingY : { check : "Integer", init : 0, apply : "_applyLayoutChange" } }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { /** {Array} 2D array of grid cell data */ __grid : null, __rowData : null, __colData : null, __colSpans : null, __rowSpans : null, __maxRowIndex : null, __maxColIndex : null, /** {Array} cached row heights */ __rowHeights : null, /** {Array} cached column widths */ __colWidths : null, // overridden verifyLayoutProperty : qx.core.Environment.select("qx.debug", { "true" : function(item, name, value) { var layoutProperties = { "row" : 1, "column" : 1, "rowSpan" : 1, "colSpan" : 1 } this.assert(layoutProperties[name] == 1, "The property '"+name+"' is not supported by the Grid layout!"); this.assertInteger(value); this.assert(value >= 0, "Value must be positive"); }, "false" : null }), /** * Rebuild the internal representation of the grid */ __buildGrid : function() { var grid = []; var colSpans = []; var rowSpans = []; var maxRowIndex = -1; var maxColIndex = -1; var children = this._getLayoutChildren(); for (var i=0,l=children.length; i<l; i++) { var child = children[i]; var props = child.getLayoutProperties(); var row = props.row; var column = props.column; props.colSpan = props.colSpan || 1; props.rowSpan = props.rowSpan || 1; // validate arguments if (row == null || column == null) { throw new Error( "The layout properties 'row' and 'column' of the child widget '" + child + "' must be defined!" ); } if (grid[row] && grid[row][column]) { throw new Error( "Cannot add widget '" + child + "'!. " + "There is already a widget '" + grid[row][column] + "' in this cell (" + row + ", " + column + ")" ); } for (var x=column; x<column+props.colSpan; x++) { for (var y=row; y<row+props.rowSpan; y++) { if (grid[y] == undefined) { grid[y] = []; } grid[y][x] = child; maxColIndex = Math.max(maxColIndex, x); maxRowIndex = Math.max(maxRowIndex, y); } } if (props.rowSpan > 1) { rowSpans.push(child); } if (props.colSpan > 1) { colSpans.push(child); } } // make sure all columns are defined so that accessing the grid using // this.__grid[column][row] will never raise an exception for (var y=0; y<=maxRowIndex; y++) { if (grid[y] == undefined) { grid[y] = []; } } this.__grid = grid; this.__colSpans = colSpans; this.__rowSpans = rowSpans; this.__maxRowIndex = maxRowIndex; this.__maxColIndex = maxColIndex; this.__rowHeights = null; this.__colWidths = null; // Clear invalidation marker delete this._invalidChildrenCache; }, /** * Stores data for a grid row * * @param row {Integer} The row index * @param key {String} The key under which the data should be stored * @param value {var} data to store */ _setRowData : function(row, key, value) { var rowData = this.__rowData[row]; if (!rowData) { this.__rowData[row] = {}; this.__rowData[row][key] = value; } else { rowData[key] = value; } }, /** * Stores data for a grid column * * @param column {Integer} The column index * @param key {String} The key under which the data should be stored * @param value {var} data to store */ _setColumnData : function(column, key, value) { var colData = this.__colData[column]; if (!colData) { this.__colData[column] = {}; this.__colData[column][key] = value; } else { colData[key] = value; } }, /** * Shortcut to set both horizontal and vertical spacing between grid cells * to the same value. * * @param spacing {Integer} new horizontal and vertical spacing * @return {qx.ui.layout.Grid} This object (for chaining support). */ setSpacing : function(spacing) { this.setSpacingY(spacing); this.setSpacingX(spacing); return this; }, /** * Set the default cell alignment for a column. This alignment can be * overridden on a per cell basis by setting the cell's content widget's * <code>alignX</code> and <code>alignY</code> properties. * * If on a grid cell both row and a column alignment is set, the horizontal * alignment is taken from the column and the vertical alignment is taken * from the row. * * @param column {Integer} Column index * @param hAlign {String} The horizontal alignment. Valid values are * "left", "center" and "right". * @param vAlign {String} The vertical alignment. Valid values are * "top", "middle", "bottom" * @return {qx.ui.layout.Grid} This object (for chaining support) */ setColumnAlign : function(column, hAlign, vAlign) { if (qx.core.Environment.get("qx.debug")) { this.assertInteger(column, "Invalid parameter 'column'"); this.assertInArray(hAlign, ["left", "center", "right"]); this.assertInArray(vAlign, ["top", "middle", "bottom"]); } this._setColumnData(column, "hAlign", hAlign); this._setColumnData(column, "vAlign", vAlign); this._applyLayoutChange(); return this; }, /** * Get a map of the column's alignment. * * @param column {Integer} The column index * @return {Map} A map with the keys <code>vAlign</code> and <code>hAlign</code> * containing the vertical and horizontal column alignment. */ getColumnAlign : function(column) { var colData = this.__colData[column] || {}; return { vAlign : colData.vAlign || "top", hAlign : colData.hAlign || "left" }; }, /** * Set the default cell alignment for a row. This alignment can be * overridden on a per cell basis by setting the cell's content widget's * <code>alignX</code> and <code>alignY</code> properties. * * If on a grid cell both row and a column alignment is set, the horizontal * alignment is taken from the column and the vertical alignment is taken * from the row. * * @param row {Integer} Row index * @param hAlign {String} The horizontal alignment. Valid values are * "left", "center" and "right". * @param vAlign {String} The vertical alignment. Valid values are * "top", "middle", "bottom" * @return {qx.ui.layout.Grid} This object (for chaining support) */ setRowAlign : function(row, hAlign, vAlign) { if (qx.core.Environment.get("qx.debug")) { this.assertInteger(row, "Invalid parameter 'row'"); this.assertInArray(hAlign, ["left", "center", "right"]); this.assertInArray(vAlign, ["top", "middle", "bottom"]); } this._setRowData(row, "hAlign", hAlign); this._setRowData(row, "vAlign", vAlign); this._applyLayoutChange(); return this; }, /** * Get a map of the row's alignment. * * @param row {Integer} The Row index * @return {Map} A map with the keys <code>vAlign</code> and <code>hAlign</code> * containing the vertical and horizontal row alignment. */ getRowAlign : function(row) { var rowData = this.__rowData[row] || {}; return { vAlign : rowData.vAlign || "top", hAlign : rowData.hAlign || "left" }; }, /** * Get the widget located in the cell. If a the cell is empty or the widget * has a {@link qx.ui.core.Widget#visibility} value of <code>exclude</code>, * <code>null</code> is returned. * * @param row {Integer} The cell's row index * @param column {Integer} The cell's column index * @return {qx.ui.core.Widget|null}The cell's widget. The value may be null. */ getCellWidget : function(row, column) { if (this._invalidChildrenCache) { this.__buildGrid(); } var row = this.__grid[row] || {}; return row[column] || null; }, /** * Get the number of rows in the grid layout. * * @return {Integer} The number of rows in the layout */ getRowCount : function() { if (this._invalidChildrenCache) { this.__buildGrid(); } return this.__maxRowIndex + 1; }, /** * Get the number of columns in the grid layout. * * @return {Integer} The number of columns in the layout */ getColumnCount : function() { if (this._invalidChildrenCache) { this.__buildGrid(); } return this.__maxColIndex + 1; }, /** * Get a map of the cell's alignment. For vertical alignment the row alignment * takes precedence over the column alignment. For horizontal alignment it is * the over way round. If an alignment is set on the cell widget using * {@link qx.ui.core.LayoutItem#setLayoutProperties}, this alignment takes * always precedence over row or column alignment. * * @param row {Integer} The cell's row index * @param column {Integer} The cell's column index * @return {Map} A map with the keys <code>vAlign</code> and <code>hAlign</code> * containing the vertical and horizontal cell alignment. */ getCellAlign : function(row, column) { var vAlign = "top"; var hAlign = "left"; var rowData = this.__rowData[row]; var colData = this.__colData[column]; var widget = this.__grid[row][column]; if (widget) { var widgetProps = { vAlign : widget.getAlignY(), hAlign : widget.getAlignX() } } else { widgetProps = {}; } // compute vAlign // precedence : widget -> row -> column if (widgetProps.vAlign) { vAlign = widgetProps.vAlign; } else if (rowData && rowData.vAlign) { vAlign = rowData.vAlign; } else if (colData && colData.vAlign) { vAlign = colData.vAlign; } // compute hAlign // precedence : widget -> column -> row if (widgetProps.hAlign) { hAlign = widgetProps.hAlign; } else if (colData && colData.hAlign) { hAlign = colData.hAlign; } else if (rowData && rowData.hAlign) { hAlign = rowData.hAlign; } return { vAlign : vAlign, hAlign : hAlign } }, /** * Set the flex value for a grid column. * By default the column flex value is <code>0</code>. * * @param column {Integer} The column index * @param flex {Integer} The column's flex value * @return {qx.ui.layout.Grid} This object (for chaining support) */ setColumnFlex : function(column, flex) { this._setColumnData(column, "flex", flex); this._applyLayoutChange(); return this; }, /** * Get the flex value of a grid column. * * @param column {Integer} The column index * @return {Integer} The column's flex value */ getColumnFlex : function(column) { var colData = this.__colData[column] || {}; return colData.flex !== undefined ? colData.flex : 0; }, /** * Set the flex value for a grid row. * By default the row flex value is <code>0</code>. * * @param row {Integer} The row index * @param flex {Integer} The row's flex value * @return {qx.ui.layout.Grid} This object (for chaining support) */ setRowFlex : function(row, flex) { this._setRowData(row, "flex", flex); this._applyLayoutChange(); return this; }, /** * Get the flex value of a grid row. * * @param row {Integer} The row index * @return {Integer} The row's flex value */ getRowFlex : function(row) { var rowData = this.__rowData[row] || {}; var rowFlex = rowData.flex !== undefined ? rowData.flex : 0 return rowFlex; }, /** * Set the maximum width of a grid column. * The default value is <code>Infinity</code>. * * @param column {Integer} The column index * @param maxWidth {Integer} The column's maximum width * @return {qx.ui.layout.Grid} This object (for chaining support) */ setColumnMaxWidth : function(column, maxWidth) { this._setColumnData(column, "maxWidth", maxWidth); this._applyLayoutChange(); return this; }, /** * Get the maximum width of a grid column. * * @param column {Integer} The column index * @return {Integer} The column's maximum width */ getColumnMaxWidth : function(column) { var colData = this.__colData[column] || {}; return colData.maxWidth !== undefined ? colData.maxWidth : Infinity; }, /** * Set the preferred width of a grid column. * The default value is <code>Infinity</code>. * * @param column {Integer} The column index * @param width {Integer} The column's width * @return {qx.ui.layout.Grid} This object (for chaining support) */ setColumnWidth : function(column, width) { this._setColumnData(column, "width", width); this._applyLayoutChange(); return this; }, /** * Get the preferred width of a grid column. * * @param column {Integer} The column index * @return {Integer} The column's width */ getColumnWidth : function(column) { var colData = this.__colData[column] || {}; return colData.width !== undefined ? colData.width : null; }, /** * Set the minimum width of a grid column. * The default value is <code>0</code>. * * @param column {Integer} The column index * @param minWidth {Integer} The column's minimum width * @return {qx.ui.layout.Grid} This object (for chaining support) */ setColumnMinWidth : function(column, minWidth) { this._setColumnData(column, "minWidth", minWidth); this._applyLayoutChange(); return this; }, /** * Get the minimum width of a grid column. * * @param column {Integer} The column index * @return {Integer} The column's minimum width */ getColumnMinWidth : function(column) { var colData = this.__colData[column] || {}; return colData.minWidth || 0; }, /** * Set the maximum height of a grid row. * The default value is <code>Infinity</code>. * * @param row {Integer} The row index * @param maxHeight {Integer} The row's maximum width * @return {qx.ui.layout.Grid} This object (for chaining support) */ setRowMaxHeight : function(row, maxHeight) { this._setRowData(row, "maxHeight", maxHeight); this._applyLayoutChange(); return this; }, /** * Get the maximum height of a grid row. * * @param row {Integer} The row index * @return {Integer} The row's maximum width */ getRowMaxHeight : function(row) { var rowData = this.__rowData[row] || {}; return rowData.maxHeight || Infinity; }, /** * Set the preferred height of a grid row. * The default value is <code>Infinity</code>. * * @param row {Integer} The row index * @param height {Integer} The row's width * @return {qx.ui.layout.Grid} This object (for chaining support) */ setRowHeight : function(row, height) { this._setRowData(row, "height", height); this._applyLayoutChange(); return this; }, /** * Get the preferred height of a grid row. * * @param row {Integer} The row index * @return {Integer} The row's width */ getRowHeight : function(row) { var rowData = this.__rowData[row] || {}; return rowData.height !== undefined ? rowData.height : null; }, /** * Set the minimum height of a grid row. * The default value is <code>0</code>. * * @param row {Integer} The row index * @param minHeight {Integer} The row's minimum width * @return {qx.ui.layout.Grid} This object (for chaining support) */ setRowMinHeight : function(row, minHeight) { this._setRowData(row, "minHeight", minHeight); this._applyLayoutChange(); return this; }, /** * Get the minimum height of a grid row. * * @param row {Integer} The row index * @return {Integer} The row's minimum width */ getRowMinHeight : function(row) { var rowData = this.__rowData[row] || {}; return rowData.minHeight || 0; }, /** * Computes the widget's size hint including the widget's margins * * @param widget {qx.ui.core.LayoutItem} The widget to get the size for * @return {Map} a size hint map */ __getOuterSize : function(widget) { var hint = widget.getSizeHint(); var hMargins = widget.getMarginLeft() + widget.getMarginRight(); var vMargins = widget.getMarginTop() + widget.getMarginBottom(); var outerSize = { height: hint.height + vMargins, width: hint.width + hMargins, minHeight: hint.minHeight + vMargins, minWidth: hint.minWidth + hMargins, maxHeight: hint.maxHeight + vMargins, maxWidth: hint.maxWidth + hMargins } return outerSize; }, /** * Check whether all row spans fit with their preferred height into the * preferred row heights. If there is not enough space, the preferred * row sizes are increased. The distribution respects the flex and max * values of the rows. * * The same is true for the min sizes. * * The height array is modified in place. * * @param rowHeights {Map[]} The current row height array as computed by * {@link #_getRowHeights}. */ _fixHeightsRowSpan : function(rowHeights) { var vSpacing = this.getSpacingY(); for (var i=0, l=this.__rowSpans.length; i<l; i++) { var widget = this.__rowSpans[i]; var hint = this.__getOuterSize(widget); var widgetProps = widget.getLayoutProperties(); var widgetRow = widgetProps.row; var prefSpanHeight = vSpacing * (widgetProps.rowSpan - 1); var minSpanHeight = prefSpanHeight; var rowFlexes = {}; for (var j=0; j<widgetProps.rowSpan; j++) { var row = widgetProps.row+j; var rowHeight = rowHeights[row]; var rowFlex = this.getRowFlex(row); if (rowFlex > 0) { // compute flex array for the preferred height rowFlexes[row] = { min : rowHeight.minHeight, value : rowHeight.height, max : rowHeight.maxHeight, flex: rowFlex }; } prefSpanHeight += rowHeight.height; minSpanHeight += rowHeight.minHeight; } // If there is not enough space for the preferred size // increment the preferred row sizes. if (prefSpanHeight < hint.height) { if (!qx.lang.Object.isEmpty(rowFlexes)) { var rowIncrements = qx.ui.layout.Util.computeFlexOffsets( rowFlexes, hint.height, prefSpanHeight ); for (var k=0; k<widgetProps.rowSpan; k++) { var offset = rowIncrements[widgetRow+k] ? rowIncrements[widgetRow+k].offset : 0; rowHeights[widgetRow+k].height += offset; } // row is too small and we have no flex value set } else { var totalSpacing = vSpacing * (widgetProps.rowSpan - 1); var availableHeight = hint.height - totalSpacing; // get the row height which every child would need to share the // available hight equally var avgRowHeight = Math.floor(availableHeight / widgetProps.rowSpan); // get the hight already used and the number of children which do // not have at least that avg row height var usedHeight = 0; var rowsNeedAddition = 0; for (var k = 0; k < widgetProps.rowSpan; k++) { var currentHeight = rowHeights[widgetRow + k].height; usedHeight += currentHeight; if (currentHeight < avgRowHeight) { rowsNeedAddition++; } } // the difference of available and used needs to be shared among // those not having the min size var additionalRowHeight = Math.floor((availableHeight - usedHeight) / rowsNeedAddition); // add the extra height to the too small children for (var k = 0; k < widgetProps.rowSpan; k++) { if (rowHeights[widgetRow + k].height < avgRowHeight) { rowHeights[widgetRow + k].height += additionalRowHeight; } } } } // If there is not enough space for the min size // increment the min row sizes. if (minSpanHeight < hint.minHeight) { var rowIncrements = qx.ui.layout.Util.computeFlexOffsets( rowFlexes, hint.minHeight, minSpanHeight ); for (var j=0; j<widgetProps.rowSpan; j++) { var offset = rowIncrements[widgetRow+j] ? rowIncrements[widgetRow+j].offset : 0; rowHeights[widgetRow+j].minHeight += offset; } } } }, /** * Check whether all col spans fit with their preferred width into the * preferred column widths. If there is not enough space the preferred * column sizes are increased. The distribution respects the flex and max * values of the columns. * * The same is true for the min sizes. * * The width array is modified in place. * * @param colWidths {Map[]} The current column width array as computed by * {@link #_getColWidths}. */ _fixWidthsColSpan : function(colWidths) { var hSpacing = this.getSpacingX(); for (var i=0, l=this.__colSpans.length; i<l; i++) { var widget = this.__colSpans[i]; var hint = this.__getOuterSize(widget); var widgetProps = widget.getLayoutProperties(); var widgetColumn = widgetProps.column; var prefSpanWidth = hSpacing * (widgetProps.colSpan - 1); var minSpanWidth = prefSpanWidth; var colFlexes = {}; var offset; for (var j=0; j<widgetProps.colSpan; j++) { var col = widgetProps.column+j; var colWidth = colWidths[col]; var colFlex = this.getColumnFlex(col); // compute flex array for the preferred width if (colFlex > 0) { colFlexes[col] = { min : colWidth.minWidth, value : colWidth.width, max : colWidth.maxWidth, flex: colFlex }; } prefSpanWidth += colWidth.width; minSpanWidth += colWidth.minWidth; } // If there is not enought space for the preferred size // increment the preferred column sizes. if (prefSpanWidth < hint.width) { var colIncrements = qx.ui.layout.Util.computeFlexOffsets( colFlexes, hint.width, prefSpanWidth ); for (var j=0; j<widgetProps.colSpan; j++) { offset = colIncrements[widgetColumn+j] ? colIncrements[widgetColumn+j].offset : 0; colWidths[widgetColumn+j].width += offset; } } // If there is not enought space for the min size // increment the min column sizes. if (minSpanWidth < hint.minWidth) { var colIncrements = qx.ui.layout.Util.computeFlexOffsets( colFlexes, hint.minWidth, minSpanWidth ); for (var j=0; j<widgetProps.colSpan; j++) { offset = colIncrements[widgetColumn+j] ? colIncrements[widgetColumn+j].offset : 0; colWidths[widgetColumn+j].minWidth += offset; } } } }, /** * Compute the min/pref/max row heights. * * @return {Map[]} An array containg height information for each row. The * entries have the keys <code>minHeight</code>, <code>maxHeight</code> and * <code>height</code>. */ _getRowHeights : function() { if (this.__rowHeights != null) { return this.__rowHeights; } var rowHeights = []; var maxRowIndex = this.__maxRowIndex; var maxColIndex = this.__maxColIndex; for (var row=0; row<=maxRowIndex; row++) { var minHeight = 0; var height = 0; var maxHeight = 0; for (var col=0; col<=maxColIndex; col++) { var widget = this.__grid[row][col]; if (!widget) { continue; } // ignore rows with row spans at this place // these rows will be taken into account later var widgetRowSpan = widget.getLayoutProperties().rowSpan || 0; if (widgetRowSpan > 1) { continue; } var cellSize = this.__getOuterSize(widget); if (this.getRowFlex(row) > 0) { minHeight = Math.max(minHeight, cellSize.minHeight); } else { minHeight = Math.max(minHeight, cellSize.height); } height = Math.max(height, cellSize.height); } var minHeight = Math.max(minHeight, this.getRowMinHeight(row)); var maxHeight = this.getRowMaxHeight(row); if (this.getRowHeight(row) !== null) { var height = this.getRowHeight(row); } else { var height = Math.max(minHeight, Math.min(height, maxHeight)); } rowHeights[row] = { minHeight : minHeight, height : height, maxHeight : maxHeight }; } if (this.__rowSpans.length > 0) { this._fixHeightsRowSpan(rowHeights); } this.__rowHeights = rowHeights; return rowHeights; }, /** * Compute the min/pref/max column widths. * * @return {Map[]} An array containg width information for each column. The * entries have the keys <code>minWidth</code>, <code>maxWidth</code> and * <code>width</code>. */ _getColWidths : function() { if (this.__colWidths != null) { return this.__colWidths; } var colWidths = []; var maxColIndex = this.__maxColIndex; var maxRowIndex = this.__maxRowIndex; for (var col=0; col<=maxColIndex; col++) { var width = 0; var minWidth = 0; var maxWidth = Infinity; for (var row=0; row<=maxRowIndex; row++) { var widget = this.__grid[row][col]; if (!widget) { continue; } // ignore columns with col spans at this place // these columns will be taken into account later var widgetColSpan = widget.getLayoutProperties().colSpan || 0; if (widgetColSpan > 1) { continue; } var cellSize = this.__getOuterSize(widget); if (this.getColumnFlex(col) > 0) { minWidth = Math.max(minWidth, cellSize.minWidth); } else { minWidth = Math.max(minWidth, cellSize.width); } width = Math.max(width, cellSize.width); } minWidth = Math.max(minWidth, this.getColumnMinWidth(col)); maxWidth = this.getColumnMaxWidth(col); if (this.getColumnWidth(col) !== null) { var width = this.getColumnWidth(col); } else { var width = Math.max(minWidth, Math.min(width, maxWidth)); } colWidths[col] = { minWidth: minWidth, width : width, maxWidth : maxWidth }; } if (this.__colSpans.length > 0) { this._fixWidthsColSpan(colWidths); } this.__colWidths = colWidths; return colWidths; }, /** * Computes for each column by how many pixels it must grow or shrink, taking * the column flex values and min/max widths into account. * * @param width {Integer} The grid width * @return {Integer[]} Sparse array of offsets to add to each column width. If * an array entry is empty nothing should be added to the column. */ _getColumnFlexOffsets : function(width) { var hint = this.getSizeHint(); var diff = width - hint.width; if (diff == 0) { return {}; } // collect all flexible children var colWidths = this._getColWidths(); var flexibles = {}; for (var i=0, l=colWidths.length; i<l; i++) { var col = colWidths[i]; var colFlex = this.getColumnFlex(i); if ( (colFlex <= 0) || (col.width == col.maxWidth && diff > 0) || (col.width == col.minWidth && diff < 0) ) { continue; } flexibles[i] ={ min : col.minWidth, value : col.width, max : col.maxWidth, flex : colFlex }; } return qx.ui.layout.Util.computeFlexOffsets(flexibles, width, hint.width); }, /** * Computes for each row by how many pixels it must grow or shrink, taking * the row flex values and min/max heights into account. * * @param height {Integer} The grid height * @return {Integer[]} Sparse array of offsets to add to each row height. If * an array entry is empty nothing should be added to the row. */ _getRowFlexOffsets : function(height) { var hint = this.getSizeHint(); var diff = height - hint.height; if (diff == 0) { return {}; } // collect all flexible children var rowHeights = this._getRowHeights(); var flexibles = {}; for (var i=0, l=rowHeights.length; i<l; i++) { var row = rowHeights[i]; var rowFlex = this.getRowFlex(i); if ( (rowFlex <= 0) || (row.height == row.maxHeight && diff > 0) || (row.height == row.minHeight && diff < 0) ) { continue; } flexibles[i] = { min : row.minHeight, value : row.height, max : row.maxHeight, flex : rowFlex }; } return qx.ui.layout.Util.computeFlexOffsets(flexibles, height, hint.height); }, // overridden renderLayout : function(availWidth, availHeight) { if (this._invalidChildrenCache) { this.__buildGrid(); } var Util = qx.ui.layout.Util; var hSpacing = this.getSpacingX(); var vSpacing = this.getSpacingY(); // calculate column widths var prefWidths = this._getColWidths(); var colStretchOffsets = this._getColumnFlexOffsets(availWidth); var colWidths = []; var maxColIndex = this.__maxColIndex; var maxRowIndex = this.__maxRowIndex; var offset; for (var col=0; col<=maxColIndex; col++) { offset = colStretchOffsets[col] ? colStretchOffsets[col].offset : 0; colWidths[col] = prefWidths[col].width + offset; } // calculate row heights var prefHeights = this._getRowHeights(); var rowStretchOffsets = this._getRowFlexOffsets(availHeight); var rowHeights = []; for (var row=0; row<=maxRowIndex; row++) { offset = rowStretchOffsets[row] ? rowStretchOffsets[row].offset : 0; rowHeights[row] = prefHeights[row].height + offset; } // do the layout var left = 0; for (var col=0; col<=maxColIndex; col++) { var top = 0; for (var row=0; row<=maxRowIndex; row++) { var widget = this.__grid[row][col]; // ignore empty cells if (!widget) { top += rowHeights[row] + vSpacing; continue; } var widgetProps = widget.getLayoutProperties(); // ignore cells, which have cell spanning but are not the origin // of the widget if(widgetProps.row !== row || widgetProps.column !== col) { top += rowHeights[row] + vSpacing; continue; } // compute sizes width including cell spanning var spanWidth = hSpacing * (widgetProps.colSpan - 1); for (var i=0; i<widgetProps.colSpan; i++) { spanWidth += colWidths[col+i]; } var spanHeight = vSpacing * (widgetProps.rowSpan - 1); for (var i=0; i<widgetProps.rowSpan; i++) { spanHeight += rowHeights[row+i]; } var cellHint = widget.getSizeHint(); var marginTop = widget.getMarginTop(); var marginLeft = widget.getMarginLeft(); var marginBottom = widget.getMarginBottom(); var marginRight = widget.getMarginRight(); var cellWidth = Math.max(cellHint.minWidth, Math.min(spanWidth-marginLeft-marginRight, cellHint.maxWidth)); var cellHeight = Math.max(cellHint.minHeight, Math.min(spanHeight-marginTop-marginBottom, cellHint.maxHeight)); var cellAlign = this.getCellAlign(row, col); var cellLeft = left + Util.computeHorizontalAlignOffset(cellAlign.hAlign, cellWidth, spanWidth, marginLeft, marginRight); var cellTop = top + Util.computeVerticalAlignOffset(cellAlign.vAlign, cellHeight, spanHeight, marginTop, marginBottom); widget.renderLayout( cellLeft, cellTop, cellWidth, cellHeight ); top += rowHeights[row] + vSpacing; } left += colWidths[col] + hSpacing; } }, // overridden invalidateLayoutCache : function() { this.base(arguments); this.__colWidths = null; this.__rowHeights = null; }, // overridden _computeSizeHint : function() { if (this._invalidChildrenCache) { this.__buildGrid(); } // calculate col widths var colWidths = this._getColWidths(); var minWidth=0, width=0; for (var i=0, l=colWidths.length; i<l; i++) { var col = colWidths[i]; if (this.getColumnFlex(i) > 0) { minWidth += col.minWidth; } else { minWidth += col.width; } width += col.width; } // calculate row heights var rowHeights = this._getRowHeights(); var minHeight=0, height=0; for (var i=0, l=rowHeights.length; i<l; i++) { var row = rowHeights[i]; if (this.getRowFlex(i) > 0) { minHeight += row.minHeight; } else { minHeight += row.height; } height += row.height; } var spacingX = this.getSpacingX() * (colWidths.length - 1); var spacingY = this.getSpacingY() * (rowHeights.length - 1); var hint = { minWidth : minWidth + spacingX, width : width + spacingX, minHeight : minHeight + spacingY, height : height + spacingY }; return hint; } }, /* ***************************************************************************** DESTRUCT ***************************************************************************** */ destruct : function() { this.__grid = this.__rowData = this.__colData = this.__colSpans = this.__rowSpans = this.__colWidths = this.__rowHeights = null; } });
agpl-3.0
SoftwareHeritage/swh-web-ui
swh/web/tests/resources/contents/code/extensions/test.py
209
# flake8: noqa def somefunc(param1="", param2=0): r"""A docstring""" if param1 > param2: # interesting print("Gre'ater") return (param2 - param1 + 1) or None class SomeClass: pass
agpl-3.0
Tatwi/legend-of-hondo
MMOCoreORB/bin/scripts/object/tangible/medicine/crafted/crafted_stimpack_sm_s1_b.lua
2994
--Copyright (C) 2010 <SWGEmu> --This File is part of Core3. --This program is free software; you can redistribute --it and/or modify it under the terms of the GNU Lesser --General Public License as published by the Free Software --Foundation; either version 2 of the License, --or (at your option) any later version. --This program is distributed in the hope that it will be useful, --but WITHOUT ANY WARRANTY; without even the implied warranty of --MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. --See the GNU Lesser General Public License for --more details. --You should have received a copy of the GNU Lesser General --Public License along with this program; if not, write to --the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA --Linking Engine3 statically or dynamically with other modules --is making a combined work based on Engine3. --Thus, the terms and conditions of the GNU Lesser General Public License --cover the whole combination. --In addition, as a special exception, the copyright holders of Engine3 --give you permission to combine Engine3 program with free software --programs or libraries that are released under the GNU LGPL and with --code included in the standard release of Core3 under the GNU LGPL --license (or modified versions of such code, with unchanged license). --You may copy and distribute such a system following the terms of the --GNU LGPL for Engine3 and the licenses of the other code concerned, --provided that you include the source code of that other code when --and as the GNU LGPL requires distribution of source code. --Note that people who make modified versions of Engine3 are not obligated --to grant this special exception for their modified versions; --it is their choice whether to do so. The GNU Lesser General Public License --gives permission to release a modified version without this exception; --this exception also makes it possible to release a modified version object_tangible_medicine_crafted_crafted_stimpack_sm_s1_b = object_tangible_medicine_crafted_shared_crafted_stimpack_sm_s1_b:new { gameObjectType = 8236, templateType = STIMPACK, useCount = 10, medicineUse = 20, effectiveness = 150, medicineClass = STIM_B, attributes = {0, 3}, numberExperimentalProperties = {1, 1, 2, 2, 1, 1}, experimentalProperties = {"XX", "XX", "OQ", "PE", "OQ", "UT", "XX", "XX"}, experimentalWeights = {1, 1, 2, 1, 2, 1, 1, 1}, experimentalGroupTitles = {"null", "null", "exp_effectiveness", "exp_charges", "null", "null"}, experimentalSubGroupTitles = {"null", "null", "power", "charges", "skillmodmin", "hitpoints"}, experimentalMin = {0, 0, 150, 15, 5, 1000}, experimentalMax = {0, 0, 200, 30, 5, 1000}, experimentalPrecision = {0, 0, 0, 0, 0, 0}, experimentalCombineType = {0, 0, 1, 1, 1, 4}, } ObjectTemplates:addTemplate(object_tangible_medicine_crafted_crafted_stimpack_sm_s1_b, "object/tangible/medicine/crafted/crafted_stimpack_sm_s1_b.iff")
agpl-3.0
Tatwi/legend-of-hondo
MMOCoreORB/bin/scripts/object/draft_schematic/structure/city/shuttleport_tatooine.lua
3839
--Copyright (C) 2010 <SWGEmu> --This File is part of Core3. --This program is free software; you can redistribute --it and/or modify it under the terms of the GNU Lesser --General Public License as published by the Free Software --Foundation; either version 2 of the License, --or (at your option) any later version. --This program is distributed in the hope that it will be useful, --but WITHOUT ANY WARRANTY; without even the implied warranty of --MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. --See the GNU Lesser General Public License for --more details. --You should have received a copy of the GNU Lesser General --Public License along with this program; if not, write to --the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA --Linking Engine3 statically or dynamically with other modules --is making a combined work based on Engine3. --Thus, the terms and conditions of the GNU Lesser General Public License --cover the whole combination. --In addition, as a special exception, the copyright holders of Engine3 --give you permission to combine Engine3 program with free software --programs or libraries that are released under the GNU LGPL and with --code included in the standard release of Core3 under the GNU LGPL --license (or modified versions of such code, with unchanged license). --You may copy and distribute such a system following the terms of the --GNU LGPL for Engine3 and the licenses of the other code concerned, --provided that you include the source code of that other code when --and as the GNU LGPL requires distribution of source code. --Note that people who make modified versions of Engine3 are not obligated --to grant this special exception for their modified versions; --it is their choice whether to do so. The GNU Lesser General Public License --gives permission to release a modified version without this exception; --this exception also makes it possible to release a modified version object_draft_schematic_structure_city_shuttleport_tatooine = object_draft_schematic_structure_city_shared_shuttleport_tatooine:new { templateType = DRAFTSCHEMATIC, customObjectName = "Deed for: Tatooine Shuttleport", craftingToolTab = 1024, -- (See DraftSchematicObjectTemplate.h) complexity = 22, size = 1, xpType = "crafting_structure_general", xp = 8000, assemblySkill = "structure_assembly", experimentingSkill = "structure_experimentation", customizationSkill = "structure_customization", customizationOptions = {}, customizationStringNames = {}, customizationDefaults = {}, ingredientTemplateNames = {"craft_structure_ingredients_n", "craft_structure_ingredients_n", "craft_structure_ingredients_n", "craft_structure_ingredients_n", "craft_structure_ingredients_n", "craft_structure_ingredients_n", "craft_structure_ingredients_n"}, ingredientTitleNames = {"load_bearing_structure_and_shell", "insulation_and_covering", "foundation", "wall_sections", "power_supply_unit", "storage_space", "ticket_droid_chassis"}, ingredientSlotType = {0, 0, 0, 2, 1, 1, 1}, resourceTypes = {"metal", "ore", "ore", "object/tangible/component/structure/shared_wall_module.iff", "object/tangible/component/structure/shared_power_core_unit.iff", "object/tangible/component/structure/shared_structure_storage_section.iff", "object/tangible/component/droid/shared_advanced_droid_frame.iff"}, resourceQuantities = {1550, 2350, 350, 12, 3, 3, 1}, contribution = {100, 100, 100, 100, 100, 100, 100}, targetTemplate = "object/tangible/deed/city_deed/shuttleport_tatooine_deed.iff", additionalTemplates = { } } ObjectTemplates:addTemplate(object_draft_schematic_structure_city_shuttleport_tatooine, "object/draft_schematic/structure/city/shuttleport_tatooine.iff")
agpl-3.0
invliD/lana-dashboard
lana_dashboard/usermanagement/oidc.py
1268
from django.conf import settings from django.contrib.auth import get_user_model from mozilla_django_oidc.auth import OIDCAuthenticationBackend class AuthenticationBackend(OIDCAuthenticationBackend): def __init__(self, *args, **kwargs): # Only set up OIDC backend if it's actually configured. if getattr(settings, 'OIDC_RP_CLIENT_ID', None) is not None: super(AuthenticationBackend, self).__init__(self, *args, **kwargs) else: self.UserModel = get_user_model() def filter_users_by_claims(self, claims): username = self.get_username(claims) if not username: return self.UserModel.objects.none() try: user = get_user_model().objects.get(username=username) return [user] except get_user_model().DoesNotExist: return self.UserModel.objects.none() def get_username(self, claims): return claims.get('sub') def create_user(self, claims): user = super(AuthenticationBackend, self).create_user(claims) user.first_name = claims.get('given_name', '') user.last_name = claims.get('family_name', '') user.save() return user def update_user(self, user, claims): user.email = claims.get('email') user.first_name = claims.get('given_name', '') user.last_name = claims.get('family_name', '') user.save() return user
agpl-3.0
empirical-org/Empirical-Core
services/QuillLMS/app/services/clever_integration/sign_up/sub_main.rb
875
# frozen_string_literal: true module CleverIntegration::SignUp::SubMain # we have to send district_success, district_failure, user_success, user_failure back to controller def self.run(auth_hash) case auth_hash[:info][:user_type] when 'district_admin' result = district(auth_hash) when 'student' result = student(auth_hash) when 'school_admin' result = school_admin(auth_hash) else result = teacher(auth_hash) end result end def self.district(auth_hash) CleverIntegration::SignUp::CleverDistrict.run(auth_hash) end def self.teacher(auth_hash) CleverIntegration::TeacherIntegration.run(auth_hash) end def self.student(auth_hash) CleverIntegration::SignUp::Student.run(auth_hash) end def self.school_admin(auth_hash) CleverIntegration::SignUp::SchoolAdmin.run(auth_hash) end end
agpl-3.0
juju/juju
upgrades/steps_29_test.go
7659
// Copyright 2020 Canonical Ltd. // Licensed under the AGPLv3, see LICENCE file for details. package upgrades_test import ( "fmt" "github.com/golang/mock/gomock" "github.com/juju/errors" "github.com/juju/names/v4" jc "github.com/juju/testing/checkers" "github.com/juju/version/v2" gc "gopkg.in/check.v1" "github.com/juju/juju/agent" "github.com/juju/juju/service" "github.com/juju/juju/service/common" servicemocks "github.com/juju/juju/service/mocks" "github.com/juju/juju/testing" "github.com/juju/juju/upgrades" "github.com/juju/juju/upgrades/mocks" configsettermocks "github.com/juju/juju/worker/upgradedatabase/mocks" ) var v290 = version.MustParse("2.9.0") type steps29Suite struct { testing.BaseSuite } var _ = gc.Suite(&steps29Suite{}) func (s *steps29Suite) TestStoreDeployedUnitsInMachineAgentConf(c *gc.C) { step := findStep(c, v290, "store deployed units in machine agent.conf") c.Assert(step.Targets(), jc.DeepEquals, []upgrades.Target{upgrades.HostMachine}) } func (s *steps29Suite) TestAddCharmhubToModelConfig(c *gc.C) { step := findStateStep(c, v290, "add charmhub-url to model config") c.Assert(step.Targets(), jc.DeepEquals, []upgrades.Target{upgrades.DatabaseMaster}) } func (s *steps29Suite) TestRollUpAndConvertOpenedPortDocuments(c *gc.C) { step := findStateStep(c, v290, "roll up and convert opened port documents into the new endpoint-aware format") c.Assert(step.Targets(), jc.DeepEquals, []upgrades.Target{upgrades.DatabaseMaster}) } func (s *steps29Suite) TestAddCharmOriginToApplications(c *gc.C) { step := findStateStep(c, v290, "add charm-origin to applications") c.Assert(step.Targets(), jc.DeepEquals, []upgrades.Target{upgrades.DatabaseMaster}) } func (s *steps29Suite) TestExposeWildcardEndpointForExposedApplications(c *gc.C) { step := findStateStep(c, v290, `add explicit "expose all endpoints to 0.0.0.0/0" entry for already exposed applications`) c.Assert(step.Targets(), jc.DeepEquals, []upgrades.Target{upgrades.DatabaseMaster}) } func (s *steps29Suite) TestRemoveLinkLayerDevicesRefsCollection(c *gc.C) { step := findStateStep(c, v290, "remove unused linklayerdevicesrefs collection") c.Assert(step.Targets(), jc.DeepEquals, []upgrades.Target{upgrades.DatabaseMaster}) } func (s *steps29Suite) TestUpdateKubernetesCloudCredentials(c *gc.C) { step := findStateStep(c, v290, "update kubernetes cloud credentials") c.Assert(step.Targets(), jc.DeepEquals, []upgrades.Target{upgrades.DatabaseMaster}) } type mergeAgents29Suite struct { testing.BaseSuite dataDir string machine agent.ConfigSetterWriter unitOne agent.ConfigSetterWriter unitTwo agent.ConfigSetterWriter machineTag names.MachineTag unitOneTag names.UnitTag unitTwoTag names.UnitTag mockCtx *mocks.MockContext mockClient *mocks.MockUpgradeStepsClient mockAgentConfig *configsettermocks.MockConfigSetter } var _ = gc.Suite(&mergeAgents29Suite{}) func (s *mergeAgents29Suite) SetUpTest(c *gc.C) { s.BaseSuite.SetUpTest(c) s.dataDir = c.MkDir() s.machineTag = names.NewMachineTag("42") s.unitOneTag = names.NewUnitTag("principal/1") s.unitTwoTag = names.NewUnitTag("subordinate/2") s.machine = s.writeAgentConf(c, s.machineTag) s.unitOne = s.writeAgentConf(c, s.unitOneTag) s.unitTwo = s.writeAgentConf(c, s.unitTwoTag) s.PatchValue(upgrades.ServiceDiscovery, func(name string, _ common.Conf) (service.Service, error) { return nil, errors.NotFoundf(name) }) } func (s *mergeAgents29Suite) writeAgentConf(c *gc.C, tag names.Tag) agent.ConfigSetterWriter { conf, err := agent.NewAgentConfig( agent.AgentConfigParams{ Paths: agent.Paths{ DataDir: s.dataDir, }, Tag: tag, Password: "secret", Controller: testing.ControllerTag, Model: testing.ModelTag, APIAddresses: []string{"localhost:4321"}, CACert: testing.CACert, UpgradedToVersion: version.MustParse("2.42.0"), }) c.Assert(err, jc.ErrorIsNil) c.Assert(conf.Write(), jc.ErrorIsNil) return conf } func (s *mergeAgents29Suite) TestUnitAgentSuccess(c *gc.C) { // The upgrade step succeeds but does nothing for unit agents. defer s.setup(c).Finish() s.expectAgentConfigUnitTag() err := upgrades.StoreDeployedUnitsInMachineAgentConf(s.mockCtx) c.Assert(err, jc.ErrorIsNil) } func (s *mergeAgents29Suite) TestGoodPath(c *gc.C) { mockController := s.setup(c) defer mockController.Finish() s.expectAgentConfigMachineTag() svc1 := s.expectService(mockController, s.unitOneTag) svc1.EXPECT().Installed().Return(true, nil) svc1.EXPECT().Stop().Return(nil) svc1.EXPECT().Remove().Return(nil) svc2 := s.expectService(mockController, s.unitTwoTag) svc2.EXPECT().Installed().Return(true, nil) svc2.EXPECT().Stop().Return(nil) svc2.EXPECT().Remove().Return(nil) s.mockAgentConfig.EXPECT().SetValue("deployed-units", "principal/1,subordinate/2") err := upgrades.StoreDeployedUnitsInMachineAgentConf(s.mockCtx) c.Assert(err, jc.ErrorIsNil) } func (s *mergeAgents29Suite) TestServicesNotInstalled(c *gc.C) { // This also tests idempotency as the step may have been run before // which removed the services. mockController := s.setup(c) defer mockController.Finish() s.expectAgentConfigMachineTag() svc1 := s.expectService(mockController, s.unitOneTag) svc1.EXPECT().Installed().Return(false, nil) svc2 := s.expectService(mockController, s.unitTwoTag) svc2.EXPECT().Installed().Return(false, nil) s.mockAgentConfig.EXPECT().SetValue("deployed-units", "principal/1,subordinate/2") err := upgrades.StoreDeployedUnitsInMachineAgentConf(s.mockCtx) c.Assert(err, jc.ErrorIsNil) } func (s *mergeAgents29Suite) TestServiceStopFailedStillCallsRemove(c *gc.C) { // This also tests idempotency as the step may have been run before // which removed the services. mockController := s.setup(c) defer mockController.Finish() s.expectAgentConfigMachineTag() svc := s.expectService(mockController, s.unitOneTag) svc.EXPECT().Installed().Return(true, nil) svc.EXPECT().Stop().Return(errors.New("boom")) svc.EXPECT().Remove().Return(nil) // Also happens to test the situation where service discovery for the // second unit returns an error. s.mockAgentConfig.EXPECT().SetValue("deployed-units", "principal/1,subordinate/2") err := upgrades.StoreDeployedUnitsInMachineAgentConf(s.mockCtx) c.Assert(err, jc.ErrorIsNil) } func (s *mergeAgents29Suite) setup(c *gc.C) *gomock.Controller { ctlr := gomock.NewController(c) s.mockCtx = mocks.NewMockContext(ctlr) s.mockAgentConfig = configsettermocks.NewMockConfigSetter(ctlr) s.mockClient = mocks.NewMockUpgradeStepsClient(ctlr) s.expectAgentConfig() s.expectDataDir() return ctlr } func (s *mergeAgents29Suite) expectAgentConfig() { s.mockCtx.EXPECT().AgentConfig().Return(s.mockAgentConfig).AnyTimes() } func (s *mergeAgents29Suite) expectDataDir() { s.mockAgentConfig.EXPECT().DataDir().Return(s.dataDir).AnyTimes() } func (s *mergeAgents29Suite) expectAgentConfigMachineTag() { s.mockAgentConfig.EXPECT().Tag().Return(names.NewMachineTag("42")).AnyTimes() } func (s *mergeAgents29Suite) expectAgentConfigUnitTag() { s.mockAgentConfig.EXPECT().Tag().Return(names.NewUnitTag("principal/1")) } func (s *mergeAgents29Suite) expectService(ctrl *gomock.Controller, unit names.UnitTag) *servicemocks.MockService { orig := *upgrades.ServiceDiscovery svc := servicemocks.NewMockService(ctrl) // Chain up the service discovery. s.PatchValue(upgrades.ServiceDiscovery, func(name string, conf common.Conf) (service.Service, error) { if name == fmt.Sprintf("jujud-%s", unit) { return svc, nil } return orig(name, conf) }) return svc }
agpl-3.0
nathansamson/CoOrg
coorg/deployment/state.class.php
3323
<?php /* * Copyright 2010 Nathan Samson <nathansamson at gmail dot com> * * This file is part of CoOrg. * * CoOrg 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. * CoOrg 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 CoOrg. If not, see <http://www.gnu.org/licenses/>. */ require_once 'coorg/deployment/fileupload.class.php'; class Cookies implements ICookies { public static function has($key) { } public static function get($key) { } public static function set($key, $value, $lifeTime = 0) { } public static function delete($key) { } } class Session implements ISession { private static $_keys = array(); private static $_started = false; public static function has($key) { self::start(); return array_key_exists($key, $_SESSION); } public static function get($key) { self::start(); return $_SESSION[$key]; } public static function set($key, $value) { self::start(); $_SESSION[$key] = $value; } public static function delete($key) { self::start(); unset($_SESSION[$key]); } public static function destroy() { self::start(); session_destroy(); } public static function IP() { return $_SERVER['REMOTE_ADDR']; } public static function stop() { if (self::$_started) { session_write_close(); } } private static function start() { if (!self::$_started) { session_start(); if (array_key_exists('__IP', $_SESSION)) { if ($_SESSION['__IP'] != self::IP()) { session_destroy(); } } else { $_SESSION['__IP'] = self::IP(); } self::$_started = true; } } public static function getReferrer() { if (array_key_exists('HTTP_REFERER', $_SERVER)) { return $_SERVER['HTTP_REFERER']; } else { return ''; } } public static function getSite() { return 'http://'.$_SERVER['HTTP_HOST']; } public static function getPreferredLanguages() { $langs = array(); if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { // break up string into pieces (languages and q factors) preg_match_all('/([a-z]{1,8}(-[a-z]{1,8})?)\s*(;\s*q\s*=\s*(1|0\.[0-9]+))?/i', $_SERVER['HTTP_ACCEPT_LANGUAGE'], $lang_parse); if (count($lang_parse[1])) { // create a list like "en" => 0.8 $langs = array_combine($lang_parse[1], $lang_parse[4]); // set default to 1 for any without q factor foreach ($langs as $lang => $val) { if ($val === '') $langs[$lang] = 1; } // sort list based on value arsort($langs, SORT_NUMERIC); } } return array_keys($langs); } public static function getFileUpload($name) { self::start(); return new FileUpload($name, self::getUploadManager()); } public static function getUploadManager() { return new DataManager(CoOrg::getDataPath('.session-uploads/'.session_id())); } } ?>
agpl-3.0
yanlsino/enterpriseconnect
connect-web/src/main/java/org/osforce/connect/web/oauth/OAuthController.java
4611
package org.osforce.connect.web.oauth; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpSession; import org.osforce.connect.entity.oauth.Authorization; import org.osforce.connect.entity.system.Site; import org.osforce.connect.entity.system.User; import org.osforce.connect.service.oauth.AuthorizationService; import org.osforce.connect.web.AttributeKeys; import org.osforce.platform.social.api.service.ApiService; import org.osforce.platform.web.framework.annotation.Param; import org.scribe.model.Token; import org.scribe.model.Verifier; import org.scribe.oauth.OAuthService; import org.springframework.beans.BeansException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.context.request.WebRequest; /** * * @author gavin * @since 1.0.3 * @create May 9, 2011 - 9:03:14 PM * <a href="http://www.opensourceforce.org">开源力量</a> */ @Controller @RequestMapping("oauth") public class OAuthController implements ApplicationContextAware { private Map<Token, OAuthService> oAuthServices = new HashMap<Token, OAuthService>(); private Map<String, Token> requestTokens = new HashMap<String, Token>(); private ApplicationContext appContext; private AuthorizationService authorizationService; public OAuthController() { } @Autowired public void setAuthorizationService( AuthorizationService authorizationService) { this.authorizationService = authorizationService; } public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.appContext = applicationContext; } @RequestMapping(value="authorized", method=RequestMethod.GET) public @ResponseBody Map<String, Object> isAuthorized( @Param String target, HttpSession session) { User user = (User) session.getAttribute(AttributeKeys.USER_KEY); Authorization authorization = authorizationService.getAuthorization(target, user.getId()); // Map<String, Object> model = new HashMap<String, Object>(); model.put("authorized", authorization!=null); return model; } @RequestMapping(value="authorizationUrl", method=RequestMethod.GET) public @ResponseBody Map<String, Object> getAuthUrl( @Param String target, WebRequest request) { Site site = (Site) request.getAttribute(AttributeKeys.SITE_KEY, WebRequest.SCOPE_REQUEST); String callback = site.getHomeURL()+ "/process/oauth/callback/" + target; String beanId = target + ApiService.class.getSimpleName(); ApiService apiService = appContext.getBean(beanId, ApiService.class); OAuthService oAuthService = apiService.getOAuthService(callback); Token requestToken = oAuthService.getRequestToken(); oAuthServices.put(requestToken, oAuthService); requestTokens.put(requestToken.getToken(), requestToken); String authUrl = oAuthService.getAuthorizationUrl(requestToken); Map<String, Object> model = new HashMap<String, Object>(); model.put("authUrl", authUrl); return model; } @RequestMapping(value="callback/{target}") public ResponseEntity<String> callback(@PathVariable String target, @Param String oauth_token, @Param String oauth_verifier, HttpSession session) { User user = (User) session.getAttribute(AttributeKeys.USER_KEY); Token requestToken = requestTokens.get(oauth_token); Verifier verifier = new Verifier(oauth_verifier); OAuthService oAuthService = oAuthServices.get(requestToken); Token accessToken = oAuthService.getAccessToken(requestToken, verifier); Authorization authorization = new Authorization( target, accessToken.getToken(), accessToken.getSecret(), user); authorizationService.createAuthorization(authorization); requestTokens.remove(oauth_token); oAuthServices.remove(requestToken); HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.setContentType(MediaType.TEXT_HTML) ; return new ResponseEntity<String>( "<script type=\"text/javascript\">window.close();</script>", responseHeaders, HttpStatus.OK); } }
agpl-3.0
acontes/programming
src/Tests/functionalTests/activeobject/futuremonitoring/TestFutureMonitoring.java
3641
/* * ################################################################ * * ProActive Parallel Suite(TM): The Java(TM) library for * Parallel, Distributed, Multi-Core Computing for * Enterprise Grids & Clouds * * Copyright (C) 1997-2012 INRIA/University of * Nice-Sophia Antipolis/ActiveEon * Contact: proactive@ow2.org or contact@activeeon.com * * This library 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; version 3 of * the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Affero General Public License for more details. * * You should have received a copy of the GNU Affero 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 * * If needed, contact us to obtain a release under GPL Version 2 or 3 * or a different license than the AGPL. * * Initial developer(s): The ProActive Team * http://proactive.inria.fr/team_members.htm * Contributor(s): * * ################################################################ * $$PROACTIVE_INITIAL_DEV$$ */ package functionalTests.activeobject.futuremonitoring; import static junit.framework.Assert.assertTrue; import org.junit.Test; import org.objectweb.proactive.api.PAActiveObject; import org.objectweb.proactive.core.ProActiveException; import org.objectweb.proactive.core.body.exceptions.FutureMonitoringPingFailureException; import org.objectweb.proactive.core.node.Node; import functionalTests.GCMFunctionalTest; /** * Test monitoring the futures */ public class TestFutureMonitoring extends GCMFunctionalTest { public TestFutureMonitoring() throws ProActiveException { super(4, 1); super.startDeployment(); } @Test public void action() throws Exception { Node node1 = super.getANode(); Node node2 = super.getANode(); Node node3 = super.getANode(); // With AC boolean exception = false; A a1 = PAActiveObject.newActive(A.class, null, node1); A future = a1.sleepForever(); A a2 = PAActiveObject.newActive(A.class, null, node2); A ac = a2.wrapFuture(future); a2.crash(); try { //System.out.println(ac); ac.toString(); } catch (FutureMonitoringPingFailureException fmpfe) { exception = true; } assertTrue(exception); // With AC and Terminate AO boolean exceptionT = false; A a1T = PAActiveObject.newActive(A.class, null, node1); A futureT = a1T.sleepForever(); A a2T = PAActiveObject.newActive(A.class, null, node3); A acT = a2T.wrapFuture(futureT); a2T.crashWithTerminate(); try { //System.out.println(ac); acT.toString(); } catch (FutureMonitoringPingFailureException fmpfe) { exceptionT = true; } assertTrue(exceptionT); // Without AC exception = false; A a1bis = PAActiveObject.newActive(A.class, null, node1); a1bis.crash(); try { //System.out.println(future); future.toString(); } catch (FutureMonitoringPingFailureException fmpfe) { exception = true; } assertTrue(exception); } }
agpl-3.0
abramhindle/UnnaturalCodeFork
python/testdata/launchpad/lib/lp/answers/tests/test_question_webservice.py
8593
# Copyright 2011 Canonical Ltd. This software is licensed under the # GNU Affero General Public License version 3 (see the file LICENSE). """Webservice unit tests related to Launchpad Questions.""" __metaclass__ = type from BeautifulSoup import BeautifulSoup from lazr.restfulclient.errors import HTTPError from simplejson import dumps import transaction from zope.security.proxy import removeSecurityProxy from lp.answers.errors import ( AddAnswerContactError, FAQTargetError, InvalidQuestionStateError, NotAnswerContactError, NotMessageOwnerError, NotQuestionOwnerError, QuestionTargetError, ) from lp.testing import ( celebrity_logged_in, launchpadlib_for, logout, person_logged_in, TestCase, TestCaseWithFactory, ws_object, ) from lp.testing.layers import ( AppServerLayer, DatabaseFunctionalLayer, FunctionalLayer, ) from lp.testing.pages import LaunchpadWebServiceCaller from lp.testing.views import create_webservice_error_view class ErrorsTestCase(TestCase): """Test answers errors are exported as HTTPErrors.""" layer = FunctionalLayer def test_AddAnswerContactError(self): error_view = create_webservice_error_view(AddAnswerContactError()) self.assertEqual(400, error_view.status) def test_FAQTargetError(self): error_view = create_webservice_error_view(FAQTargetError()) self.assertEqual(400, error_view.status) def test_InvalidQuestionStateError(self): error_view = create_webservice_error_view(InvalidQuestionStateError()) self.assertEqual(400, error_view.status) def test_NotAnswerContactError(self): error_view = create_webservice_error_view(NotAnswerContactError()) self.assertEqual(400, error_view.status) def test_NotMessageOwnerError(self): error_view = create_webservice_error_view(NotMessageOwnerError()) self.assertEqual(400, error_view.status) def test_NotQuestionOwnerError(self): error_view = create_webservice_error_view(NotQuestionOwnerError()) self.assertEqual(400, error_view.status) def test_QuestionTargetError(self): error_view = create_webservice_error_view(QuestionTargetError()) self.assertEqual(400, error_view.status) class TestQuestionRepresentation(TestCaseWithFactory): """Test ways of interacting with Question webservice representations.""" layer = DatabaseFunctionalLayer def setUp(self): super(TestQuestionRepresentation, self).setUp() with celebrity_logged_in('admin'): self.question = self.factory.makeQuestion( title="This is a question") self.target_name = self.question.target.name self.webservice = LaunchpadWebServiceCaller( 'launchpad-library', 'salgado-change-anything') self.webservice.default_api_version = 'devel' def findQuestionTitle(self, response): """Find the question title field in an XHTML document fragment.""" soup = BeautifulSoup(response.body) dt = soup.find('dt', text="title").parent dd = dt.findNextSibling('dd') return str(dd.contents.pop()) def test_top_level_question_get(self): # The top level question set can be used via the api to get # a question by id via redirect without url hacking. response = self.webservice.get( '/questions/%s' % self.question.id, 'application/xhtml+xml') self.assertEqual(response.status, 200) def test_GET_xhtml_representation(self): # A question's xhtml representation is available on the api. response = self.webservice.get( '/%s/+question/%d' % (self.target_name, self.question.id), 'application/xhtml+xml') self.assertEqual(response.status, 200) self.assertEqual( self.findQuestionTitle(response), "<p>This is a question</p>") def test_PATCH_xhtml_representation(self): # You can update the question through the api with PATCH. new_title = "No, this is a question" question_json = self.webservice.get( '/%s/+question/%d' % (self.target_name, self.question.id)).jsonBody() response = self.webservice.patch( question_json['self_link'], 'application/json', dumps(dict(title=new_title)), headers=dict(accept='application/xhtml+xml')) self.assertEqual(response.status, 209) self.assertEqual( self.findQuestionTitle(response), "<p>No, this is a question</p>") class TestSetCommentVisibility(TestCaseWithFactory): """Tests who can successfully set comment visibility.""" layer = DatabaseFunctionalLayer def setUp(self): super(TestSetCommentVisibility, self).setUp() self.commenter = self.factory.makePerson() with person_logged_in(self.commenter): self.question = self.factory.makeQuestion() self.message = self.question.addComment( self.commenter, 'Some comment') transaction.commit() def _get_question_for_user(self, user=None): """Convenience function to get the api question reference.""" # End any open lplib instance. logout() lp = launchpadlib_for("test", user) return ws_object(lp, removeSecurityProxy(self.question)) def _set_visibility(self, question): """Method to set visibility; needed for assertRaises.""" question.setCommentVisibility( comment_number=0, visible=False) def test_random_user_cannot_set_visible(self): # Logged in users without privs can't set question comment # visibility. random_user = self.factory.makePerson() question = self._get_question_for_user(random_user) self.assertRaises( HTTPError, self._set_visibility, question) def test_anon_cannot_set_visible(self): # Anonymous users can't set question comment # visibility. question = self._get_question_for_user() self.assertRaises( HTTPError, self._set_visibility, question) def test_comment_owner_can_set_visible(self): # Members of registry experts can set question comment # visibility. question = self._get_question_for_user(self.commenter) self._set_visibility(question) self.assertFalse(self.message.visible) def test_registry_admin_can_set_visible(self): # Members of registry experts can set question comment # visibility. with celebrity_logged_in('registry_experts') as registry: person = registry question = self._get_question_for_user(person) self._set_visibility(question) self.assertFalse(self.message.visible) def test_admin_can_set_visible(self): # Admins can set question comment # visibility. with celebrity_logged_in('admin') as admin: person = admin question = self._get_question_for_user(person) self._set_visibility(question) self.assertFalse(self.message.visible) class TestQuestionWebServiceSubscription(TestCaseWithFactory): layer = AppServerLayer def test_subscribe(self): # Test subscribe() API. person = self.factory.makePerson() with person_logged_in(person): db_question = self.factory.makeQuestion() db_person = self.factory.makePerson() launchpad = self.factory.makeLaunchpadService() question = ws_object(launchpad, db_question) person = ws_object(launchpad, db_person) question.subscribe(person=person) transaction.commit() # Check the results. self.assertTrue(db_question.isSubscribed(db_person)) def test_unsubscribe(self): # Test unsubscribe() API. person = self.factory.makePerson() with person_logged_in(person): db_question = self.factory.makeQuestion() db_person = self.factory.makePerson() db_question.subscribe(person=db_person) launchpad = self.factory.makeLaunchpadService(person=db_person) question = ws_object(launchpad, db_question) person = ws_object(launchpad, db_person) question.unsubscribe(person=person) transaction.commit() # Check the results. self.assertFalse(db_question.isSubscribed(db_person))
agpl-3.0
overview/overview-server
web/app/controllers/auth/Authority.scala
290
package controllers.auth import scala.concurrent.Future import com.overviewdocs.models.ApiToken import models.User /** Determines whether the given user/apiToken has access. */ trait Authority { def apply(user: User): Future[Boolean] def apply(apiToken: ApiToken): Future[Boolean] }
agpl-3.0
dayatz/taiga-back
taiga/events/__init__.py
993
# -*- coding: utf-8 -*- # Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz> # Copyright (C) 2014-2017 Jesús Espino <jespinog@gmail.com> # Copyright (C) 2014-2017 David Barragán <bameda@dbarragan.com> # Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net> # 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/>. default_app_config = "taiga.events.apps.EventsAppConfig"
agpl-3.0
pavlovicnemanja/superdesk-client-core
scripts/apps/contacts/components/Form/ContactFormContainer.tsx
8904
import React from 'react'; import PropTypes from 'prop-types'; import {get, set, isEqual, cloneDeep, some, isEmpty, extend, each, omit, isNil} from 'lodash'; import {gettext} from 'core/utils'; import {StretchBar} from 'core/ui/components/SubNav'; import { validateRequiredFormFields, getContactType, validateAssignableType, getContactTypeObject, } from '../../helpers'; import {FB_URL, IG_URL} from '../../constants'; import {ProfileDetail} from './ProfileDetail'; import {IContact, IContactsService, IContactType} from '../../Contacts'; interface IProps { svc: { contacts: IContactsService; notify: any; privileges: any; metadata: any; }; contact: IContact; onSave(result: IContact): void; onCancel(): void; onDirty(): void; onValidation(valid: boolean): void; triggerSave: boolean; hideActionBar: boolean; formClass?: string; } interface IState { currentContact: IContact; errors: {[key: string]: string}; originalContact: IContact; dirty: boolean; isFormValid: boolean; } export class ContactFormContainer extends React.PureComponent<IProps, IState> { static propTypes: any; static defaultProps: any; constructor(props) { super(props); // Initialize this.state = { currentContact: props.contact || {}, errors: {}, originalContact: props.contact || {}, dirty: false, isFormValid: false, }; this.save = this.save.bind(this); this.onChange = this.onChange.bind(this); this.validateForm = this.validateForm.bind(this); } validateForm() { const {metadata} = this.props.svc; const valid = validateRequiredFormFields(this.state.currentContact, metadata.values.contact_type) && !Object.values(this.state.errors).some((value) => value && value.length > 0); this.setState({isFormValid: valid}); if (this.state.dirty && this.props.onDirty) { this.props.onDirty(); } if (this.props.onValidation) { this.props.onValidation(valid); } } validateField(fieldName, value, e, diff) { const fieldValidationErrors = this.state.errors; if (e && e.target.type === 'email') { if (e.target.validity.typeMismatch) { fieldValidationErrors[e.target.name] = gettext('Please provide a valid email address'); } else if (fieldValidationErrors[e.target.name]) { delete fieldValidationErrors[e.target.name]; } } else if (fieldName === 'twitter') { const twitterPattern = this.props.svc.contacts.twitterPattern; if (!isEmpty(value) && !value.match(twitterPattern)) { fieldValidationErrors[fieldName] = gettext('Please provide a valid twitter account'); } else if (fieldValidationErrors[fieldName]) { delete fieldValidationErrors[fieldName]; } } const metadata = this.props.svc.metadata; if (!validateAssignableType(diff, metadata.values.contact_type)) { const contactType = getContactTypeObject( metadata.values.contact_type, diff.contact_type, ); fieldValidationErrors.contact_email = gettext( 'Contact type "{{ contact_type }}" MUST have an email', {contact_type: contactType.name}, ); } else if (fieldValidationErrors['contact_email']) { delete fieldValidationErrors.contact_email; } return fieldValidationErrors; } componentWillReceiveProps(nextProps) { if (!this.props.triggerSave && nextProps.triggerSave) { this.save(); } } save() { const {svc} = this.props; const {notify, contacts} = svc; const origContact = this.state.originalContact; notify.info(gettext('Saving...')); let diff: any = {}; each(this.state.currentContact, (value, key) => { if (!isEqual(origContact[key], value)) { extend(diff, {[key]: value}); } }); if (diff.facebook) { diff.facebook = FB_URL + this.state.currentContact.facebook; } if (diff.instagram) { diff.instagram = IG_URL + this.state.currentContact.instagram; } // clean diff diff = omit(diff, 'type'); return contacts.save(origContact, diff) .then((result: IContact) => { notify.pop(); notify.success(gettext('contact saved.')); this.setState({ originalContact: result, currentContact: result, dirty: false, }, () => { if (this.props.onSave) { this.props.onSave(result); } }); }, (response) => { notify.pop(); let errorMessage = gettext('There was an error when saving the contact.'); if (response.data && response.data._issues) { if (!isNil(response.data._issues['validator exception'])) { errorMessage = gettext('Error: ' + response.data._issues['validator exception']); } } notify.error(errorMessage); }); } onChange(field, value, e) { const diff = cloneDeep(this.state.currentContact); const origContact = this.state.originalContact; set(diff, field, value); this.setState({ currentContact: diff, dirty: !isEqual(origContact, diff), errors: this.validateField(field, value, e, diff), }, this.validateForm); } render() { const {svc, contact, onCancel, hideActionBar, formClass} = this.props; const { isFormValid = false, dirty = false, errors = {}, } = this.state; const {privileges} = svc; const readOnly = !get(privileges, 'privileges.contacts', false); const currentContact: IContact = this.state.currentContact || null; const contactType: string = getContactType(currentContact) || 'person'; const iconName = contactType === 'organisation' ? 'icon-business' : 'icon-user'; return ( <div id={contact._id} key={contact._id} className="contact-form"> <form name="contactForm" className={formClass} onSubmit={(e) => e.preventDefault()} > {!hideActionBar && ( <div className="subnav subnav--darker"> <StretchBar> <div className="contact__type-icon" data-sd-tooltip={gettext('Organisation Contact')} data-flow="right" > <i className={iconName} /> </div> </StretchBar> <StretchBar right={true}> <button className="btn" onClick={onCancel}> {gettext('Cancel')} </button> {!readOnly && ( <button className="btn btn--primary" onClick={this.save} disabled={!isFormValid || !dirty} >{gettext('Save')}</button> )} </StretchBar> </div> )} <div className="profile-info"> <ProfileDetail contact={currentContact} svc={svc} onChange={this.onChange} readOnly={readOnly} errors={errors} contactType={contactType} /> </div> </form> </div> ); } } ContactFormContainer.propTypes = { svc: PropTypes.object.isRequired, contact: PropTypes.object.isRequired, onSave: PropTypes.func, onCancel: PropTypes.func, onDirty: PropTypes.func, onValidation: PropTypes.func, triggerSave: PropTypes.bool, hideActionBar: PropTypes.bool, }; ContactFormContainer.defaultProps = {hideActionBar: false};
agpl-3.0
dzc34/Asqatasun
rules/rules-accessiweb2.2/src/test/java/org/asqatasun/rules/accessiweb22/Aw22Rule04011Test.java
3499
/* * Asqatasun - Automated webpage assessment * Copyright (C) 2008-2019 Asqatasun.org * * 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/>. * * Contact us by mail: asqatasun AT asqatasun DOT org */ package org.asqatasun.rules.accessiweb22; import org.asqatasun.entity.audit.TestSolution; import org.asqatasun.rules.accessiweb22.test.Aw22RuleImplementationTestCase; /** * Unit test class for the implementation of the rule 4.1.1 of the referential Accessiweb 2.2. * * @author jkowalczyk */ public class Aw22Rule04011Test extends Aw22RuleImplementationTestCase { /** * Default constructor */ public Aw22Rule04011Test (String testName){ super(testName); } @Override protected void setUpRuleImplementationClassName() { setRuleImplementationClassName( "org.asqatasun.rules.accessiweb22.Aw22Rule04011"); } @Override protected void setUpWebResourceMap() { // getWebResourceMap().put("AW22.Test.4.1.1-1Passed-01", // getWebResourceFactory().createPage( // getTestcasesFilePath() + "accessiweb22/Aw22Rule04011/AW22.Test.4.1.1-1Passed-01.html")); // getWebResourceMap().put("AW22.Test.4.1.1-2Failed-01", // getWebResourceFactory().createPage( // getTestcasesFilePath() + "accessiweb22/Aw22Rule04011/AW22.Test.4.1.1-2Failed-01.html")); getWebResourceMap().put("AW22.Test.4.1.1-3NMI-01", getWebResourceFactory().createPage( getTestcasesFilePath() + "accessiweb22/Aw22Rule04011/AW22.Test.4.1.1-3NMI-01.html")); // getWebResourceMap().put("AW22.Test.4.1.1-4NA-01", // getWebResourceFactory().createPage( // getTestcasesFilePath() + "accessiweb22/Aw22Rule04011/AW22.Test.4.1.1-4NA-01.html")); } @Override protected void setProcess() { // assertEquals(TestSolution.PASSED, // processPageTest("AW22.Test.4.1.1-1Passed-01").getValue()); // assertEquals(TestSolution.FAILED, // processPageTest("AW22.Test.4.1.1-2Failed-01").getValue()); assertEquals(TestSolution.NOT_TESTED, processPageTest("AW22.Test.4.1.1-3NMI-01").getValue()); // assertEquals(TestSolution.NOT_APPLICABLE, // processPageTest("AW22.Test.4.1.1-4NA-01").getValue()); } @Override protected void setConsolidate() { // assertEquals(TestSolution.PASSED, // consolidate("AW22.Test.4.1.1-1Passed-01").getValue()); // assertEquals(TestSolution.FAILED, // consolidate("AW22.Test.4.1.1-2Failed-01").getValue()); assertEquals(TestSolution.NOT_TESTED, consolidate("AW22.Test.4.1.1-3NMI-01").getValue()); // assertEquals(TestSolution.NOT_APPLICABLE, // consolidate("AW22.Test.4.1.1-4NA-01").getValue()); } }
agpl-3.0
deepsrijit1105/edx-platform
lms/djangoapps/grades/tests/test_scores.py
11379
""" Tests for grades.scores module. """ # pylint: disable=protected-access from collections import namedtuple import ddt from django.test import TestCase import itertools from lms.djangoapps.grades.models import BlockRecord import lms.djangoapps.grades.scores as scores from lms.djangoapps.grades.transformer import GradesTransformer from opaque_keys.edx.locator import BlockUsageLocator, CourseLocator from openedx.core.lib.block_structure.block_structure import BlockData from xmodule.graders import ProblemScore class TestScoredBlockTypes(TestCase): """ Tests for the possibly_scored function. """ possibly_scored_block_types = { 'course', 'chapter', 'sequential', 'vertical', 'library_content', 'split_test', 'conditional', 'library', 'randomize', 'problem', 'drag-and-drop-v2', 'openassessment', 'lti', 'lti_consumer', 'videosequence', 'problemset', 'acid_parent', 'done', 'wrapper', 'edx_sga', } def test_block_types_possibly_scored(self): self.assertSetEqual( self.possibly_scored_block_types, scores._block_types_possibly_scored() ) def test_possibly_scored(self): course_key = CourseLocator(u'org', u'course', u'run') for block_type in self.possibly_scored_block_types: usage_key = BlockUsageLocator(course_key, block_type, 'mock_block_id') self.assertTrue(scores.possibly_scored(usage_key)) @ddt.ddt class TestGetScore(TestCase): """ Tests for get_score """ display_name = 'test_name' location = 'test_location' SubmissionValue = namedtuple('SubmissionValue', 'exists, weighted_earned, weighted_possible') CSMValue = namedtuple('CSMValue', 'exists, raw_earned, raw_possible') PersistedBlockValue = namedtuple('PersistedBlockValue', 'exists, raw_possible, weight, graded') ContentBlockValue = namedtuple('ContentBlockValue', 'raw_possible, weight, explicit_graded') ExpectedResult = namedtuple( 'ExpectedResult', 'raw_earned, raw_possible, weighted_earned, weighted_possible, weight, graded' ) def _create_submissions_scores(self, submission_value): """ Creates a stub result from the submissions API for the given values. """ if submission_value.exists: return {self.location: (submission_value.weighted_earned, submission_value.weighted_possible)} else: return {} def _create_csm_scores(self, csm_value): """ Creates a stub result from courseware student module for the given values. """ if csm_value.exists: stub_csm_record = namedtuple('stub_csm_record', 'correct, total') return {self.location: stub_csm_record(correct=csm_value.raw_earned, total=csm_value.raw_possible)} else: return {} def _create_persisted_block(self, persisted_block_value): """ Creates and returns a minimal BlockRecord object with the give values. """ if persisted_block_value.exists: return BlockRecord( self.location, persisted_block_value.weight, persisted_block_value.raw_possible, persisted_block_value.graded, ) else: return None def _create_block(self, content_block_value): """ Creates and returns a minimal BlockData object with the give values. """ block = BlockData(self.location) block.display_name = self.display_name block.weight = content_block_value.weight block_grades_transformer_data = block.transformer_data.get_or_create(GradesTransformer) block_grades_transformer_data.max_score = content_block_value.raw_possible setattr( block_grades_transformer_data, GradesTransformer.EXPLICIT_GRADED_FIELD_NAME, content_block_value.explicit_graded, ) return block @ddt.data( # submissions _trumps_ other values; weighted and graded from persisted-block _trumps_ latest content values ( SubmissionValue(exists=True, weighted_earned=50, weighted_possible=100), CSMValue(exists=True, raw_earned=10, raw_possible=40), PersistedBlockValue(exists=True, raw_possible=5, weight=40, graded=True), ContentBlockValue(raw_possible=1, weight=20, explicit_graded=False), ExpectedResult( raw_earned=None, raw_possible=None, weighted_earned=50, weighted_possible=100, weight=40, graded=True ), ), # same as above, except submissions doesn't exist; CSM values used ( SubmissionValue(exists=False, weighted_earned=50, weighted_possible=100), CSMValue(exists=True, raw_earned=10, raw_possible=40), PersistedBlockValue(exists=True, raw_possible=5, weight=40, graded=True), ContentBlockValue(raw_possible=1, weight=20, explicit_graded=False), ExpectedResult( raw_earned=10, raw_possible=40, weighted_earned=10, weighted_possible=40, weight=40, graded=True ), ), # neither submissions nor CSM exist; Persisted values used ( SubmissionValue(exists=False, weighted_earned=50, weighted_possible=100), CSMValue(exists=False, raw_earned=10, raw_possible=40), PersistedBlockValue(exists=True, raw_possible=5, weight=40, graded=True), ContentBlockValue(raw_possible=1, weight=20, explicit_graded=False), ExpectedResult( raw_earned=0, raw_possible=5, weighted_earned=0, weighted_possible=40, weight=40, graded=True ), ), # none of submissions, CSM, or persisted exist; Latest content values used ( SubmissionValue(exists=False, weighted_earned=50, weighted_possible=100), CSMValue(exists=False, raw_earned=10, raw_possible=40), PersistedBlockValue(exists=False, raw_possible=5, weight=40, graded=True), ContentBlockValue(raw_possible=1, weight=20, explicit_graded=False), ExpectedResult( raw_earned=0, raw_possible=1, weighted_earned=0, weighted_possible=20, weight=20, graded=False ), ), ) @ddt.unpack def test_get_score(self, submission_value, csm_value, persisted_block_value, block_value, expected_result): score = scores.get_score( self._create_submissions_scores(submission_value), self._create_csm_scores(csm_value), self._create_persisted_block(persisted_block_value), self._create_block(block_value), ) expected_score = ProblemScore( display_name=self.display_name, module_id=self.location, **expected_result._asdict() ) self.assertEquals(score, expected_score) @ddt.ddt class TestInternalWeightedScore(TestCase): """ Tests the internal helper method: _weighted_score """ @ddt.data( (0, 0, 1), (5, 0, 0), (10, 0, None), (0, 5, None), (5, 10, None), (10, 10, None), ) @ddt.unpack def test_cannot_compute(self, raw_earned, raw_possible, weight): self.assertEquals( scores._weighted_score(raw_earned, raw_possible, weight), (raw_earned, raw_possible), ) @ddt.data( (0, 5, 0, (0, 0)), (5, 5, 0, (0, 0)), (2, 5, 1, (.4, 1)), (5, 5, 1, (1, 1)), (5, 5, 3, (3, 3)), (2, 4, 6, (3, 6)), ) @ddt.unpack def test_computed(self, raw_earned, raw_possible, weight, expected_score): self.assertEquals( scores._weighted_score(raw_earned, raw_possible, weight), expected_score, ) def test_assert_on_invalid_r_possible(self): with self.assertRaises(AssertionError): scores._weighted_score(raw_earned=1, raw_possible=None, weight=1) @ddt.ddt class TestInternalGetGraded(TestCase): """ Tests the internal helper method: _get_explicit_graded """ def _create_block(self, explicit_graded_value): """ Creates and returns a minimal BlockData object with the give value for explicit_graded. """ block = BlockData('any_key') setattr( block.transformer_data.get_or_create(GradesTransformer), GradesTransformer.EXPLICIT_GRADED_FIELD_NAME, explicit_graded_value, ) return block @ddt.data(None, True, False) def test_with_no_persisted_block(self, explicitly_graded_value): block = self._create_block(explicitly_graded_value) self.assertEquals( scores._get_graded_from_block(None, block), explicitly_graded_value is not False, # defaults to True unless explicitly False ) @ddt.data( *itertools.product((True, False), (True, False, None)) ) @ddt.unpack def test_with_persisted_block(self, persisted_block_value, block_value): block = self._create_block(block_value) block_record = BlockRecord(block.location, 0, 0, persisted_block_value) self.assertEquals( scores._get_graded_from_block(block_record, block), block_record.graded, # persisted value takes precedence ) @ddt.ddt class TestInternalGetScoreFromBlock(TestCase): """ Tests the internal helper method: _get_score_from_persisted_or_latest_block """ def _create_block(self, raw_possible): """ Creates and returns a minimal BlockData object with the give value for raw_possible. """ block = BlockData('any_key') block.transformer_data.get_or_create(GradesTransformer).max_score = raw_possible return block def _verify_score_result(self, persisted_block, block, weight, expected_r_possible): """ Verifies the result of _get_score_from_persisted_or_latest_block is as expected. """ # pylint: disable=unbalanced-tuple-unpacking raw_earned, raw_possible, weighted_earned, weighted_possible = scores._get_score_from_persisted_or_latest_block( persisted_block, block, weight, ) self.assertEquals(raw_earned, 0.0) self.assertEquals(raw_possible, expected_r_possible) self.assertEquals(weighted_earned, 0.0) if weight is None or expected_r_possible == 0: self.assertEquals(weighted_possible, expected_r_possible) else: self.assertEquals(weighted_possible, weight) @ddt.data( *itertools.product((0, 1, 5), (None, 0, 1, 5)) ) @ddt.unpack def test_with_no_persisted_block(self, block_r_possible, weight): block = self._create_block(block_r_possible) self._verify_score_result(None, block, weight, block_r_possible) @ddt.data( *itertools.product((0, 1, 5), (None, 0, 1, 5), (None, 0, 1, 5)) ) @ddt.unpack def test_with_persisted_block(self, persisted_block_r_possible, block_r_possible, weight): block = self._create_block(block_r_possible) block_record = BlockRecord(block.location, 0, persisted_block_r_possible, False) self._verify_score_result(block_record, block, weight, persisted_block_r_possible)
agpl-3.0
gladk/palabos
jlabos/src/plbWrapper/lattice/dynamicsGenerator.hh
1469
/* This file is part of the Palabos library. * * Copyright (C) 2011-2017 FlowKit Sarl * Route d'Oron 2 * 1010 Lausanne, Switzerland * E-mail contact: contact@flowkit.com * * The most recent release of Palabos can be downloaded at * <http://www.palabos.org/> * * The library Palabos 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. * * The 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 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/>. */ /** \file * Generator functions for dynamics with pointer arguments, to make them * accessible to SWIG; generic code. */ #ifndef DYNAMICS_GENERATOR_HH #define DYNAMICS_GENERATOR_HH #include "plbWrapper/lattice/dynamicsGenerator.h" namespace plb { template<typename T, template<typename U> class Descriptor> RLBdynamics<T,Descriptor>* generateRLBdynamics(Dynamics<T,Descriptor>* baseDynamics) { return new RLBdynamics<T,Descriptor>(baseDynamics->clone()); } } // namespace plb #endif // DYNAMICS_GENERATOR_HH
agpl-3.0
LitusProject/Litus
module/SportBundle/Component/Controller/RunController.php
1359
<?php namespace SportBundle\Component\Controller; use Laminas\Mvc\MvcEvent; /** * We extend the CommonBundle controller. * * @author Kristof Mariën <kristof.marien@litus.cc> * @author Pieter Maene <pieter.maene@litus.cc> */ class RunController extends \CommonBundle\Component\Controller\ActionController { /** * Execute the request. * * @param MvcEvent $e The MVC event * @return array */ public function onDispatch(MvcEvent $e) { $result = parent::onDispatch($e); $e->setResult($result); return $result; } /** * We need to be able to specify all required authentication information, * which depends on the part of the site that is currently being used. * * @return array */ public function getAuthenticationHandler() { return array( 'action' => 'common_auth', 'controller' => 'login', 'auth_route' => 'common_auth', 'redirect_route' => 'sport_run_index', ); } /** * Returns the WebSocket URL. * * @return string */ protected function getSocketUrl() { return $this->getEntityManager() ->getRepository('CommonBundle\Entity\General\Config') ->getConfigValue('sport.queue_socket_public'); } }
agpl-3.0
isard-vdi/isard
authentication/model/user_test.go
2367
package model_test import ( "context" "testing" "gitlab.com/isard/isardvdi/authentication/model" "github.com/stretchr/testify/assert" r "gopkg.in/rethinkdb/rethinkdb-go.v6" ) func TestUserLoad(t *testing.T) { assert := assert.New(t) cases := map[string]struct { PrepareTest func(*r.Mock) User *model.User ExpectedUser *model.User ExpectedErr string }{ "should work as expected": { PrepareTest: func(m *r.Mock) { m.On(r.Table("users").Get("local-default-admin-admin")).Return([]interface{}{ map[string]interface{}{ "uid": "admin", "username": "admin", "password": "f0ckt3Rf$", "provider": "local", "category": "default", "role": "default", "group": "default", "name": "Administrator", "email": "admin@isardvdi.com", "photo": "https://isardvdi.com/path/to/photo.jpg", }, }, nil) }, User: &model.User{ Provider: "local", Category: "default", UID: "admin", Username: "admin", }, ExpectedUser: &model.User{ UID: "admin", Username: "admin", Password: "f0ckt3Rf$", Provider: "local", Category: "default", Role: "default", Group: "default", Name: "Administrator", Email: "admin@isardvdi.com", Photo: "https://isardvdi.com/path/to/foto.jpg", }, }, "should return an error if there's an error querying the DB": { PrepareTest: func(m *r.Mock) { m = nil }, User: &model.User{ Provider: "local", Category: "default", UID: "admin", Username: "admin", }, ExpectedErr: ":)", }, "should return not found if the user is not found": { PrepareTest: func(m *r.Mock) { m.On(r.Table("users").Get("local-default-fakeuser-fakeuser")).Return([]interface{}{}, nil) }, User: &model.User{ Provider: "local", Category: "default", UID: "fakeuser", Username: "fakeuser", }, ExpectedUser: &model.User{}, ExpectedErr: model.ErrNotFound.Error(), }, } for name, tc := range cases { t.Run(name, func(t *testing.T) { mock := r.NewMock() tc.PrepareTest(mock) err := tc.User.Load(context.Background(), mock) if tc.ExpectedErr == "" { assert.NoError(err) } else { assert.EqualError(err, tc.ExpectedErr) } mock.AssertExpectations(t) }) } }
agpl-3.0
ESOedX/edx-platform
lms/djangoapps/course_blocks/api.py
3854
""" API entry point to the course_blocks app with top-level get_course_blocks function. """ from __future__ import absolute_import from django.conf import settings from edx_when import field_data from openedx.core.djangoapps.content.block_structure.api import get_block_structure_manager from openedx.core.djangoapps.content.block_structure.transformers import BlockStructureTransformers from openedx.features.content_type_gating.block_transformers import ContentTypeGateTransformer from .transformers import library_content, load_override_data, start_date, user_partitions, visibility from .usage_info import CourseUsageInfo INDIVIDUAL_STUDENT_OVERRIDE_PROVIDER = ( 'lms.djangoapps.courseware.student_field_overrides.IndividualStudentOverrideProvider' ) def has_individual_student_override_provider(): """ check if FIELD_OVERRIDE_PROVIDERS has class `lms.djangoapps.courseware.student_field_overrides.IndividualStudentOverrideProvider` """ return INDIVIDUAL_STUDENT_OVERRIDE_PROVIDER in getattr(settings, 'FIELD_OVERRIDE_PROVIDERS', ()) def get_course_block_access_transformers(user): """ Default list of transformers for manipulating course block structures based on the user's access to the course blocks. Arguments: user (django.contrib.auth.models.User) - User object for which the block structure is to be transformed. """ course_block_access_transformers = [ library_content.ContentLibraryTransformer(), start_date.StartDateTransformer(), ContentTypeGateTransformer(), user_partitions.UserPartitionTransformer(), visibility.VisibilityTransformer(), field_data.DateOverrideTransformer(user), ] if has_individual_student_override_provider(): course_block_access_transformers += [load_override_data.OverrideDataTransformer(user)] return course_block_access_transformers def get_course_blocks( user, starting_block_usage_key, transformers=None, collected_block_structure=None, ): """ A higher order function implemented on top of the block_structure.get_blocks function returning a transformed block structure for the given user starting at starting_block_usage_key. Arguments: user (django.contrib.auth.models.User) - User object for which the block structure is to be transformed. starting_block_usage_key (UsageKey) - Specifies the starting block of the block structure that is to be transformed. transformers (BlockStructureTransformers) - A collection of transformers whose transform methods are to be called. If None, get_course_block_access_transformers() is used. collected_block_structure (BlockStructureBlockData) - A block structure retrieved from a prior call to BlockStructureManager.get_collected. Can be optionally provided if already available, for optimization. Returns: BlockStructureBlockData - A transformed block structure, starting at starting_block_usage_key, that has undergone the transform methods for the given user and the course associated with the block structure. If using the default transformers, the transformed block structure will be exactly equivalent to the blocks that the given user has access. """ if not transformers: transformers = BlockStructureTransformers(get_course_block_access_transformers(user)) transformers.usage_info = CourseUsageInfo(starting_block_usage_key.course_key, user) return get_block_structure_manager(starting_block_usage_key.course_key).get_transformed( transformers, starting_block_usage_key, collected_block_structure, )
agpl-3.0
dzc34/Asqatasun
rules/rules-rgaa3.2016/src/main/java/org/asqatasun/rules/rgaa32016/Rgaa32016Rule100501.java
1554
/* * Asqatasun - Automated webpage assessment * Copyright (C) 2008-2019 Asqatasun.org * * 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/>. * * Contact us by mail: asqatasun AT asqatasun DOT org */ package org.asqatasun.rules.rgaa32016; import org.asqatasun.ruleimplementation.AbstractNotTestedRuleImplementation; /** * Implementation of the rule 10.5.1 of the referential RGAA 3.2016 * <br/> * For more details about the implementation, refer to <a href="http://doc.asqatasun.org/en/90_Rules/rgaa3.2016/10.Presentation_of_information/Rule-10-5-1.html">the rule 10.5.1 design page.</a> * @see <a href="http://references.modernisation.gouv.fr/rgaa-accessibilite/2016/criteres.html#test-10-5-1">10.5.1 rule specification</a> * * @author */ public class Rgaa32016Rule100501 extends AbstractNotTestedRuleImplementation { /** * Default constructor */ public Rgaa32016Rule100501 () { super(); } }
agpl-3.0
jolyonb/edx-platform
common/test/acceptance/tests/discussion/test_cohorts.py
6011
""" Tests related to the cohorting feature. """ from uuid import uuid4 from common.test.acceptance.fixtures.course import CourseFixture, XBlockFixtureDesc from common.test.acceptance.pages.common.auto_auth import AutoAuthPage from common.test.acceptance.pages.lms.courseware import CoursewarePage from common.test.acceptance.pages.lms.discussion import DiscussionTabSingleThreadPage, InlineDiscussionPage from common.test.acceptance.tests.discussion.helpers import BaseDiscussionMixin, BaseDiscussionTestCase, CohortTestMixin from common.test.acceptance.tests.helpers import UniqueCourseTest from openedx.core.lib.tests import attr class NonCohortedDiscussionTestMixin(BaseDiscussionMixin): """ Mixin for tests of discussion in non-cohorted courses. """ def setup_cohorts(self): """ No cohorts are desired for this mixin. """ pass def test_non_cohort_visibility_label(self): self.setup_thread(1) self.assertEquals(self.thread_page.get_group_visibility_label(), "This post is visible to everyone.") class CohortedDiscussionTestMixin(BaseDiscussionMixin, CohortTestMixin): """ Mixin for tests of discussion in cohorted courses. """ def setup_cohorts(self): """ Sets up the course to use cohorting with a single defined cohort. """ self.setup_cohort_config(self.course_fixture) self.cohort_1_name = "Cohort 1" self.cohort_1_id = self.add_manual_cohort(self.course_fixture, self.cohort_1_name) def test_cohort_visibility_label(self): # Must be moderator to view content in a cohort other than your own AutoAuthPage(self.browser, course_id=self.course_id, roles="Moderator").visit() self.thread_id = self.setup_thread(1, group_id=self.cohort_1_id) # Enable cohorts and verify that the post shows to cohort only. self.enable_cohorting(self.course_fixture) self.enable_always_divide_inline_discussions(self.course_fixture) self.refresh_thread_page(self.thread_id) self.assertEquals( self.thread_page.get_group_visibility_label(), u"This post is visible only to {}.".format(self.cohort_1_name) ) # Disable cohorts and verify that the post now shows as visible to everyone. self.disable_cohorting(self.course_fixture) self.refresh_thread_page(self.thread_id) self.assertEquals(self.thread_page.get_group_visibility_label(), "This post is visible to everyone.") class DiscussionTabSingleThreadTest(BaseDiscussionTestCase): """ Tests for the discussion page displaying a single thread. """ def setUp(self): super(DiscussionTabSingleThreadTest, self).setUp() self.setup_cohorts() AutoAuthPage(self.browser, course_id=self.course_id).visit() def setup_thread_page(self, thread_id): self.thread_page = DiscussionTabSingleThreadPage(self.browser, self.course_id, self.discussion_id, thread_id) # pylint: disable=attribute-defined-outside-init self.thread_page.visit() # pylint: disable=unused-argument def refresh_thread_page(self, thread_id): self.browser.refresh() self.thread_page.wait_for_page() @attr(shard=5) class CohortedDiscussionTabSingleThreadTest(DiscussionTabSingleThreadTest, CohortedDiscussionTestMixin): """ Tests for the discussion page displaying a single cohorted thread. """ # Actual test method(s) defined in CohortedDiscussionTestMixin. pass @attr(shard=5) class NonCohortedDiscussionTabSingleThreadTest(DiscussionTabSingleThreadTest, NonCohortedDiscussionTestMixin): """ Tests for the discussion page displaying a single non-cohorted thread. """ # Actual test method(s) defined in NonCohortedDiscussionTestMixin. pass class InlineDiscussionTest(UniqueCourseTest): """ Tests for inline discussions """ def setUp(self): super(InlineDiscussionTest, self).setUp() self.discussion_id = "test_discussion_{}".format(uuid4().hex) self.course_fixture = CourseFixture(**self.course_info).add_children( XBlockFixtureDesc("chapter", "Test Section").add_children( XBlockFixtureDesc("sequential", "Test Subsection").add_children( XBlockFixtureDesc("vertical", "Test Unit").add_children( XBlockFixtureDesc( "discussion", "Test Discussion", metadata={"discussion_id": self.discussion_id} ) ) ) ) ).install() self.setup_cohorts() self.user_id = AutoAuthPage(self.browser, course_id=self.course_id).visit().get_user_id() def setup_thread_page(self, thread_id): CoursewarePage(self.browser, self.course_id).visit() self.show_thread(thread_id) def show_thread(self, thread_id): discussion_page = InlineDiscussionPage(self.browser, self.discussion_id) if not discussion_page.is_discussion_expanded(): discussion_page.expand_discussion() self.assertEqual(discussion_page.get_num_displayed_threads(), 1) discussion_page.show_thread(thread_id) self.thread_page = discussion_page.thread_page # pylint: disable=attribute-defined-outside-init def refresh_thread_page(self, thread_id): self.browser.refresh() self.show_thread(thread_id) @attr(shard=5) class CohortedInlineDiscussionTest(InlineDiscussionTest, CohortedDiscussionTestMixin): """ Tests for cohorted inline discussions. """ # Actual test method(s) defined in CohortedDiscussionTestMixin. pass @attr(shard=5) class NonCohortedInlineDiscussionTest(InlineDiscussionTest, NonCohortedDiscussionTestMixin): """ Tests for non-cohorted inline discussions. """ # Actual test method(s) defined in NonCohortedDiscussionTestMixin. pass
agpl-3.0
marcostudios/osu-web
resources/lang/nl/layout.php
5951
<?php /** * Copyright 2016 ppy Pty. Ltd. * * This file is part of osu!web. osu!web is distributed in the hopes of * attracting more community contributions to the core ecosystem of osu! * * osu!web is free software: you can redistribute it and/or modify * it under the terms of the Affero GNU General Public License version 3 * as published by the Free Software Foundation. * * osu!web is distributed 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 osu!web. If not, see <http://www.gnu.org/licenses/>. */ return [ 'defaults' => [ 'page_description' => 'osu! - Ritme is slechts een *klik* verwijderd! Met Ouendan/EBA, Taiko en originele spelmodi, en zelfs een volledig functionele level editor.', ], 'menu' => [ 'home' => [ '_' => 'start', 'getChangelog' => 'changelog', 'getDownload' => 'downloaden', 'getIcons' => 'iconen', 'getNews' => 'nieuws', 'supportTheGame' => 'ondersteun het spel', ], 'help' => [ '_' => 'hulp', 'getWiki' => 'wiki', 'getFaq' => 'faq', 'getSupport' => 'ondersteuning', ], 'beatmaps' => [ '_' => 'beatmaps', 'show' => 'info', 'index' => 'index', // 'getPacks' => 'pakketten', // 'getCharts' => 'grafieken', ], 'beatmapsets' => [ '_' => 'beatmapsets', 'discussion' => 'modding', ], 'ranking' => [ '_' => 'ranking', 'getOverall' => 'globaal', 'getCountry' => 'landelijke', 'getCharts' => 'grafieken', 'getMapper' => 'mapper', 'index' => 'globaal', ], 'community' => [ '_' => 'community', 'getForum' => 'forum', 'getChat' => 'chat', 'getSupport' => 'ondersteuning', 'getLive' => 'live', 'getSlack' => 'osu!dev', 'profile' => 'profiel', 'tournaments' => 'toernooien', 'tournaments-index' => 'toernooien', 'tournaments-show' => 'toernooi info', 'forum-topics-create' => 'forum', 'forum-topics-show' => 'forum', 'forum-forums-index' => 'forum', 'forum-forums-show' => 'forum', ], 'error' => [ '_' => 'fout', '404' => 'ontbreekt', '403' => 'verboden', '401' => 'onbevoegd', '405' => 'ontbreekt', '500' => 'iets brak', '503' => 'onderhoud', ], 'user' => [ '_' => 'gebruiker', 'getLogin' => 'inloggen', 'disabled' => 'inactief', 'register' => 'registreren', 'reset' => 'herstellen', 'new' => 'nieuw', 'messages' => 'Berichten', 'settings' => 'Instellingen', 'logout' => 'Uitloggen', 'help' => 'Help', ], 'store' => [ '_' => 'winkel', 'getListing' => 'index', 'getCart' => 'winkelwagen', 'getCheckout' => 'afrekenen', 'getInvoice' => 'factuur', 'getProduct' => 'artikel', 'new' => 'nieuw', 'home' => 'start', 'index' => 'start', 'thanks' => 'bedankt', ], 'admin-forum' => [ '_' => 'admin::forum', 'forum-covers-index' => 'forum covers', ], 'admin-store' => [ '_' => 'admin::store', 'orders-index' => 'bestellingen', 'orders-show' => 'bestelling', ], 'admin' => [ '_' => 'admin', 'logs-index' => 'log', 'beatmapsets' => [ '_' => 'beatmapsets', 'covers' => 'covers', 'show' => 'detail', ], ], ], 'errors' => [ '404' => [ 'error' => 'Pagina Mist', 'description' => 'Sorry, de pagina die je hebt opgevraagd is er niet!', 'link' => false, ], '403' => [ 'error' => 'Jij hoort hier niet te zijn.', 'description' => 'Je zou kunnen proberen terug te gaan.', 'link' => false, ], '401' => [ 'error' => 'Jij hoort hier niet.', 'description' => 'Je zou kunnen proberen terug te gaan. Of misschien zou je kunnen inloggen.', 'link' => false, ], '405' => [ 'error' => 'Pagina Mist', 'description' => 'Sorry, de pagina die je hebt opgevraagd is er niet!', 'link' => false, ], '500' => [ 'error' => 'Oh nee! Iets brak! ;_;', 'description' => 'We worden automatisch op de hoogte gesteld van alle fouten.', 'link' => false, ], 'fatal' => [ 'error' => 'Oh nee! Iets brak (heel erg)! ;_;', 'description' => 'We worden automatisch op de hoogte gesteld van alle fouten.', 'link' => false, ], '503' => [ 'error' => 'Offline voor onderhoud!', 'description' => 'Onderhoud duurt meestal ongeveer 5 seconden tot 10 minuten. Als we langer offline zijn, check :link voor meer informatie.', 'link' => [ 'text' => '@osustatus', 'href' => 'https://twitter.com/osustatus', ], ], // used by sentry if it returns an error 'reference' => 'Voor de zekerheid is hier een code die je aan het ondersteuningsteam kan geven!', ], ];
agpl-3.0
RealmOfAesir/backend
src/repositories/settings_repository.cpp
2612
/* Realm of Aesir backend Copyright (C) 2016 Michael de Lang 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/>. */ #include "settings_repository.h" #include <pqxx/pqxx> #include <easylogging++.h> #include <sql_exceptions.h> #include <macros.h> using namespace std; using namespace experimental; using namespace roa; using namespace pqxx; settings_repository::settings_repository(std::shared_ptr<idatabase_pool> database_pool) : repository(database_pool) { } settings_repository::settings_repository(settings_repository &repo) : repository(repo._database_pool) { } settings_repository::settings_repository(settings_repository &&repo) : repository(repo._database_pool) { } settings_repository::~settings_repository() { } auto settings_repository::create_transaction() -> decltype(repository::create_transaction()) { return repository::create_transaction(); } bool settings_repository::insert_or_update_setting(setting &sett, std::unique_ptr<idatabase_transaction> const &transaction) { auto result = transaction->execute( "INSERT INTO settings (setting_name, value) VALUES ('" + transaction->escape(sett.name) + "', '" + transaction->escape(sett.value) + "') ON CONFLICT (setting_name) DO UPDATE SET" " value = '" + transaction->escape(sett.value) + "' RETURNING xmax"); return result[0]["xmax"].as<string>() == "0"; } STD_OPTIONAL<setting> settings_repository::get_setting(std::string const &name, std::unique_ptr<idatabase_transaction> const &transaction) { auto result = transaction->execute("SELECT * FROM settings WHERE setting_name = '" + transaction->escape(name) + "'"); LOG(DEBUG) << NAMEOF(settings_repository::get_setting) << " contains " << result.size() << " entries"; if(result.size() == 0) { return {}; } return make_optional<setting>({result[0]["setting_name"].as<string>(), result[0]["value"].as<string>()}); }
agpl-3.0
Chocobozzz/PeerTube
server/lib/activitypub/videos/refresh.ts
2439
import { logger, loggerTagsFactory } from '@server/helpers/logger' import { PeerTubeRequestError } from '@server/helpers/requests' import { VideoLoadByUrlType } from '@server/lib/model-loaders' import { VideoModel } from '@server/models/video/video' import { MVideoAccountLightBlacklistAllFiles, MVideoThumbnail } from '@server/types/models' import { HttpStatusCode } from '@shared/models' import { ActorFollowHealthCache } from '../../actor-follow-health-cache' import { fetchRemoteVideo, SyncParam, syncVideoExternalAttributes } from './shared' import { APVideoUpdater } from './updater' async function refreshVideoIfNeeded (options: { video: MVideoThumbnail fetchedType: VideoLoadByUrlType syncParam: SyncParam }): Promise<MVideoThumbnail> { if (!options.video.isOutdated()) return options.video // We need more attributes if the argument video was fetched with not enough joints const video = options.fetchedType === 'all' ? options.video as MVideoAccountLightBlacklistAllFiles : await VideoModel.loadByUrlAndPopulateAccount(options.video.url) const lTags = loggerTagsFactory('ap', 'video', 'refresh', video.uuid, video.url) logger.info('Refreshing video %s.', video.url, lTags()) try { const { videoObject } = await fetchRemoteVideo(video.url) if (videoObject === undefined) { logger.warn('Cannot refresh remote video %s: invalid body.', video.url, lTags()) await video.setAsRefreshed() return video } const videoUpdater = new APVideoUpdater(videoObject, video) await videoUpdater.update() await syncVideoExternalAttributes(video, videoObject, options.syncParam) ActorFollowHealthCache.Instance.addGoodServerId(video.VideoChannel.Actor.serverId) return video } catch (err) { if ((err as PeerTubeRequestError).statusCode === HttpStatusCode.NOT_FOUND_404) { logger.info('Cannot refresh remote video %s: video does not exist anymore. Deleting it.', video.url, lTags()) // Video does not exist anymore await video.destroy() return undefined } logger.warn('Cannot refresh video %s.', options.video.url, { err, ...lTags() }) ActorFollowHealthCache.Instance.addBadServerId(video.VideoChannel.Actor.serverId) // Don't refresh in loop await video.setAsRefreshed() return video } } // --------------------------------------------------------------------------- export { refreshVideoIfNeeded }
agpl-3.0
Implem/Implem.Pleasanter
Implem.DefinitionAccessor/Directories.cs
2800
using Implem.Libraries.Utilities; using System.Collections.Generic; using System.IO; using System.Linq; namespace Implem.DefinitionAccessor { public static class Directories { private const string CodeDefinerDirectoryName = "Implem.CodeDefiner"; private const string DefinitionAccessorDirectoryName = "Implem.DefinitionAccessor"; private const string LibrariesDirectoryName = "Implem.Libraries"; public static string ServicePath() { return new DirectoryInfo(Environments.CurrentDirectoryPath).Parent.FullName; } public static string CodeDefiner(params string[] pathes) { return CurrentPath(CodeDefinerDirectoryName, pathes.ToList()); } public static string DefinitionAccessor(params string[] pathes) { return CurrentPath(DefinitionAccessorDirectoryName, pathes.ToList()); } public static string Libraries(params string[] pathes) { return CurrentPath(LibrariesDirectoryName, pathes.ToList()); } public static string Outputs(params string[] pathes) { if (Environments.CodeDefiner) { return Path.Combine(Environments.CurrentDirectoryPath, pathes.Join("\\")); } else { var list = pathes.ToList(); list.Insert(0, Environments.CurrentDirectoryPath); return Path.Combine(list.ToArray()); } } public static string Definitions(string fileName = "") { return Outputs("App_Data", "Definitions") + fileName.IsNotEmpty("\\" + fileName); } public static string Displays() { return Outputs("App_Data", "Displays"); } public static string Temp() { return Path.Combine(Environments.CurrentDirectoryPath, "App_Data", "Temp"); } public static string Logs() { return Path.Combine(Environments.CurrentDirectoryPath, "App_Data", "Logs"); } public static string Histories() { return Path.Combine(Environments.CurrentDirectoryPath, "App_Data", "Histories"); } public static string BinaryStorage() { var path = Parameters.BinaryStorage.Path; return path.IsNullOrEmpty() ? Path.Combine(Environments.CurrentDirectoryPath, "App_Data", "BinaryStorage") : path; } internal static string CurrentPath(string directoryName, List<string> pathes) { pathes.Insert(0, ServicePath()); pathes.Insert(1, directoryName); return Path.Combine(pathes.ToArray()); } } }
agpl-3.0
cykod/Webiva-social
app/models/social/friend_notification.rb
1287
class Social::FriendNotification < Message::Notification handle_actions :add_friend,:refuse_friend,:block def add_friend usr = EndUser.find_by_id(msg.data[:from_user_id]) if usr && recipient.to_user SocialFriend.add_friend(usr,recipient.to_user) msg.update_message(:success,{ :name => usr.name }) response = MessageTemplate.create_message('friend_accepted',recipient.to_user) response.send_notification(usr) end end def refuse_friend usr = EndUser.find_by_id(msg.data[:from_user_id]) if usr && recipient.to_user msg.update_message(:failure,{ :name => usr.name }) response = MessageTemplate.create_message('friend_rejected', recipient.to_user) response.send_notification(usr) end end def block usr = EndUser.find_by_id(msg.data[:from_user_id]) if usr && recipient.to_user msg.update_message(:other,{ :name => usr.name }) SocialBlock.find_by_end_user_id_and_blocked_user_id(recipient.to_user.id,usr.id) || SocialBlock.create(:end_user_id => recipient.to_user.id,:blocked_user_id => usr.id) response = MessageTemplate.create_message('friend_blocked',recipient.to_user) response.send_notification(usr) end end end
agpl-3.0
fulldump/8
component/CodeMirrorJavascript/index.js
24318
// TODO actually recognize syntax of TypeScript constructs CodeMirror.defineMode("javascript", function(config, parserConfig) { var indentUnit = config.indentUnit; var statementIndent = parserConfig.statementIndent; var jsonldMode = parserConfig.jsonld; var jsonMode = parserConfig.json || jsonldMode; var isTS = parserConfig.typescript; // Tokenizer var keywords = function(){ function kw(type) {return {type: type, style: "keyword"};} var A = kw("keyword a"), B = kw("keyword b"), C = kw("keyword c"); var operator = kw("operator"), atom = {type: "atom", style: "atom"}; var jsKeywords = { "if": kw("if"), "while": A, "with": A, "else": B, "do": B, "try": B, "finally": B, "return": C, "break": C, "continue": C, "new": C, "delete": C, "throw": C, "debugger": C, "var": kw("var"), "const": kw("var"), "let": kw("var"), "function": kw("function"), "catch": kw("catch"), "for": kw("for"), "switch": kw("switch"), "case": kw("case"), "default": kw("default"), "in": operator, "typeof": operator, "instanceof": operator, "true": atom, "false": atom, "null": atom, "undefined": atom, "NaN": atom, "Infinity": atom, "this": kw("this"), "module": kw("module"), "class": kw("class"), "super": kw("atom"), "yield": C, "export": kw("export"), "import": kw("import"), "extends": C }; // Extend the 'normal' keywords with the TypeScript language extensions if (isTS) { var type = {type: "variable", style: "variable-3"}; var tsKeywords = { // object-like things "interface": kw("interface"), "extends": kw("extends"), "constructor": kw("constructor"), // scope modifiers "public": kw("public"), "private": kw("private"), "protected": kw("protected"), "static": kw("static"), // types "string": type, "number": type, "bool": type, "any": type }; for (var attr in tsKeywords) { jsKeywords[attr] = tsKeywords[attr]; } } return jsKeywords; }(); var isOperatorChar = /[+\-*&%=<>!?|~^]/; var isJsonldKeyword = /^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/; function readRegexp(stream) { var escaped = false, next, inSet = false; while ((next = stream.next()) != null) { if (!escaped) { if (next == "/" && !inSet) return; if (next == "[") inSet = true; else if (inSet && next == "]") inSet = false; } escaped = !escaped && next == "\\"; } } // Used as scratch variables to communicate multiple values without // consing up tons of objects. var type, content; function ret(tp, style, cont) { type = tp; content = cont; return style; } function tokenBase(stream, state) { var ch = stream.next(); if (ch == '"' || ch == "'") { state.tokenize = tokenString(ch); return state.tokenize(stream, state); } else if (ch == "." && stream.match(/^\d+(?:[eE][+\-]?\d+)?/)) { return ret("number", "number"); } else if (ch == "." && stream.match("..")) { return ret("spread", "meta"); } else if (/[\[\]{}\(\),;\:\.]/.test(ch)) { return ret(ch); } else if (ch == "=" && stream.eat(">")) { return ret("=>", "operator"); } else if (ch == "0" && stream.eat(/x/i)) { stream.eatWhile(/[\da-f]/i); return ret("number", "number"); } else if (/\d/.test(ch)) { stream.match(/^\d*(?:\.\d*)?(?:[eE][+\-]?\d+)?/); return ret("number", "number"); } else if (ch == "/") { if (stream.eat("*")) { state.tokenize = tokenComment; return tokenComment(stream, state); } else if (stream.eat("/")) { stream.skipToEnd(); return ret("comment", "comment"); } else if (state.lastType == "operator" || state.lastType == "keyword c" || state.lastType == "sof" || /^[\[{}\(,;:]$/.test(state.lastType)) { readRegexp(stream); stream.eatWhile(/[gimy]/); // 'y' is "sticky" option in Mozilla return ret("regexp", "string-2"); } else { stream.eatWhile(isOperatorChar); return ret("operator", "operator", stream.current()); } } else if (ch == "`") { state.tokenize = tokenQuasi; return tokenQuasi(stream, state); } else if (ch == "#") { stream.skipToEnd(); return ret("error", "error"); } else if (isOperatorChar.test(ch)) { stream.eatWhile(isOperatorChar); return ret("operator", "operator", stream.current()); } else { stream.eatWhile(/[\w\$_]/); var word = stream.current(), known = keywords.propertyIsEnumerable(word) && keywords[word]; return (known && state.lastType != ".") ? ret(known.type, known.style, word) : ret("variable", "variable", word); } } function tokenString(quote) { return function(stream, state) { var escaped = false, next; if (jsonldMode && stream.peek() == "@" && stream.match(isJsonldKeyword)){ state.tokenize = tokenBase; return ret("jsonld-keyword", "meta"); } while ((next = stream.next()) != null) { if (next == quote && !escaped) break; escaped = !escaped && next == "\\"; } if (!escaped) state.tokenize = tokenBase; return ret("string", "string"); }; } function tokenComment(stream, state) { var maybeEnd = false, ch; while (ch = stream.next()) { if (ch == "/" && maybeEnd) { state.tokenize = tokenBase; break; } maybeEnd = (ch == "*"); } return ret("comment", "comment"); } function tokenQuasi(stream, state) { var escaped = false, next; while ((next = stream.next()) != null) { if (!escaped && (next == "`" || next == "$" && stream.eat("{"))) { state.tokenize = tokenBase; break; } escaped = !escaped && next == "\\"; } return ret("quasi", "string-2", stream.current()); } var brackets = "([{}])"; // This is a crude lookahead trick to try and notice that we're // parsing the argument patterns for a fat-arrow function before we // actually hit the arrow token. It only works if the arrow is on // the same line as the arguments and there's no strange noise // (comments) in between. Fallback is to only notice when we hit the // arrow, and not declare the arguments as locals for the arrow // body. function findFatArrow(stream, state) { if (state.fatArrowAt) state.fatArrowAt = null; var arrow = stream.string.indexOf("=>", stream.start); if (arrow < 0) return; var depth = 0, sawSomething = false; for (var pos = arrow - 1; pos >= 0; --pos) { var ch = stream.string.charAt(pos); var bracket = brackets.indexOf(ch); if (bracket >= 0 && bracket < 3) { if (!depth) { ++pos; break; } if (--depth == 0) break; } else if (bracket >= 3 && bracket < 6) { ++depth; } else if (/[$\w]/.test(ch)) { sawSomething = true; } else if (sawSomething && !depth) { ++pos; break; } } if (sawSomething && !depth) state.fatArrowAt = pos; } // Parser var atomicTypes = {"atom": true, "number": true, "variable": true, "string": true, "regexp": true, "this": true, "jsonld-keyword": true}; function JSLexical(indented, column, type, align, prev, info) { this.indented = indented; this.column = column; this.type = type; this.prev = prev; this.info = info; if (align != null) this.align = align; } function inScope(state, varname) { for (var v = state.localVars; v; v = v.next) if (v.name == varname) return true; for (var cx = state.context; cx; cx = cx.prev) { for (var v = cx.vars; v; v = v.next) if (v.name == varname) return true; } } function parseJS(state, style, type, content, stream) { var cc = state.cc; // Communicate our context to the combinators. // (Less wasteful than consing up a hundred closures on every call.) cx.state = state; cx.stream = stream; cx.marked = null, cx.cc = cc; if (!state.lexical.hasOwnProperty("align")) state.lexical.align = true; while(true) { var combinator = cc.length ? cc.pop() : jsonMode ? expression : statement; if (combinator(type, content)) { while(cc.length && cc[cc.length - 1].lex) cc.pop()(); if (cx.marked) return cx.marked; if (type == "variable" && inScope(state, content)) return "variable-2"; return style; } } } // Combinator utils var cx = {state: null, column: null, marked: null, cc: null}; function pass() { for (var i = arguments.length - 1; i >= 0; i--) cx.cc.push(arguments[i]); } function cont() { pass.apply(null, arguments); return true; } function register(varname) { function inList(list) { for (var v = list; v; v = v.next) if (v.name == varname) return true; return false; } var state = cx.state; if (state.context) { cx.marked = "def"; if (inList(state.localVars)) return; state.localVars = {name: varname, next: state.localVars}; } else { if (inList(state.globalVars)) return; if (parserConfig.globalVars) state.globalVars = {name: varname, next: state.globalVars}; } } // Combinators var defaultVars = {name: "this", next: {name: "arguments"}}; function pushcontext() { cx.state.context = {prev: cx.state.context, vars: cx.state.localVars}; cx.state.localVars = defaultVars; } function popcontext() { cx.state.localVars = cx.state.context.vars; cx.state.context = cx.state.context.prev; } function pushlex(type, info) { var result = function() { var state = cx.state, indent = state.indented; if (state.lexical.type == "stat") indent = state.lexical.indented; state.lexical = new JSLexical(indent, cx.stream.column(), type, null, state.lexical, info); }; result.lex = true; return result; } function poplex() { var state = cx.state; if (state.lexical.prev) { if (state.lexical.type == ")") state.indented = state.lexical.indented; state.lexical = state.lexical.prev; } } poplex.lex = true; function expect(wanted) { return function(type) { if (type == wanted) return cont(); else if (wanted == ";") return pass(); else return cont(arguments.callee); }; } function statement(type, value) { if (type == "var") return cont(pushlex("vardef", value.length), vardef, expect(";"), poplex); if (type == "keyword a") return cont(pushlex("form"), expression, statement, poplex); if (type == "keyword b") return cont(pushlex("form"), statement, poplex); if (type == "{") return cont(pushlex("}"), block, poplex); if (type == ";") return cont(); if (type == "if") return cont(pushlex("form"), expression, statement, poplex, maybeelse); if (type == "function") return cont(functiondef); if (type == "for") return cont(pushlex("form"), forspec, statement, poplex); if (type == "variable") return cont(pushlex("stat"), maybelabel); if (type == "switch") return cont(pushlex("form"), expression, pushlex("}", "switch"), expect("{"), block, poplex, poplex); if (type == "case") return cont(expression, expect(":")); if (type == "default") return cont(expect(":")); if (type == "catch") return cont(pushlex("form"), pushcontext, expect("("), funarg, expect(")"), statement, poplex, popcontext); if (type == "module") return cont(pushlex("form"), pushcontext, afterModule, popcontext, poplex); if (type == "class") return cont(pushlex("form"), className, objlit, poplex); if (type == "export") return cont(pushlex("form"), afterExport, poplex); if (type == "import") return cont(pushlex("form"), afterImport, poplex); return pass(pushlex("stat"), expression, expect(";"), poplex); } function expression(type) { return expressionInner(type, false); } function expressionNoComma(type) { return expressionInner(type, true); } function expressionInner(type, noComma) { if (cx.state.fatArrowAt == cx.stream.start) { var body = noComma ? arrowBodyNoComma : arrowBody; if (type == "(") return cont(pushcontext, pushlex(")"), commasep(pattern, ")"), poplex, expect("=>"), body, popcontext); else if (type == "variable") return pass(pushcontext, pattern, expect("=>"), body, popcontext); } var maybeop = noComma ? maybeoperatorNoComma : maybeoperatorComma; if (atomicTypes.hasOwnProperty(type)) return cont(maybeop); if (type == "function") return cont(functiondef); if (type == "keyword c") return cont(noComma ? maybeexpressionNoComma : maybeexpression); if (type == "(") return cont(pushlex(")"), maybeexpression, comprehension, expect(")"), poplex, maybeop); if (type == "operator" || type == "spread") return cont(noComma ? expressionNoComma : expression); if (type == "[") return cont(pushlex("]"), arrayLiteral, poplex, maybeop); if (type == "{") return contCommasep(objprop, "}", null, maybeop); return cont(); } function maybeexpression(type) { if (type.match(/[;\}\)\],]/)) return pass(); return pass(expression); } function maybeexpressionNoComma(type) { if (type.match(/[;\}\)\],]/)) return pass(); return pass(expressionNoComma); } function maybeoperatorComma(type, value) { if (type == ",") return cont(expression); return maybeoperatorNoComma(type, value, false); } function maybeoperatorNoComma(type, value, noComma) { var me = noComma == false ? maybeoperatorComma : maybeoperatorNoComma; var expr = noComma == false ? expression : expressionNoComma; if (value == "=>") return cont(pushcontext, noComma ? arrowBodyNoComma : arrowBody, popcontext); if (type == "operator") { if (/\+\+|--/.test(value)) return cont(me); if (value == "?") return cont(expression, expect(":"), expr); return cont(expr); } if (type == "quasi") { cx.cc.push(me); return quasi(value); } if (type == ";") return; if (type == "(") return contCommasep(expressionNoComma, ")", "call", me); if (type == ".") return cont(property, me); if (type == "[") return cont(pushlex("]"), maybeexpression, expect("]"), poplex, me); } function quasi(value) { if (value.slice(value.length - 2) != "${") return cont(); return cont(expression, continueQuasi); } function continueQuasi(type) { if (type == "}") { cx.marked = "string-2"; cx.state.tokenize = tokenQuasi; return cont(); } } function arrowBody(type) { findFatArrow(cx.stream, cx.state); if (type == "{") return pass(statement); return pass(expression); } function arrowBodyNoComma(type) { findFatArrow(cx.stream, cx.state); if (type == "{") return pass(statement); return pass(expressionNoComma); } function maybelabel(type) { if (type == ":") return cont(poplex, statement); return pass(maybeoperatorComma, expect(";"), poplex); } function property(type) { if (type == "variable") {cx.marked = "property"; return cont();} } function objprop(type, value) { if (type == "variable") { cx.marked = "property"; if (value == "get" || value == "set") return cont(getterSetter); } else if (type == "number" || type == "string") { cx.marked = jsonldMode ? "property" : (type + " property"); } else if (type == "[") { return cont(expression, expect("]"), afterprop); } if (atomicTypes.hasOwnProperty(type)) return cont(afterprop); } function getterSetter(type) { if (type != "variable") return pass(afterprop); cx.marked = "property"; return cont(functiondef); } function afterprop(type) { if (type == ":") return cont(expressionNoComma); if (type == "(") return pass(functiondef); } function commasep(what, end) { function proceed(type) { if (type == ",") { var lex = cx.state.lexical; if (lex.info == "call") lex.pos = (lex.pos || 0) + 1; return cont(what, proceed); } if (type == end) return cont(); return cont(expect(end)); } return function(type) { if (type == end) return cont(); return pass(what, proceed); }; } function contCommasep(what, end, info) { for (var i = 3; i < arguments.length; i++) cx.cc.push(arguments[i]); return cont(pushlex(end, info), commasep(what, end), poplex); } function block(type) { if (type == "}") return cont(); return pass(statement, block); } function maybetype(type) { if (isTS && type == ":") return cont(typedef); } function typedef(type) { if (type == "variable"){cx.marked = "variable-3"; return cont();} } function vardef() { return pass(pattern, maybetype, maybeAssign, vardefCont); } function pattern(type, value) { if (type == "variable") { register(value); return cont(); } if (type == "[") return contCommasep(pattern, "]"); if (type == "{") return contCommasep(proppattern, "}"); } function proppattern(type, value) { if (type == "variable" && !cx.stream.match(/^\s*:/, false)) { register(value); return cont(maybeAssign); } if (type == "variable") cx.marked = "property"; return cont(expect(":"), pattern, maybeAssign); } function maybeAssign(_type, value) { if (value == "=") return cont(expressionNoComma); } function vardefCont(type) { if (type == ",") return cont(vardef); } function maybeelse(type, value) { if (type == "keyword b" && value == "else") return cont(pushlex("form"), statement, poplex); } function forspec(type) { if (type == "(") return cont(pushlex(")"), forspec1, expect(")"), poplex); } function forspec1(type) { if (type == "var") return cont(vardef, expect(";"), forspec2); if (type == ";") return cont(forspec2); if (type == "variable") return cont(formaybeinof); return pass(expression, expect(";"), forspec2); } function formaybeinof(_type, value) { if (value == "in" || value == "of") { cx.marked = "keyword"; return cont(expression); } return cont(maybeoperatorComma, forspec2); } function forspec2(type, value) { if (type == ";") return cont(forspec3); if (value == "in" || value == "of") { cx.marked = "keyword"; return cont(expression); } return pass(expression, expect(";"), forspec3); } function forspec3(type) { if (type != ")") cont(expression); } function functiondef(type, value) { if (value == "*") {cx.marked = "keyword"; return cont(functiondef);} if (type == "variable") {register(value); return cont(functiondef);} if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, statement, popcontext); } function funarg(type) { if (type == "spread") return cont(funarg); return pass(pattern, maybetype); } function className(type, value) { if (type == "variable") {register(value); return cont(classNameAfter);} } function classNameAfter(_type, value) { if (value == "extends") return cont(expression); } function objlit(type) { if (type == "{") return contCommasep(objprop, "}"); } function afterModule(type, value) { if (type == "string") return cont(statement); if (type == "variable") { register(value); return cont(maybeFrom); } } function afterExport(_type, value) { if (value == "*") { cx.marked = "keyword"; return cont(maybeFrom, expect(";")); } if (value == "default") { cx.marked = "keyword"; return cont(expression, expect(";")); } return pass(statement); } function afterImport(type) { if (type == "string") return cont(); return pass(importSpec, maybeFrom); } function importSpec(type, value) { if (type == "{") return contCommasep(importSpec, "}"); if (type == "variable") register(value); return cont(); } function maybeFrom(_type, value) { if (value == "from") { cx.marked = "keyword"; return cont(expression); } } function arrayLiteral(type) { if (type == "]") return cont(); return pass(expressionNoComma, maybeArrayComprehension); } function maybeArrayComprehension(type) { if (type == "for") return pass(comprehension, expect("]")); if (type == ",") return cont(commasep(expressionNoComma, "]")); return pass(commasep(expressionNoComma, "]")); } function comprehension(type) { if (type == "for") return cont(forspec, comprehension); if (type == "if") return cont(expression, comprehension); } // Interface return { startState: function(basecolumn) { var state = { tokenize: tokenBase, lastType: "sof", cc: [], lexical: new JSLexical((basecolumn || 0) - indentUnit, 0, "block", false), localVars: parserConfig.localVars, context: parserConfig.localVars && {vars: parserConfig.localVars}, indented: 0 }; if (parserConfig.globalVars && typeof parserConfig.globalVars == "object") state.globalVars = parserConfig.globalVars; return state; }, token: function(stream, state) { if (stream.sol()) { if (!state.lexical.hasOwnProperty("align")) state.lexical.align = false; state.indented = stream.indentation(); findFatArrow(stream, state); } if (state.tokenize != tokenComment && stream.eatSpace()) return null; var style = state.tokenize(stream, state); if (type == "comment") return style; state.lastType = type == "operator" && (content == "++" || content == "--") ? "incdec" : type; return parseJS(state, style, type, content, stream); }, indent: function(state, textAfter) { if (state.tokenize == tokenComment) return CodeMirror.Pass; if (state.tokenize != tokenBase) return 0; var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical; // Kludge to prevent 'maybelse' from blocking lexical scope pops for (var i = state.cc.length - 1; i >= 0; --i) { var c = state.cc[i]; if (c == poplex) lexical = lexical.prev; else if (c != maybeelse) break; } if (lexical.type == "stat" && firstChar == "}") lexical = lexical.prev; if (statementIndent && lexical.type == ")" && lexical.prev.type == "stat") lexical = lexical.prev; var type = lexical.type, closing = firstChar == type; if (type == "vardef") return lexical.indented + (state.lastType == "operator" || state.lastType == "," ? lexical.info + 1 : 0); else if (type == "form" && firstChar == "{") return lexical.indented; else if (type == "form") return lexical.indented + indentUnit; else if (type == "stat") return lexical.indented + (state.lastType == "operator" || state.lastType == "," ? statementIndent || indentUnit : 0); else if (lexical.info == "switch" && !closing && parserConfig.doubleIndentSwitch != false) return lexical.indented + (/^(?:case|default)\b/.test(textAfter) ? indentUnit : 2 * indentUnit); else if (lexical.align) return lexical.column + (closing ? 0 : 1); else return lexical.indented + (closing ? 0 : indentUnit); }, electricChars: ":{}", blockCommentStart: jsonMode ? null : "/*", blockCommentEnd: jsonMode ? null : "*/", lineComment: jsonMode ? null : "//", fold: "brace", helperType: jsonMode ? "json" : "javascript", jsonldMode: jsonldMode, jsonMode: jsonMode }; }); CodeMirror.defineMIME("text/javascript", "javascript"); CodeMirror.defineMIME("text/ecmascript", "javascript"); CodeMirror.defineMIME("application/javascript", "javascript"); CodeMirror.defineMIME("application/ecmascript", "javascript"); CodeMirror.defineMIME("application/json", {name: "javascript", json: true}); CodeMirror.defineMIME("application/x-json", {name: "javascript", json: true}); CodeMirror.defineMIME("application/ld+json", {name: "javascript", jsonld: true}); CodeMirror.defineMIME("text/typescript", { name: "javascript", typescript: true }); CodeMirror.defineMIME("application/typescript", { name: "javascript", typescript: true });
agpl-3.0
EpicCoders/epiclogger
lib/error_store.rb
4307
module ErrorStore def self.create!(request) ErrorStore::Error.new(request: request).create! end def self.find(issue) ErrorStore::Error.new(issue: issue).find end @@interfaces_list = [] def self.find_interfaces Dir[Pathname(File.dirname(__FILE__)).join('error_store/interfaces/*.rb')].each do |path| base = File.basename(path, '.rb') begin klass = interface_class(base) if !klass.respond_to?(:available) || klass.available register_interface({ name: klass.display_name, type: base.to_sym, interface: klass }) end rescue => exception Raven.capture_exception(exception) Rails.logger.error("Could not load class #{base}") end end @@interfaces_list.sort! { |a, b| a[:name].casecmp(b[:name]) } end def self.interface_class(type) "ErrorStore::Interfaces::#{type.to_s.camelize}".constantize end def self.register_interface(interface) @@interfaces_list ||= [] @@interfaces_list <<= interface end def self.available_interfaces @@interfaces_list end def self.interfaces_types @@interfaces_list.map { |i| i[:type] } end def self.get_interface(type) interface_name = INTERFACES[type] interface = available_interfaces.find { |e| e[:type] == interface_name }.try(:[], :interface) raise ErrorStore::InvalidInterface.new(self), 'This interface does not exist' if interface.nil? interface end INTERFACES = { 'exception': :exception, 'logentry': :message, 'request': :http, 'stacktrace': :stacktrace, 'template': :template, 'query': :query, 'user': :user, 'csp': :csp, 'http': :http, 'sdk': :sdk, 'breadcrumbs': :breadcrumbs, 'sentry.interfaces.Exception': :exception, 'sentry.interfaces.Message': :message, 'sentry.interfaces.Stacktrace': :stacktrace, 'sentry.interfaces.Template': :template, 'sentry.interfaces.Query': :query, 'sentry.interfaces.Http': :http, 'sentry.interfaces.User': :user, 'sentry.interfaces.Csp': :csp, 'sentry.interfaces.Breadcrumbs': :breadcrumbs } CLIENT_RESERVED_ATTRS = [ :website, :errors, :event_id, :message, :checksum, :culprit, :fingerprint, :level, :time_spent, :logger, :server_name, :site, :timestamp, :extra, :modules, :tags, :platform, :release, :environment, :interfaces ] VALID_PLATFORMS = %w(as3 c cfml csharp go java javascript node objc other perl php python ruby) LOG_LEVELS = { 10 => 'debug', 20 => 'info', 30 => 'warning', 40 => 'error', 50 => 'fatal' } # The following values control the sampling rates SAMPLE_RATES = [ # up until N events, store 1 in M [50, 1], [1000, 2], [10000, 10], [100000, 50], [1000000, 300], [10000000, 2000] ] MAX_SAMPLE_RATE = 10000 SAMPLE_TIMES = [ [3600, 1], [360, 10], [60, 60], ] MAX_SAMPLE_TIME = 10000 CURRENT_VERSION = '5' DEFAULT_LOG_LEVEL = 'error' DEFAULT_LOGGER_NAME = '' MAX_STACKTRACE_FRAMES = 50 MAX_HTTP_BODY_SIZE = 4096 * 4 # 16kb MAX_EXCEPTIONS = 25 MAX_HASH_ITEMS = 50 MAX_VARIABLE_SIZE = 512 MAX_CULPRIT_LENGTH = 200 MAX_MESSAGE_LENGTH = 1024 * 8 HTTP_METHODS = %w(GET POST PUT OPTIONS HEAD DELETE TRACE CONNECT PATCH) class StoreError < StandardError attr_reader :website_id def initialize(error_store = nil) # @website_id = error_store.website_id end def message to_s end end # an exception raised if the user does not send the right credentials class MissingCredentials < StoreError; end # an exception raised if the website is missing class WebsiteMissing < StoreError; end # an exception raised of the request data is bogus class BadData < StoreError; end # an exception raised when the timestamp is not valid class InvalidTimestamp < StoreError; end class InvalidFingerprint < StoreError; end class InvalidAttribute < StoreError; end class InvalidInterface < StoreError; end class InvalidOrigin < StoreError; end class ValidationError < StoreError; end end ErrorStore.find_interfaces
agpl-3.0
DrXyzzy/smc
src/test/puppeteer/src/test_sage_ker.ts
4256
const path = require("path"); const this_file: string = path.basename(__filename, ".js"); const debuglog = require("util").debuglog("cc-" + this_file); import chalk from "chalk"; import { Creds, Opts, PassFail, TestFiles } from "./types"; import { time_log2 } from "./time_log"; import screenshot from "./screenshot"; import { Page } from "puppeteer"; import { expect } from "chai"; export const test_sage_ker = async function( creds: Creds, opts: Opts, page: Page ): Promise<PassFail> { const pfcounts: PassFail = new PassFail(); if (opts.skip && opts.skip.test(this_file)) { debuglog("skipping test: " + this_file); pfcounts.skip += 1; return pfcounts; } try { const tm_open_sage_ker = process.hrtime.bigint(); // click the Files button let sel = '*[cocalc-test="Files"]'; await page.click(sel); debuglog("clicked Files"); sel = '*[cocalc-test="search-input"][placeholder="Search or create file"]'; await page.click(sel); await page.type(sel, TestFiles.sageipynbfile); debuglog(`entered ${TestFiles.sageipynbfile} into file search`); // find and click the file link // split file name into base and ext because they appear in separate spans const z = TestFiles.sageipynbfile.lastIndexOf("."); const tfbase = TestFiles.sageipynbfile.slice(0, z); const tfext = TestFiles.sageipynbfile.slice(z); const xpt = `//a[@cocalc-test="file-line"][//span[text()="${tfbase}"]][//span[text()="${tfext}"]]`; await page.waitForXPath(xpt); sel = '*[cocalc-test="file-line"]'; await page.click(sel); debuglog("clicked file line"); await time_log2(`open ${TestFiles.sageipynbfile}`, tm_open_sage_ker, creds, opts); const tm_sage_ker_test = process.hrtime.bigint(); sel = '*[cocalc-test="jupyter-cell"]'; await page.waitForSelector(sel); debuglog("got sage ipynb jupyter cell"); await screenshot(page, opts, "wait-for-kernel-button.png"); // sage kernel takes longer to start than python 3 system kernel //const dqs: string = 'document.querySelector("button[id=\'Kernel\']").innerText=="Kernel"'; //debuglog('dqs',dqs); //await page.waitForFunction(dqs); //debuglog('got kernel menu button'); sel = "[id='Kernel']"; await page.waitForSelector(sel, { visible: true }); await page.click(sel); debuglog("clicked Kernel button"); let linkHandlers = await page.$x( "//span[contains(., 'Restart and run all (do not stop on errors)...')]" ); await linkHandlers[0].click(); debuglog("clicked Restart and run all no stop"); linkHandlers = await page.$x( "//button[contains(., 'Restart and run all')]" ); await linkHandlers[0].click(); debuglog("clicked Restart and run all"); // make sure restart happens // document.querySelector("[cocalc-test='jupyter-cell']").innerText // ==> // "In [ ]:↵%display latex↵sum(1/x^2,x,1,oo)↵3.476 seconds1" sel = "[cocalc-test='jupyter-cell']"; const empty_exec_str: string = "In []:"; const restart_max_tries = 300; let text: string = "XX"; let step: number = 0; for (; step < restart_max_tries; step++) { text = await page.$eval(sel, function(e) { return (<HTMLElement>e).innerText.toString(); }); if (step > 0 && step % 10 == 0) debuglog(step, ": readout: ", text.substr(0, 40)); if (text.startsWith(empty_exec_str)) break; await page.waitFor(100); } const enpfx: string = text.substr(0, empty_exec_str.length); debuglog("after ", step, "tries, exec number starts with ", enpfx); expect(enpfx).to.equal(empty_exec_str); await page.$$(".myfrac"); debuglog("got fraction in sage ipynb"); sel = "button[title='Close and halt']"; await page.click(sel); debuglog("clicked halt button"); sel = '*[cocalc-test="search-input"][placeholder="Search or create file"]'; await page.waitForSelector(sel); debuglog("got file search"); await time_log2(this_file, tm_sage_ker_test, creds, opts); await screenshot(page, opts, "cocalc-sage-ipynb.png"); pfcounts.pass += 1; } catch (e) { pfcounts.fail += 1; console.log(chalk.red(`ERROR: ${e.message}`)); } return pfcounts; }
agpl-3.0
colosa/processmaker
resources/assets/js/home/main.js
2384
import Vue from "vue"; import VueRouter from "vue-router"; import VueSidebarMenu from "vue-sidebar-menu"; import VueI18n from 'vue-i18n'; import { BootstrapVue, BootstrapVueIcons } from 'bootstrap-vue'; import { ServerTable, Event, ClientTable } from 'vue-tables-2'; import VtTableHeadingCustom from './../components/vuetable/extends/VtTableHeadingCustom'; import VtSortControl from './../components/vuetable/extends/VtSortControl'; import SettingsPopover from "../components/vuetable/SettingsPopover.vue"; import Sortable from 'sortablejs'; import "@fortawesome/fontawesome-free/css/all.css"; import 'bootstrap/dist/css/bootstrap-grid.css'; import 'bootstrap/dist/css/bootstrap.min.css' import 'bootstrap-vue/dist/bootstrap-vue.css'; import VueApexCharts from 'vue-apexcharts'; import 'bootstrap-vue/dist/bootstrap-vue.css'; import VueSimpleContextMenu from 'vue-simple-context-menu'; import VtTableRow from '../components/vuetable/extends/VtTableRow'; import 'vue-simple-context-menu/dist/vue-simple-context-menu.css' import Home from "./Home"; Vue.use(VueApexCharts); Vue.use(VueRouter); Vue.use(VueSidebarMenu); Vue.use(BootstrapVue); Vue.use(BootstrapVueIcons); Vue.use(VueI18n); Vue.use(ServerTable, {}, false, 'bootstrap3', { tableHeading: VtTableHeadingCustom, sortControl: VtSortControl, tableRow: VtTableRow }); Vue.use(ClientTable, {}, false, 'bootstrap3', {}); Vue.component('settings-popover', SettingsPopover); Vue.component('apexchart', VueApexCharts); Vue.component('vue-simple-context-menu', VueSimpleContextMenu); window.ProcessMaker = { apiClient: require('axios') }; window.ProcessMaker.pluginBase = "/sysworkflow/en/neoclassic/viena/index.php"; window.ProcessMaker.apiClient.defaults.baseURL = '/sysworkflow/en/neoclassic/viena/index.php/api/'; window.ProcessMaker.SYS_SYS = "workflow"; window.ProcessMaker.SYS_LANG = "en"; window.ProcessMaker.SYS_SKIN = "neoclassic"; let messages = {}; messages[config.SYS_LANG] = config.TRANSLATIONS; const i18n = new VueI18n({ locale: config.SYS_LANG, // set locale messages, // set locale messages }); // Define routes const routes = [ //{ path: "/advanced-search", component: AdvancedSearch } ]; const router = new VueRouter({ routes, // short for `routes: routes`, }); new Vue({ i18n, // eslint-disable-line no-new el: "#app", router, render: (h) => h(Home), });
agpl-3.0
denkbar/djigger
client-ui/src/main/java/io/djigger/aggregation/Aggregation.java
1608
/******************************************************************************* * (C) Copyright 2016 Jérôme Comte and Dorian Cransac * * This file is part of djigger * * djigger 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. * * djigger 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 djigger. If not, see <http://www.gnu.org/licenses/>. * *******************************************************************************/ package io.djigger.aggregation; import io.djigger.aggregation.Thread.RealNodePathWrapper; import io.djigger.ui.model.RealNodePath; import java.util.LinkedList; import java.util.List; public class Aggregation { private final RealNodePath path; private final LinkedList<RealNodePathWrapper> samples; public Aggregation(RealNodePath path) { super(); samples = new LinkedList<>(); this.path = path; } public void addSample(RealNodePathWrapper sample) { samples.add(sample); } public RealNodePath getPath() { return path; } public List<RealNodePathWrapper> getSamples() { return samples; } }
agpl-3.0
iCloudWorkGroup/fengniao
js/entrance/sheet/getpointbyposi.js
568
'use strict'; define(function(require) { var Backbone = require('lib/backbone'), getPointByPosi; getPointByPosi = function(sheetId, mouseColPosi, mouseRowPosi) { var result = {}; var getResult = function() { return function(callback) { result.point = callback; }; }; Backbone.trigger('event:cellsContainer:getCoordinateDisplayName', mouseColPosi, mouseRowPosi , getResult()); if (result.point === undefined) { result.point = { col: '', row: '' }; return result; } else { return result; } }; return getPointByPosi; });
agpl-3.0
alabs/nolotiro.org
test/routing/legacy_routing_test.rb
5395
# frozen_string_literal: true require "test_helper" require "support/routing" require "support/web_mocking" class LegacyRoutingTest < ActionDispatch::IntegrationTest include Routing include WebMocking before do @ad = create(:ad) @user = create(:user) @another_user = create(:user) @admin = create(:admin) end def test_route_to_home assert_recognizes( { controller: "woeid", action: "show", type: "give" }, "/" ) end def test_route_to_woeid_ads assert_woeid_ad_routing "/es/woeid/766273/give", id: "766273", type: "give" assert_woeid_ad_routing "/es/woeid/766273/give/status/available", id: "766273", type: "give", status: "available" assert_woeid_ad_routing "/es/woeid/766273/give/status/booked", id: "766273", type: "give", status: "booked" assert_woeid_ad_routing "/es/woeid/766273/give/status/delivered", id: "766273", type: "give", status: "delivered" assert_woeid_ad_routing "/es/woeid/766273/want", id: "766273", type: "want" end def test_route_to_listall_ads assert_woeid_ad_routing "/es/ad/listall/ad_type/give", type: "give" assert_woeid_ad_routing "/es/ad/listall/ad_type/give/status/available", type: "give", status: "available" assert_woeid_ad_routing "/es/ad/listall/ad_type/give/status/booked", type: "give", status: "booked" assert_woeid_ad_routing "/es/ad/listall/ad_type/give/status/delivered", type: "give", status: "delivered" assert_woeid_ad_routing "/es/ad/listall/ad_type/want", type: "want" end def test_routes_to_location_change assert_routing "/es/location/change", controller: "location", action: "ask", locale: "es" assert_routing "/es/location/change2", controller: "location", action: "change", locale: "es" end def test_routes_to_pages assert_routing "/es/page/faqs", controller: "page", action: "faqs", locale: "es" assert_routing "/es/page/rules", controller: "page", action: "rules", locale: "es" assert_routing "/es/page/translate", controller: "page", action: "translate", locale: "es" assert_routing "/es/page/privacy", controller: "page", action: "privacy", locale: "es" assert_routing "/es/page/about", controller: "page", action: "about", locale: "es" end def test_routes_to_contact assert_routing "/es/contact", controller: "contact", action: "new", locale: "es" end def test_routes_to_user_profile assert_user_routing "/es/profile/#{@user.username}" assert_user_routing "/es/profile/#{@user.id}", username: @user.id.to_s end def test_routes_to_user_present_list assert_user_routing "/es/profile/#{@user.username}/type/give", type: "give" assert_user_routing "/es/profile/#{@user.id}/type/give", type: "give", username: @user.id.to_s end def test_routes_to_user_petition_list assert_user_routing "/es/profile/#{@user.username}/type/want", type: "want" assert_user_routing "/es/profile/#{@user.id}/type/want", type: "want", username: @user.id.to_s end def test_routes_to_user_available_ads assert_user_routing "/es/profile/#{@user.username}/type/give/status/available", type: "give", status: "available" assert_user_routing "/es/profile/#{@user.id}/type/give/status/available", type: "give", status: "available", username: @user.id.to_s end def test_routes_to_user_booked_ads assert_user_routing "/es/profile/#{@user.username}/type/give/status/booked", type: "give", status: "booked" assert_user_routing "/es/profile/#{@user.id}/type/give/status/booked", type: "give", status: "booked", username: @user.id.to_s end def test_routes_to_user_delivered_ads assert_user_routing "/es/profile/#{@user.username}/type/give/status/delivered", type: "give", status: "delivered" assert_user_routing "/es/profile/#{@user.id}/type/give/status/delivered", type: "give", status: "delivered", username: @user.id.to_s end def test_routes_to_user_expired_ads assert_user_routing "/es/profile/#{@user.username}/type/give/status/expired", type: "give", status: "expired" assert_user_routing "/es/profile/#{@user.id}/type/give/status/expired", type: "give", status: "expired", username: @user.id.to_s end def test_routes_auth assert_routing "/es/user/register", action: "new", controller: "registrations", locale: "es" end def test_routes_to_ad_management assert_routing "/es/ad/create", action: "new", controller: "ads", locale: "es" assert_routing "/es/ad/#{@ad.id}/#{@ad.slug}", controller: "ads", action: "show", locale: "es", id: @ad.id.to_s, slug: "ordenador-en-vallecas" end end
agpl-3.0
splicemachine/spliceengine
db-engine/src/main/java/com/splicemachine/db/iapi/sql/dictionary/DefaultDescriptor.java
7168
/* * This file is part of Splice Machine. * Splice Machine 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, or (at your option) any later version. * Splice Machine 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 Splice Machine. * If not, see <http://www.gnu.org/licenses/>. * * Some parts of this source code are based on Apache Derby, and the following notices apply to * Apache Derby: * * Apache Derby is a subproject of the Apache DB project, and is licensed under * the Apache License, Version 2.0 (the "License"); you may not use these files * 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. * * Splice Machine, Inc. has modified the Apache Derby code in this file. * * All such Splice Machine modifications are Copyright 2012 - 2020 Splice Machine, Inc., * and are licensed to you under the GNU Affero General Public License. */ package com.splicemachine.db.iapi.sql.dictionary; import com.splicemachine.db.catalog.Dependable; import com.splicemachine.db.catalog.DependableFinder; import com.splicemachine.db.catalog.UUID; import com.splicemachine.db.iapi.error.StandardException; import com.splicemachine.db.iapi.reference.SQLState; import com.splicemachine.db.iapi.services.i18n.MessageService; import com.splicemachine.db.iapi.services.io.StoredFormatIds; import com.splicemachine.db.iapi.services.sanity.SanityManager; import com.splicemachine.db.iapi.sql.conn.LanguageConnectionContext; import com.splicemachine.db.iapi.sql.depend.DependencyManager; import com.splicemachine.db.iapi.sql.depend.Dependent; import com.splicemachine.db.iapi.sql.depend.Provider; /** * This interface is used to get information from a DefaultDescriptor. * */ public final class DefaultDescriptor extends TupleDescriptor implements UniqueTupleDescriptor, Provider, Dependent { private final int columnNumber; private final UUID defaultUUID; private final UUID tableUUID; /** * Constructor for a DefaultDescriptor * * @param dataDictionary the DD * @param defaultUUID The UUID of the default * @param tableUUID The UUID of the table * @param columnNumber The column number of the column that the default is for */ public DefaultDescriptor(DataDictionary dataDictionary, UUID defaultUUID, UUID tableUUID, int columnNumber) { super( dataDictionary ); this.defaultUUID = defaultUUID; this.tableUUID = tableUUID; this.columnNumber = columnNumber; } /** * Get the UUID of the default. * * @return The UUID of the default. */ public UUID getUUID() { return defaultUUID; } /** * Get the UUID of the table. * * @return The UUID of the table. */ public UUID getTableUUID() { return tableUUID; } /** * Get the column number of the column. * * @return The column number of the column. */ public int getColumnNumber() { return columnNumber; } /** * Convert the DefaultDescriptor to a String. * * @return A String representation of this DefaultDescriptor */ public String toString() { if (SanityManager.DEBUG) { /* ** NOTE: This does not format table, because table.toString() ** formats columns, leading to infinite recursion. */ return "defaultUUID: " + defaultUUID + "\n" + "tableUUID: " + tableUUID + "\n" + "columnNumber: " + columnNumber + "\n"; } else { return ""; } } //////////////////////////////////////////////////////////////////// // // PROVIDER INTERFACE // //////////////////////////////////////////////////////////////////// /** @return the stored form of this provider @see Dependable#getDependableFinder */ public DependableFinder getDependableFinder() { return getDependableFinder(StoredFormatIds.DEFAULT_DESCRIPTOR_FINDER_V01_ID); } /** * Return the name of this Provider. (Useful for errors.) * * @return String The name of this provider. */ public String getObjectName() { return "default"; } /** * Get the provider's UUID * * @return The provider's UUID */ public UUID getObjectID() { return defaultUUID; } /** * Get the provider's type. * * @return char The provider's type. */ public String getClassType() { return Dependable.DEFAULT; } ////////////////////////////////////////////////////// // // DEPENDENT INTERFACE // ////////////////////////////////////////////////////// /** * Check that all of the dependent's dependencies are valid. * * @return true if the dependent is currently valid */ public synchronized boolean isValid() { return true; } /** * Prepare to mark the dependent as invalid (due to at least one of * its dependencies being invalid). * * @param action The action causing the invalidation * @param p the provider * * @exception StandardException thrown if unable to make it invalid */ public void prepareToInvalidate(Provider p, int action, LanguageConnectionContext lcc) throws StandardException { DependencyManager dm = getDataDictionary().getDependencyManager(); switch (action) { /* ** Currently, the only thing we are depenedent ** on is an alias. */ default: DataDictionary dd = getDataDictionary(); ColumnDescriptor cd = dd.getColumnDescriptorByDefaultId(defaultUUID); TableDescriptor td = dd.getTableDescriptor(cd.getReferencingUUID(), null); throw StandardException.newException(SQLState.LANG_PROVIDER_HAS_DEPENDENT_OBJECT, dm.getActionString(action), p.getObjectName(), MessageService.getTextMessage( SQLState.LANG_COLUMN_DEFAULT ), td.getQualifiedName() + "." + cd.getColumnName()); } } /** * Mark the dependent as invalid (due to at least one of * its dependencies being invalid). Always an error * for a constraint -- should never have gotten here. * * @param action The action causing the invalidation * * @exception StandardException thrown if called in sanity mode */ public void makeInvalid(int action, LanguageConnectionContext lcc) throws StandardException { /* ** We should never get here, we should have barfed on ** prepareToInvalidate(). */ if (SanityManager.DEBUG) { DependencyManager dm; dm = getDataDictionary().getDependencyManager(); SanityManager.THROWASSERT("makeInvalid("+ dm.getActionString(action)+ ") not expected to get called"); } } }
agpl-3.0
estimancy/projestimate
vendor/gems/ge/app/controllers/ge/ge_models_controller.rb
5837
# encoding: UTF-8 ############################################################################# # # Estimancy, Open Source project estimation web application # Copyright (c) 2014 Estimancy (http://www.estimancy.com) # # 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. # # ====================================================================== # # ProjEstimate, Open Source project estimation web application # Copyright (c) 2013 Spirula (http://www.spirula.fr) # # 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/>. # ############################################################################# class Ge::GeModelsController < ApplicationController def show authorize! :show_modules_instances, ModuleProject @ge_model = Ge::GeModel.find(params[:id]) set_breadcrumbs "Organizations" => "/organizationals_params", "Modèle d'UO" => main_app.edit_organization_path(@ge_model.organization), @ge_model.organization => "" end def new authorize! :manage_modules_instances, ModuleProject @ge_model = Ge::GeModel.new end def edit authorize! :show_modules_instances, ModuleProject @ge_model = Ge::GeModel.find(params[:id]) set_breadcrumbs "Organizations" => "/organizationals_params", "Modèle d'UO" => main_app.edit_organization_path(@ge_model.organization), @ge_model.organization => "" end def create authorize! :manage_modules_instances, ModuleProject @ge_model = Ge::GeModel.new(params[:ge_model]) @ge_model.organization_id = params[:ge_model][:organization_id].to_i @ge_model.save redirect_to main_app.organization_module_estimation_path(@ge_model.organization_id, anchor: "effort") end def update authorize! :manage_modules_instances, ModuleProject @ge_model = Ge::GeModel.find(params[:id]) @ge_model.update_attributes(params[:ge_model]) redirect_to main_app.organization_module_estimation_path(@ge_model.organization_id, anchor: "effort") end def destroy authorize! :manage_modules_instances, ModuleProject @ge_model = Ge::GeModel.find(params[:id]) organization_id = @ge_model.organization_id @ge_model.module_projects.each do |mp| mp.destroy end @ge_model.delete redirect_to main_app.organization_module_estimation_path(@ge_model.organization_id, anchor: "effort") end def save_efforts authorize! :execute_estimation_plan, @project @ge_model = Ge::GeModel.find(params[:ge_model_id]) current_module_project.pemodule.attribute_modules.each do |am| tmp_prbl = Array.new ev = EstimationValue.where(:module_project_id => current_module_project.id, :pe_attribute_id => am.pe_attribute.id).first ["low", "most_likely", "high"].each do |level| if @ge_model.three_points_estimation? size = params[:"retained_size_#{level}"].to_f else size = params[:"retained_size_most_likely"].to_f end if am.pe_attribute.alias == "effort" effort = (@ge_model.coeff_a * size ** @ge_model.coeff_b) * @ge_model.standard_unit_coefficient ev.send("string_data_#{level}")[current_component.id] = effort ev.save tmp_prbl << ev.send("string_data_#{level}")[current_component.id] elsif am.pe_attribute.alias == "retained_size" ev = EstimationValue.where(:module_project_id => current_module_project.id, :pe_attribute_id => am.pe_attribute.id).first ev.send("string_data_#{level}")[current_component.id] = size ev.save tmp_prbl << ev.send("string_data_#{level}")[current_component.id] end end unless @ge_model.three_points_estimation? tmp_prbl[0] = tmp_prbl[1] tmp_prbl[2] = tmp_prbl[1] end ev.update_attribute(:"string_data_probable", { current_component.id => ((tmp_prbl[0].to_f + 4 * tmp_prbl[1].to_f + tmp_prbl[2].to_f)/6) } ) end current_module_project.nexts.each do |n| ModuleProject::common_attributes(current_module_project, n).each do |ca| ["low", "most_likely", "high"].each do |level| EstimationValue.where(:module_project_id => n.id, :pe_attribute_id => ca.id).first.update_attribute(:"string_data_#{level}", { current_component.id => nil } ) EstimationValue.where(:module_project_id => n.id, :pe_attribute_id => ca.id).first.update_attribute(:"string_data_probable", { current_component.id => nil } ) end end end #@current_organization.fields.each do |field| current_module_project.views_widgets.each do |vw| ViewsWidget::update_field(vw, @current_organization, current_module_project.project, current_component) end #end redirect_to main_app.dashboard_path(@project) end end
agpl-3.0
pbouillet/inspectIT
inspectIT/src/info/novatec/inspectit/rcp/repository/CmrRepositoryDefinition.java
12906
package info.novatec.inspectit.rcp.repository; import info.novatec.inspectit.cmr.service.ICmrManagementService; import info.novatec.inspectit.cmr.service.IConfigurationInterfaceService; import info.novatec.inspectit.cmr.service.IExceptionDataAccessService; import info.novatec.inspectit.cmr.service.IGlobalDataAccessService; import info.novatec.inspectit.cmr.service.IHttpTimerDataAccessService; import info.novatec.inspectit.cmr.service.IInvocationDataAccessService; import info.novatec.inspectit.cmr.service.IServerStatusService; import info.novatec.inspectit.cmr.service.IServerStatusService.ServerStatus; import info.novatec.inspectit.cmr.service.ISqlDataAccessService; import info.novatec.inspectit.cmr.service.IStorageService; import info.novatec.inspectit.cmr.service.ITimerDataAccessService; import info.novatec.inspectit.cmr.service.cache.CachedDataService; import info.novatec.inspectit.rcp.InspectIT; import info.novatec.inspectit.rcp.provider.ICmrRepositoryProvider; import info.novatec.inspectit.rcp.repository.service.RefreshEditorsCachedDataService; import info.novatec.inspectit.rcp.repository.service.cmr.CmrServiceProvider; import info.novatec.inspectit.version.VersionService; import java.util.ArrayList; import java.util.List; import java.util.Objects; /** * The CMR repository definition initializes the services exposed by the CMR. * * @author Patrice Bouillet * @author Dirk Maucher * @author Eduard Tudenhoefner * @author Matthias Huber * */ public class CmrRepositoryDefinition implements RepositoryDefinition, ICmrRepositoryProvider { /** * Default CMR name. */ public static final String DEFAULT_NAME = "Local CMR"; /** * Default CMR ip address. */ public static final String DEFAULT_IP = "localhost"; /** * Default CMR port. */ public static final int DEFAULT_PORT = 8182; /** * Default description. */ public static final String DEFAULT_DESCRIPTION = "This Central Management Repository (CMR) is automatically added by default when you first start the inspectIT."; /** * Enumeration for the online status of {@link CmrRepositoryDefinition}. * * @author Ivan Senic * */ public enum OnlineStatus { /** * Unknown state before the first check. */ UNKNOWN, /** * CMR is off-line. */ OFFLINE, /** * Status is being checked. */ CHECKING, /** * CMR is online. */ ONLINE; /** * Defines if the status can be changed. * * @param newStatus * New status * @return True if the status change is allowed. */ public boolean canChangeTo(OnlineStatus newStatus) { if (this.equals(newStatus)) { return false; } if (newStatus.equals(UNKNOWN)) { return false; } switch (this) { case OFFLINE: if (newStatus.equals(ONLINE)) { return false; } case ONLINE: if (newStatus.equals(OFFLINE)) { return false; } default: return true; } } } /** * The ip of the CMR. */ private final String ip; /** * The port used by the CMR. */ private final int port; /** * State of the CMR. */ private OnlineStatus onlineStatus; /** * Key received from the serverStatusService for checking the validation of the registered IDs * on the CMR. */ private String registrationIdKey; /** * CMR name assigned by user. */ private String name; /** * Optional description for the CMR. */ private String description; /** * The cached data service. */ private final CachedDataService cachedDataService; /** * The sql data access service. */ private final ISqlDataAccessService sqlDataAccessService; /** * The invocation data access service. */ private final IInvocationDataAccessService invocationDataAccessService; /** * The exception data access service. */ private final IExceptionDataAccessService exceptionDataAccessService; /** * The server status service exposed by the CMR and initialized by Spring. */ private final IServerStatusService serverStatusService; /** * The buffer data access service. */ private ICmrManagementService cmrManagementService; /** * The timer data access service. */ private ITimerDataAccessService timerDataAccessService; /** * The http timer data access service. */ private IHttpTimerDataAccessService httpTimerDataAccessService; /** * The {@link IGlobalDataAccessService}. */ private IGlobalDataAccessService globalDataAccessService; /** * The storage service. */ private IStorageService storageService; /** * The configuration interface service. */ private IConfigurationInterfaceService configurationInterfaceService; /** * CMR repository change listeners. */ private List<CmrRepositoryChangeListener> cmrRepositoryChangeListeners = new ArrayList<CmrRepositoryChangeListener>(1); /** * Calls default constructor with name 'Undefined'. * * @param ip * The ip of the CMR. * @param port * The port used by the CMR. */ public CmrRepositoryDefinition(String ip, int port) { this(ip, port, "Undefined"); } /** * The default constructor of this class. The ip and port is mandatory to create the connection. * * @param ip * The ip of the CMR. * @param port * The port used by the CMR. * @param name * The name of the CMR assigned by user. */ public CmrRepositoryDefinition(String ip, int port, String name) { this.ip = ip; this.port = port; this.onlineStatus = OnlineStatus.UNKNOWN; this.name = name; CmrServiceProvider cmrServiceProvider = InspectIT.getService(CmrServiceProvider.class); sqlDataAccessService = cmrServiceProvider.getSqlDataAccessService(this); serverStatusService = cmrServiceProvider.getServerStatusService(this); invocationDataAccessService = cmrServiceProvider.getInvocationDataAccessService(this); exceptionDataAccessService = cmrServiceProvider.getExceptionDataAccessService(this); httpTimerDataAccessService = cmrServiceProvider.getHttpTimerDataAccessService(this); cmrManagementService = cmrServiceProvider.getCmrManagementService(this); timerDataAccessService = cmrServiceProvider.getTimerDataAccessService(this); globalDataAccessService = cmrServiceProvider.getGlobalDataAccessService(this); storageService = cmrServiceProvider.getStorageService(this); configurationInterfaceService = cmrServiceProvider.getConfigurationInterfaceService(this); cachedDataService = new RefreshEditorsCachedDataService(globalDataAccessService, this); } /** * {@inheritDoc} */ @Override public CachedDataService getCachedDataService() { return cachedDataService; } /** * {@inheritDoc} */ @Override public IExceptionDataAccessService getExceptionDataAccessService() { return exceptionDataAccessService; } /** * {@inheritDoc} */ @Override public ISqlDataAccessService getSqlDataAccessService() { return sqlDataAccessService; } /** * {@inheritDoc} */ @Override public IInvocationDataAccessService getInvocationDataAccessService() { return invocationDataAccessService; } /** * {@inheritDoc} */ public ICmrManagementService getCmrManagementService() { return cmrManagementService; } /** * {@inheritDoc} */ @Override public ITimerDataAccessService getTimerDataAccessService() { return timerDataAccessService; } /** * {@inheritDoc} */ public IStorageService getStorageService() { return storageService; } /** * {@inheritDoc} */ @Override public IHttpTimerDataAccessService getHttpTimerDataAccessService() { return httpTimerDataAccessService; } /** * {@inheritDoc} */ @Override public IGlobalDataAccessService getGlobalDataAccessService() { return globalDataAccessService; } /** * Gets {@link #configurationInterfaceService}. * * @return {@link #configurationInterfaceService} */ public IConfigurationInterfaceService getConfigurationInterfaceService() { return configurationInterfaceService; } /** * {@inheritDoc} */ @Override public String getIp() { return ip; } /** * {@inheritDoc} */ @Override public int getPort() { return port; } /** * Registers a CMR repository change listener to this CMR if it was not already. * * @param cmrRepositoryChangeListener * {@link CmrRepositoryChangeListener}. */ public void addCmrRepositoryChangeListener(CmrRepositoryChangeListener cmrRepositoryChangeListener) { synchronized (cmrRepositoryChangeListeners) { if (!cmrRepositoryChangeListeners.contains(cmrRepositoryChangeListener)) { cmrRepositoryChangeListeners.add(cmrRepositoryChangeListener); } } } /** * Removes a CMR repository change listener to this CMR. * * @param cmrRepositoryChangeListener * {@link CmrRepositoryChangeListener}. */ public void removeCmrRepositoryChangeListener(CmrRepositoryChangeListener cmrRepositoryChangeListener) { synchronized (cmrRepositoryChangeListeners) { cmrRepositoryChangeListeners.remove(cmrRepositoryChangeListener); } } /** * @return the name */ @Override public String getName() { return name; } /** * @param name * the name to set */ public void setName(String name) { this.name = name; } /** * @return the description */ public String getDescription() { return description; } /** * @param description * the description to set */ public void setDescription(String description) { this.description = description; } /** * @return the onlineStatus */ public OnlineStatus getOnlineStatus() { return onlineStatus; } /** * If the CMR is online invokes the {@link IServerStatusService} to get the version. Otherwise * returns 'N/A'. * * @return Version of this CMR. */ public String getVersion() { if (onlineStatus != OnlineStatus.OFFLINE) { try { return serverStatusService.getVersion(); } catch (Exception e) { return VersionService.UNKNOWN_VERSION; } } else { return VersionService.UNKNOWN_VERSION; } } /** * Updates the status of the CMR if possible. * * @param newStatus * New status. * @return True if change was successful, false if the change is not allowed. */ public boolean changeOnlineStatus(OnlineStatus newStatus) { if (onlineStatus.canChangeTo(newStatus)) { OnlineStatus oldStatus = onlineStatus; onlineStatus = newStatus; synchronized (cmrRepositoryChangeListeners) { for (CmrRepositoryChangeListener changeListener : cmrRepositoryChangeListeners) { changeListener.repositoryOnlineStatusUpdated(this, oldStatus, newStatus); } } return true; } return false; } /** * Refreshes the online status. */ public void refreshOnlineStatus() { this.changeOnlineStatus(OnlineStatus.CHECKING); boolean isOnline = isOnline(); if (isOnline) { this.changeOnlineStatus(OnlineStatus.ONLINE); } else { this.changeOnlineStatus(OnlineStatus.OFFLINE); } } /** * Returns if the server is online by checking the {@link IServerStatusService}. * * @return Returns if the server is online by checking the {@link IServerStatusService}. */ private boolean isOnline() { try { ServerStatus status = serverStatusService.getServerStatus(); if (ServerStatus.SERVER_ONLINE == status) { checkKey(status.getRegistrationIdsValidationKey()); return true; } return false; } catch (Exception e) { return false; } } /** * {@inheritDoc} */ @Override public CmrRepositoryDefinition getCmrRepositoryDefinition() { return this; } /** * Check if key has changed and fire the refresh idents if necessary. * * @param newKey * New key received from status. */ private void checkKey(String newKey) { boolean isRefreshIdents = false; if (null == registrationIdKey) { registrationIdKey = newKey; } else { isRefreshIdents = !Objects.equals(registrationIdKey, newKey); // NOPMD registrationIdKey = newKey; } if (isRefreshIdents) { cachedDataService.triggerRefreshIdents(); } } /** * {@inheritDoc} */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((ip == null) ? 0 : ip.hashCode()); result = prime * result + port; return result; } /** * {@inheritDoc} */ @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } CmrRepositoryDefinition other = (CmrRepositoryDefinition) obj; if (ip == null) { if (other.ip != null) { return false; } } else if (!ip.equals(other.ip)) { return false; } if (port != other.port) { return false; } return true; } /** * {@inheritDoc} */ @Override public String toString() { return "Repository definition :: Name=" + name + " IP=" + ip + " Port=" + port; } }
agpl-3.0
RussWhitehead/HPCC-Platform
ecl/hqlcpp/hqlresource.hpp
2050
/*############################################################################## Copyright (C) 2011 HPCC Systems. All rights reserved. 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/>. ############################################################################## */ #ifndef __HQLRESOURCE_HPP_ #define __HQLRESOURCE_HPP_ #include "workunit.hpp" #include "hqlcpp.hpp" #include "hqlcpp.ipp" IHqlExpression * resourceThorGraph(HqlCppTranslator & translator, IHqlExpression * expr, ClusterType targetClusterType, unsigned clusterSize, IHqlExpression * graphIdExpr); IHqlExpression * resourceLibraryGraph(HqlCppTranslator & translator, IHqlExpression * expr, ClusterType targetClusterType, unsigned clusterSize, IHqlExpression * graphIdExpr, unsigned * numResults); IHqlExpression * resourceLoopGraph(HqlCppTranslator & translator, HqlExprCopyArray & activeRows, IHqlExpression * expr, ClusterType targetClusterType, IHqlExpression * graphIdExpr, unsigned * numResults, bool insideChildGraph); IHqlExpression * resourceNewChildGraph(HqlCppTranslator & translator, HqlExprCopyArray & activeRows, IHqlExpression * expr, ClusterType targetClusterType, IHqlExpression * graphIdExpr, unsigned * numResults); IHqlExpression * resourceRemoteGraph(HqlCppTranslator & translator, IHqlExpression * expr, ClusterType targetClusterType, unsigned clusterSize); IHqlExpression * convertSpillsToActivities(IHqlExpression * expr); #endif
agpl-3.0
mtucker6784/snipe-it
resources/lang/sr-CS/admin/asset_maintenances/table.php
204
<?php return [ 'title' => 'Održavanje imovine', 'asset_name' => 'Naziv imovine', 'is_warranty' => 'Garancija', 'dl_csv' => 'Download CSV', ];
agpl-3.0
crowdAI/crowdai
app/models/views/challenge_registrations.rb
148
class ChallengeRegistration < SqlView self.primary_key = :id after_initialize :readonly! belongs_to :challenge belongs_to :participant end
agpl-3.0
AjuntamentdeBarcelona/decidim-barcelona
db/migrate/20170128115616_make_user_group_fields_optional.rb
214
class MakeUserGroupFieldsOptional < ActiveRecord::Migration[5.0] def change change_column_null :decidim_user_groups, :document_number, true change_column_null :decidim_user_groups, :phone, true end end
agpl-3.0
okfn/ckanext-panama
ckanext/panama/helpers.py
860
from pylons import config from ckan.plugins import toolkit from ckan.lib import search import logging log = logging.getLogger(__name__) def get_default_locale(): return config.get('ckan.locale_default', 'en') def get_extra_exclude_fields(): return ['fluent_notes', 'fluent_title', 'fluent_name', 'fluent_description'] def get_recently_updated_panama_datasets(limit=3): try: pkg_search_results = toolkit.get_action('package_search')(data_dict={ 'sort': 'metadata_modified desc', 'rows': limit, })['results'] except toolkit.ValidationError, search.SearchError: return [] else: pkgs = [] for pkg in pkg_search_results: pkgs.append(toolkit.get_action('package_show')(data_dict={ 'id': pkg['id'] })) return pkgs
agpl-3.0
ComPlat/chemotion_ELN
lib/datacollector/foldercollector.rb
3059
# frozen_string_literal: true require 'zip' # Collector: folder inspection and collection class Foldercollector < Fcollector FCOLL = 'folder' private def sleep_seconds(device) 30 || Rails.configuration.datacollectors.services && (Rails.configuration.datacollectors.services.find { |e| e[:name] == device.profile.data['method'] } || {})[:watcher_sleep] end def modification_time_diff(device, folder_p) time_now = Time.now time_diff = case device.profile.data['method'] when 'folderwatcherlocal' then time_now - File.mtime(folder_p) when 'folderwatchersftp' then time_now - (Time.at @sftp.file.open(folder_p).stat.attributes[:mtime]) else 30 end time_diff end def inspect_folder(device) params = device.profile.data['method_params'] sleep_time = sleep_seconds(device).to_i new_folders(params['dir']).each do |new_folder_p| if (params['number_of_files'].blank? || (params['number_of_files']).to_i.zero?) && modification_time_diff(device, new_folder_p) < 30 sleep sleep_time end @current_collector = DatacollectorFolder.new(new_folder_p, @sftp) @current_collector.files = list_files error = CollectorError.find_by error_code: CollectorHelper.hash( @current_collector.path, @sftp ) begin stored = false if @current_collector.recipient if params['number_of_files'].present? && params['number_of_files'].to_i != 0 && @current_collector.files.length != params['number_of_files'].to_i log_info 'Wrong number of files!' next end unless error @current_collector.collect(device) log_info 'Stored!' stored = true end @current_collector.delete log_info 'Status 200' else # Recipient unknown @current_collector.delete log_info 'Recipient unknown. Folder deleted!' end rescue => e if stored CollectorHelper.write_error( CollectorHelper.hash(@current_collector.path, @sftp) ) end log_error e.backtrace.join('\n') end end end def list_files if @sftp all_files = @sftp.dir.entries(@current_collector.path).reject( &:directory? ) all_files.map!(&:name) else all_files = Dir.entries(@current_collector.path).reject { |e| File.directory?(File.join(@current_collector.path, e)) } end all_files.delete_if do |f| f.end_with?('..', '.', '.filepart', '.part') end all_files end def new_folders(monitored_folder_p) if @sftp new_folders_p = @sftp.dir.glob(monitored_folder_p, '*').select( &:directory? ) new_folders_p.map! { |dir| File.join(monitored_folder_p, dir.name) } else new_folders_p = Dir.glob(File.join(monitored_folder_p, '*')).select { |e| File.directory?(e) } end new_folders_p end end
agpl-3.0
kamax-io/mxisd
src/main/java/io/kamax/mxisd/backend/wordpress/WordpressAuthProvider.java
2303
/* * mxisd - Matrix Identity Server Daemon * Copyright (C) 2018 Kamax Sàrl * * https://www.kamax.io/ * * 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 io.kamax.mxisd.backend.wordpress; import io.kamax.matrix.ThreePid; import io.kamax.matrix._MatrixID; import io.kamax.mxisd.UserIdType; import io.kamax.mxisd.auth.provider.AuthenticatorProvider; import io.kamax.mxisd.auth.provider.BackendAuthResult; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class WordpressAuthProvider implements AuthenticatorProvider { private transient final Logger log = LoggerFactory.getLogger(WordpressAuthProvider.class); private WordpressRestBackend wordpress; public WordpressAuthProvider(WordpressRestBackend wordpress) { this.wordpress = wordpress; } @Override public boolean isEnabled() { return wordpress.isEnabled(); } @Override public BackendAuthResult authenticate(_MatrixID mxid, String password) { try { WordpressAuthData data = wordpress.authenticate(mxid.getLocalPart(), password); BackendAuthResult result = new BackendAuthResult(); if (StringUtils.isNotBlank(data.getUserEmail())) { result.withThreePid(new ThreePid("email", data.getUserEmail())); } result.succeed(mxid.getId(), UserIdType.MatrixID.getId(), data.getUserDisplayName()); return result; } catch (IllegalArgumentException e) { log.error("Authentication failed for {}: {}", mxid.getId(), e.getMessage()); return BackendAuthResult.failure(); } } }
agpl-3.0
kingjan1999/mail
l10n/fi.js
9911
OC.L10N.register( "mail", { "Mail" : "Sähköposti", "Auto detect failed. Please use manual mode." : "Automaattinen havaitseminen epäonnistui. Käytä manuaalitilaa.", "Updating account failed: " : "Tilin päivittäminen epäonnistui:", "Creating account failed: " : "Tilin luominen epäonnistui:", "Embedded message %s" : "Upotettu viesti %s", "💌 A mail app for Nextcloud" : "💌 Sähköpostisovellus Nextcloudille", "Auto" : "Automaattinen", "Name" : "Nimi", "Mail Address" : "Sähköpostiosoite", "Password" : "Salasana", "Manual" : "Manuaalinen", "IMAP Settings" : "IMAP-asetukset", "IMAP Host" : "IMAP-palvelin", "IMAP Security" : "IMAP-tietoturva", "None" : "Ei mitään", "SSL/TLS" : "SSL/TLS", "STARTTLS" : "STARTTLS", "IMAP Port" : "IMAP-portti", "IMAP User" : "IMAP-käyttäjä", "IMAP Password" : "IMAP-salasana", "SMTP Settings" : "SMTP-asetukset", "SMTP Host" : "SMTP-palvelin", "SMTP Security" : "SMTP-tietoturva", "SMTP Port" : "SMTP-portti", "SMTP User" : "SMTP-käyttäjä", "SMTP Password" : "SMTP-salasana", "Save" : "Tallenna", "Connect" : "Yhdistä", "Add mail account" : "Lisää sähköpostitili", "Use Gravatar and favicon avatars" : "Käytä Gravatar- ja favicon-avatareja", "Register as application for mail links" : "Rekisteröi sovellukseksi mail-linkeille", "Keyboard shortcuts" : "Pikanäppäimet", "From" : "Lähettäjä", "Select account" : "Valitse tili", "To" : "Vastaanottaja", "Contact or email address …" : "Yhteystieto tai sähköpostiosoite…", "No contacts found." : "Yhteystietoja ei löytynyt.", "Subject" : "Aihe", "Subject …" : "Aihe…", "This message came from a noreply address so your reply will probably not be read." : "Tämä viesti saapui noreply-osoitteesta, joten vastaustasi ei luultavasti lueta.", "Write message …" : "Kirjoita viesti…", "Saving draft …" : "Tallennetaan luonnosta…", "Draft saved" : "Luonnos tallennettu", "Upload attachment" : "Lähetä liite", "Add attachment from Files" : "Lisää liitteitä tiedostosovelluksesta", "Add attachment link from Files" : "Lisää liitelinkki tiedostosovelluksesta", "Enable formatting" : "Käytä muotoilua", "Looking for a way to encrypt your emails? Install the Mailvelope browser extension!" : "Etsitkö tapaa salata sähköpostisi? Asenna Mailvelope-selainlaajennus!", "Uploading attachments …" : "Lähetetään liitteitä…", "Sending …" : "Lähetetään…", "Error sending your message" : "Virhe viestiäsi lähettäessä", "Go back" : "Takaisin", "Retry" : "Yritä uudelleen", "Message sent!" : "Viesti lähetetty!", "Write another message" : "Kirjoita toinen viesti", "Send" : "Lähetä", "Uploading {percent}% …" : "Lähetetään {percent}% …", "Choose a file to add as attachment" : "Valitse liitteeksi lisättävä tiedosto", "Choose a file to share as a link" : "Valitse tiedosto, joka jaetaan linkkinä", "Writing mode" : "Kirjoitustila", "Preferred writing mode for new messages and replies." : "Ensisijainen kirjoitustila uusissa viesteissä ja vastauksissa.", "No messages in this folder" : "Tässä kansiossa ei ole viestejä", "Draft: " : "Luonnos: ", "Unfavorite" : "Poista suosikeista", "Favorite" : "Suosikki", "Mark unread" : "Merkitse lukemattomaksi", "Mark read" : "Merkitse luetuksi", "Unselect" : "Poista valinta", "Select" : "Valitse", "Delete" : "Poista", "Blind copy recipients only" : "Vain piilokopion vastaanottajat", "Report this bug" : "Ilmoita viasta", "Could not open mailbox" : "Postilaatikkoa ei voitu avata", "Loading messages" : "Ladataan viestejä", "Indexing your messages. This can take a bit longer for larger mailboxes." : "Viestejäsi indeksoidaan. Tämä saattaa kestää hetken varsinkin suurikokoisissa postilaatikoissa.", "Important" : "Tärkeä", "Favorites" : "Suosikit", "Other" : "Muu", "Not found" : "Ei löytynyt", "to" : "Vastaanottaja", "cc" : "Kopio", "Reply" : "Vastaa", "Reply to sender only" : "Vastaa vain lähettäjälle", "Forward" : "Lähetä edelleen", "View source" : "Näytä lähde", "Message source" : "Viestin lähde", "Could not load your message" : "Viestiä ei voitu ladata", "Import into calendar" : "Tuo kalenteriin", "Download attachment" : "Lataa liite", "Save to Files" : "Tallenna tiedostoihin", "Unnamed" : "Nimetön", "Embedded message" : "Upotettu viesti", "Choose a folder to store the attachment in" : "Valitse kansio liitetiedoston tallentamiselle", "Save all to Files" : "Tallenna kaikki tiedostoihin", "Choose a folder to store the attachments in" : "Valitse kansio johon liitteet tallennetaan", "The images have been blocked to protect your privacy." : "Kuvat estettiin yksityisyytesi suojelemiseksi.", "Show images from this sender" : "Näytä kuvat tältä lähettäjältä", "New message" : "Uusi viesti", "Settings" : "Asetukset", "Quota" : "Kiintiö", "Edit account" : "Muokkaa tiliä", "Add folder" : "Lisää kansio", "Saving" : "Tallennetaan", "Move Up" : "Siirrä ylös", "Move down" : "Siirrä alas", "Remove account" : "Poista tili", "Loading …" : "Ladataan…", "Cancel" : "Peruuta", "Show all folders" : "Näytä kaikki kansiot", "Collapse folders" : "Supista kansiot", "Mark all as read" : "Merkitse kaikki luetuiksi", "Mark all messages of this folder as read" : "Merkitse tämän kansion kaikki viestit luetuiksi", "Add subfolder" : "Lisää alikansio", "Clear cache" : "Tyhjennä välimuisti", "_{total} message_::_{total} messages_" : ["{total} viesti","{total} viestiä"], "Could not load your draft" : "Luonnosta ei voitu ladata", "Could not load original message" : "Alkuperäistä viestiä ei voitu ladata", "No message selected" : "Viestiä ei ole valittu", "Signature" : "Allekirjoitus", "A signature is added to the text of new messages and replies." : "Allekirjoitus lisätään uusien viestien ja vastausten tekstiosaan.", "Signature …" : "Allekirjoitus…", "Save signature" : "Tallenna allekirjoitus", "Import into {calendar}" : "Tuo kalenteriin {calendar}", "Event imported into {calendar}" : "Tapahtuma tuotiin kalenteriin {calendar}", "Could not create event" : "Tapahtumaa ei voitu luoda", "Airplane" : "Lentokone", "Reservation {id}" : "Varaus {id}", "Flight {flightNr} from {depAirport} to {arrAirport}" : "Lento {flightNr} lentokentältä {depAirport} lentokentälle {arrAirport}", "Train" : "Juna", "{trainNr} from {depStation} to {arrStation}" : "{trainNr} asemalta {depStation} asemalle {arrStation}", "Train from {depStation} to {arrStation}" : "Juna asemalta {depStation} asemalle {arrStation}", "Mail app" : "Sähköpostisovellus", "The mail app allows users to read mails on their IMAP accounts." : "Tämä sähköpostisovellus mahdollistaa käyttäjien lukea sähköpostiviestejä IMAP-tileiltä.", "Email: {email}" : "Sähköposti: {email}", "General" : "Yleiset", "Email address" : "Sähköpostiosoite", "IMAP" : "IMAP", "User" : "Käyttäjä", "Host" : "Palvelin", "Port" : "Portti", "SMTP" : "SMTP", "Apply and create/update for all users" : "Toteuta ja luo/päivitä kaikille käyttäjille", "With the settings above, the app will create account settings in the following way:" : "Sovellus luo tiliasetukset yllä olevin asetuksin seuraavasti:", "Account settings" : "Tilin asetukset", "Change name" : "Vaihda nimi", "Mail server" : "Sähköpostipalvelin", "Speed up your Mail experience with these quick shortcuts." : "Nopeuta sähköpostikokemustasi näillä pikanäppäimillä.", "Compose new message" : "Uusi viesti", "Newer message" : "Uudempi", "Older message" : "Vanhempi viesti", "Toggle star" : "Lisää/poista tähti", "Toggle unread" : "Merkitse luetuksi/lukemattomaksi", "Search" : "Etsi", "Refresh" : "Päivitä", "Connect your mail account" : "Yhdistä sähköpostitilisi", "Unexpected error during account creation" : "Odottamaton virhe tilin luonnin aikanaa", "All" : "Kaikki", "Archive" : "Arkisto", "Drafts" : "Luonnokset", "All inboxes" : "Kaikki saapuneiden laatikot", "Inbox" : "Saapuneet", "Junk" : "Roskaposti", "Sent" : "Lähetetyt", "Trash" : "Roskakori", "Error while sharing file" : "Virhe tiedostoa jakaessa", "{from}\n{subject}" : "{from}\n{subject}", "_%n new message \nfrom {from}_::_%n new messages \nfrom {from}_" : ["%n uusi viesti \nlähettäjältä {from}","%n uutta viestiä \nlähettäjältä {from}"], "Nextcloud Mail" : "Nextcloud-sähköposti", "Could not load {tag}{name}{endtag}" : "{tag}{name}{endtag} ei voitu ladata", "There was a problem loading {tag}{name}{endtag}" : "Ladattaessa {tag}{name}{endtag} ilmeni ongelma", "Could not load the desired message" : "Haluttua viestiä ei voitu ladata", "Could not load the message" : "Viestiä ei voitu ladata", "Error loading message" : "Virhe viestiä ladatessa", "Forwarding to %s" : "Välitä viesti %s", "Click here if you are not automatically redirected within the next few seconds." : "Klikkaa jos sinua ei uudelleenohjata automaattisesti muutamaan sekuntiin.", "Redirect" : "Uudelleenohjaus", "The link leads to %s" : "Tämä linkki johtaa kohteeseen %s", "If you don’t want to visit that page, you can return to <a href=\"%s\">Mail</a>." : "Jos et halua vierailla kyseisellä sivulla, voit palata <a href=\"%s\">sähköpostiin</a>.", "Continue to %s" : "Jatka sivulle %s" }, "nplurals=2; plural=(n != 1);");
agpl-3.0
appsembler/edx-platform
lms/djangoapps/certificates/tests/test_api.py
32358
"""Tests for the certificates Python API. """ import uuid from contextlib import contextmanager from datetime import datetime, timedelta import unittest import ddt import pytz import six from config_models.models import cache from django.conf import settings from django.test import RequestFactory, TestCase from django.test.utils import override_settings from django.urls import reverse from django.utils import timezone from freezegun import freeze_time from mock import patch from opaque_keys.edx.keys import CourseKey from opaque_keys.edx.locator import CourseLocator from course_modes.models import CourseMode from course_modes.tests.factories import CourseModeFactory from lms.djangoapps.certificates import api as certs_api from lms.djangoapps.certificates.models import ( CertificateGenerationConfiguration, CertificateStatuses, ExampleCertificate, GeneratedCertificate, certificate_status_for_student ) from lms.djangoapps.certificates.queue import XQueueAddToQueueError, XQueueCertInterface from lms.djangoapps.certificates.tests.factories import CertificateInvalidationFactory, GeneratedCertificateFactory from lms.djangoapps.courseware.tests.factories import GlobalStaffFactory from lms.djangoapps.grades.tests.utils import mock_passing_grade from openedx.core.djangoapps.site_configuration.tests.test_util import with_site_configuration from student.models import CourseEnrollment from student.tests.factories import UserFactory from util.testing import EventTestMixin from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase, SharedModuleStoreTestCase from xmodule.modulestore.tests.factories import CourseFactory FEATURES_WITH_CERTS_ENABLED = settings.FEATURES.copy() FEATURES_WITH_CERTS_ENABLED['CERTIFICATES_HTML_VIEW'] = True class WebCertificateTestMixin(object): """ Mixin with helpers for testing Web Certificates. """ @contextmanager def _mock_queue(self, is_successful=True): """ Mock the "send to XQueue" method to return either success or an error. """ symbol = 'capa.xqueue_interface.XQueueInterface.send_to_queue' with patch(symbol) as mock_send_to_queue: if is_successful: mock_send_to_queue.return_value = (0, "Successfully queued") else: mock_send_to_queue.side_effect = XQueueAddToQueueError(1, self.ERROR_REASON) yield mock_send_to_queue def _setup_course_certificate(self): """ Creates certificate configuration for course """ certificates = [ { 'id': 1, 'name': 'Test Certificate Name', 'description': 'Test Certificate Description', 'course_title': 'tes_course_title', 'signatories': [], 'version': 1, 'is_active': True } ] self.course.certificates = {'certificates': certificates} self.course.cert_html_view_enabled = True self.course.save() self.store.update_item(self.course, self.user.id) @ddt.ddt class CertificateDownloadableStatusTests(WebCertificateTestMixin, ModuleStoreTestCase): """Tests for the `certificate_downloadable_status` helper function. """ ENABLED_SIGNALS = ['course_published'] def setUp(self): super(CertificateDownloadableStatusTests, self).setUp() self.student = UserFactory() self.student_no_cert = UserFactory() self.course = CourseFactory.create( org='edx', number='verified', display_name='Verified Course', end=datetime.now(pytz.UTC), self_paced=False, certificate_available_date=datetime.now(pytz.UTC) - timedelta(days=2) ) self.request_factory = RequestFactory() def test_cert_status_with_generating(self): GeneratedCertificateFactory.create( user=self.student, course_id=self.course.id, status=CertificateStatuses.generating, mode='verified' ) self.assertEqual( certs_api.certificate_downloadable_status(self.student, self.course.id), { 'is_downloadable': False, 'is_generating': True, 'is_unverified': False, 'download_url': None, 'uuid': None, } ) def test_cert_status_with_error(self): GeneratedCertificateFactory.create( user=self.student, course_id=self.course.id, status=CertificateStatuses.error, mode='verified' ) self.assertEqual( certs_api.certificate_downloadable_status(self.student, self.course.id), { 'is_downloadable': False, 'is_generating': True, 'is_unverified': False, 'download_url': None, 'uuid': None } ) def test_without_cert(self): self.assertEqual( certs_api.certificate_downloadable_status(self.student_no_cert, self.course.id), { 'is_downloadable': False, 'is_generating': False, 'is_unverified': False, 'download_url': None, 'uuid': None, } ) def verify_downloadable_pdf_cert(self): """ Verifies certificate_downloadable_status returns the correct response for PDF certificates. """ cert = GeneratedCertificateFactory.create( user=self.student, course_id=self.course.id, status=CertificateStatuses.downloadable, mode='verified', download_url='www.google.com', ) self.assertEqual( certs_api.certificate_downloadable_status(self.student, self.course.id), { 'is_downloadable': True, 'is_generating': False, 'is_unverified': False, 'download_url': 'www.google.com', 'is_pdf_certificate': True, 'uuid': cert.verify_uuid } ) @patch.dict(settings.FEATURES, {'CERTIFICATES_HTML_VIEW': True}) def test_pdf_cert_with_html_enabled(self): self.verify_downloadable_pdf_cert() def test_pdf_cert_with_html_disabled(self): self.verify_downloadable_pdf_cert() @patch.dict(settings.FEATURES, {'CERTIFICATES_HTML_VIEW': True}) def test_with_downloadable_web_cert(self): CourseEnrollment.enroll(self.student, self.course.id, mode='honor') self._setup_course_certificate() with mock_passing_grade(): certs_api.generate_user_certificates(self.student, self.course.id) cert_status = certificate_status_for_student(self.student, self.course.id) self.assertEqual( certs_api.certificate_downloadable_status(self.student, self.course.id), { 'is_downloadable': True, 'is_generating': False, 'is_unverified': False, 'download_url': '/certificates/{uuid}'.format(uuid=cert_status['uuid']), 'is_pdf_certificate': False, 'uuid': cert_status['uuid'] } ) @unittest.skipIf(settings.TAHOE_ALWAYS_SKIP_TEST, 'Test fails. Investigated. Disabling permanently.') @ddt.data( (False, timedelta(days=2), False), (False, -timedelta(days=2), True), (True, timedelta(days=2), True) ) @ddt.unpack @patch.dict(settings.FEATURES, {'CERTIFICATES_HTML_VIEW': True}) def test_cert_api_return(self, self_paced, cert_avail_delta, cert_downloadable_status): """ Test 'downloadable status' ## Tahoe: Failing test condition Test condition 1, `(False, timedelta(days=2), False),` fails It returns `True` when expected to return `False` CourseOverview.get_from_id(course_key).may_certify() returns `True` and the matching generated certificate record 'status' field == 'downloadable' This may be a flaky test due to date issue or there may be a fundamental issue with controlling when a cert is generated or there may be a wrong assumption in when a certificate is downloadable. Note the call in this method to `mock_passing_grade` context manager which makes a passing grade before calling `generate_user_certificates`. """ cert_avail_date = datetime.now(pytz.UTC) + cert_avail_delta self.course.self_paced = self_paced self.course.certificate_available_date = cert_avail_date self.course.save() CourseEnrollment.enroll(self.student, self.course.id, mode='honor') self._setup_course_certificate() with mock_passing_grade(): certs_api.generate_user_certificates(self.student, self.course.id) self.assertEqual( certs_api.certificate_downloadable_status(self.student, self.course.id)['is_downloadable'], cert_downloadable_status ) @ddt.ddt class CertificateisInvalid(WebCertificateTestMixin, ModuleStoreTestCase): """Tests for the `is_certificate_invalid` helper function. """ def setUp(self): super(CertificateisInvalid, self).setUp() self.student = UserFactory() self.course = CourseFactory.create( org='edx', number='verified', display_name='Verified Course' ) self.global_staff = GlobalStaffFactory() self.request_factory = RequestFactory() def test_method_with_no_certificate(self): """ Test the case when there is no certificate for a user for a specific course. """ course = CourseFactory.create( org='edx', number='honor', display_name='Course 1' ) # Also check query count for 'is_certificate_invalid' method. with self.assertNumQueries(1): self.assertFalse( certs_api.is_certificate_invalid(self.student, course.id) ) @ddt.data( CertificateStatuses.generating, CertificateStatuses.downloadable, CertificateStatuses.notpassing, CertificateStatuses.error, CertificateStatuses.unverified, CertificateStatuses.deleted, CertificateStatuses.unavailable, ) def test_method_with_invalidated_cert(self, status): """ Verify that if certificate is marked as invalid than method will return True. """ generated_cert = self._generate_cert(status) self._invalidate_certificate(generated_cert, True) self.assertTrue( certs_api.is_certificate_invalid(self.student, self.course.id) ) @ddt.data( CertificateStatuses.generating, CertificateStatuses.downloadable, CertificateStatuses.notpassing, CertificateStatuses.error, CertificateStatuses.unverified, CertificateStatuses.deleted, CertificateStatuses.unavailable, ) def test_method_with_inactive_invalidated_cert(self, status): """ Verify that if certificate is valid but it's invalidated status is false than method will return false. """ generated_cert = self._generate_cert(status) self._invalidate_certificate(generated_cert, False) self.assertFalse( certs_api.is_certificate_invalid(self.student, self.course.id) ) @ddt.data( CertificateStatuses.generating, CertificateStatuses.downloadable, CertificateStatuses.notpassing, CertificateStatuses.error, CertificateStatuses.unverified, CertificateStatuses.deleted, CertificateStatuses.unavailable, ) def test_method_with_all_statues(self, status): """ Verify method return True if certificate has valid status but it is marked as invalid in CertificateInvalidation table. """ certificate = self._generate_cert(status) CertificateInvalidationFactory.create( generated_certificate=certificate, invalidated_by=self.global_staff, active=True ) # Also check query count for 'is_certificate_invalid' method. with self.assertNumQueries(2): self.assertTrue( certs_api.is_certificate_invalid(self.student, self.course.id) ) def _invalidate_certificate(self, certificate, active): """ Dry method to mark certificate as invalid. """ CertificateInvalidationFactory.create( generated_certificate=certificate, invalidated_by=self.global_staff, active=active ) # Invalidate user certificate certificate.invalidate() self.assertFalse(certificate.is_valid()) def _generate_cert(self, status): """ Dry method to generate certificate. """ return GeneratedCertificateFactory.create( user=self.student, course_id=self.course.id, status=status, mode='verified' ) class CertificateGetTests(SharedModuleStoreTestCase): """Tests for the `test_get_certificate_for_user` helper function. """ now = timezone.now() @classmethod def setUpClass(cls): cls.freezer = freeze_time(cls.now) cls.freezer.start() super(CertificateGetTests, cls).setUpClass() cls.student = UserFactory() cls.student_no_cert = UserFactory() cls.uuid = uuid.uuid4().hex cls.nonexistent_course_id = CourseKey.from_string('course-v1:some+fake+course') cls.web_cert_course = CourseFactory.create( org='edx', number='verified_1', display_name='Verified Course 1', cert_html_view_enabled=True ) cls.pdf_cert_course = CourseFactory.create( org='edx', number='verified_2', display_name='Verified Course 2', cert_html_view_enabled=False ) cls.no_cert_course = CourseFactory.create( org='edx', number='verified_3', display_name='Verified Course 3', ) # certificate for the first course GeneratedCertificateFactory.create( user=cls.student, course_id=cls.web_cert_course.id, status=CertificateStatuses.downloadable, mode='verified', download_url='www.google.com', grade="0.88", verify_uuid=cls.uuid, ) # certificate for the second course GeneratedCertificateFactory.create( user=cls.student, course_id=cls.pdf_cert_course.id, status=CertificateStatuses.downloadable, mode='honor', download_url='www.gmail.com', grade="0.99", verify_uuid=cls.uuid, ) # certificate for a course that will be deleted GeneratedCertificateFactory.create( user=cls.student, course_id=cls.nonexistent_course_id, status=CertificateStatuses.downloadable ) @classmethod def tearDownClass(cls): super(CertificateGetTests, cls).tearDownClass() cls.freezer.stop() def test_get_certificate_for_user(self): """ Test to get a certificate for a user for a specific course. """ cert = certs_api.get_certificate_for_user(self.student.username, self.web_cert_course.id) self.assertEqual(cert['username'], self.student.username) self.assertEqual(cert['course_key'], self.web_cert_course.id) self.assertEqual(cert['created'], self.now) self.assertEqual(cert['type'], CourseMode.VERIFIED) self.assertEqual(cert['status'], CertificateStatuses.downloadable) self.assertEqual(cert['grade'], "0.88") self.assertEqual(cert['is_passing'], True) self.assertEqual(cert['download_url'], 'www.google.com') def test_get_certificates_for_user(self): """ Test to get all the certificates for a user """ certs = certs_api.get_certificates_for_user(self.student.username) self.assertEqual(len(certs), 2) self.assertEqual(certs[0]['username'], self.student.username) self.assertEqual(certs[1]['username'], self.student.username) self.assertEqual(certs[0]['course_key'], self.web_cert_course.id) self.assertEqual(certs[1]['course_key'], self.pdf_cert_course.id) self.assertEqual(certs[0]['created'], self.now) self.assertEqual(certs[1]['created'], self.now) self.assertEqual(certs[0]['type'], CourseMode.VERIFIED) self.assertEqual(certs[1]['type'], CourseMode.HONOR) self.assertEqual(certs[0]['status'], CertificateStatuses.downloadable) self.assertEqual(certs[1]['status'], CertificateStatuses.downloadable) self.assertEqual(certs[0]['is_passing'], True) self.assertEqual(certs[1]['is_passing'], True) self.assertEqual(certs[0]['grade'], '0.88') self.assertEqual(certs[1]['grade'], '0.99') self.assertEqual(certs[0]['download_url'], 'www.google.com') self.assertEqual(certs[1]['download_url'], 'www.gmail.com') def test_get_certificates_for_user_by_course_keys(self): """ Test to get certificates for a user for certain course keys, in a dictionary indexed by those course keys. """ certs = certs_api.get_certificates_for_user_by_course_keys( user=self.student, course_keys={self.web_cert_course.id, self.no_cert_course.id}, ) assert set(certs.keys()) == {self.web_cert_course.id} cert = certs[self.web_cert_course.id] self.assertEqual(cert['username'], self.student.username) self.assertEqual(cert['course_key'], self.web_cert_course.id) self.assertEqual(cert['download_url'], 'www.google.com') def test_no_certificate_for_user(self): """ Test the case when there is no certificate for a user for a specific course. """ self.assertIsNone( certs_api.get_certificate_for_user(self.student_no_cert.username, self.web_cert_course.id) ) def test_no_certificates_for_user(self): """ Test the case when there are no certificates for a user. """ self.assertEqual( certs_api.get_certificates_for_user(self.student_no_cert.username), [] ) @patch.dict(settings.FEATURES, {'CERTIFICATES_HTML_VIEW': True}) def test_get_web_certificate_url(self): """ Test the get_certificate_url with a web cert course """ expected_url = reverse( 'certificates:render_cert_by_uuid', kwargs=dict(certificate_uuid=self.uuid) ) cert_url = certs_api.get_certificate_url( user_id=self.student.id, course_id=self.web_cert_course.id, uuid=self.uuid ) self.assertEqual(expected_url, cert_url) expected_url = reverse( 'certificates:render_cert_by_uuid', kwargs=dict(certificate_uuid=self.uuid) ) cert_url = certs_api.get_certificate_url( user_id=self.student.id, course_id=self.web_cert_course.id, uuid=self.uuid ) self.assertEqual(expected_url, cert_url) @patch.dict(settings.FEATURES, {'CERTIFICATES_HTML_VIEW': True}) def test_get_pdf_certificate_url(self): """ Test the get_certificate_url with a pdf cert course """ cert_url = certs_api.get_certificate_url( user_id=self.student.id, course_id=self.pdf_cert_course.id, uuid=self.uuid ) self.assertEqual('www.gmail.com', cert_url) def test_get_certificate_with_deleted_course(self): """ Test the case when there is a certificate but the course was deleted. """ self.assertIsNone( certs_api.get_certificate_for_user( self.student.username, self.nonexistent_course_id ) ) @override_settings(CERT_QUEUE='certificates') class GenerateUserCertificatesTest(EventTestMixin, WebCertificateTestMixin, ModuleStoreTestCase): """Tests for generating certificates for students. """ ERROR_REASON = "Kaboom!" ENABLED_SIGNALS = ['course_published'] def setUp(self): # pylint: disable=arguments-differ super(GenerateUserCertificatesTest, self).setUp('lms.djangoapps.certificates.api.tracker') self.student = UserFactory.create( email='joe_user@edx.org', username='joeuser', password='foo' ) self.student_no_cert = UserFactory() self.course = CourseFactory.create( org='edx', number='verified', display_name='Verified Course', grade_cutoffs={'cutoff': 0.75, 'Pass': 0.5} ) self.enrollment = CourseEnrollment.enroll(self.student, self.course.id, mode='honor') self.request_factory = RequestFactory() def test_new_cert_requests_into_xqueue_returns_generating(self): with mock_passing_grade(): with self._mock_queue(): certs_api.generate_user_certificates(self.student, self.course.id) # Verify that the certificate has status 'generating' cert = GeneratedCertificate.eligible_certificates.get(user=self.student, course_id=self.course.id) self.assertEqual(cert.status, CertificateStatuses.generating) self.assert_event_emitted( 'edx.certificate.created', user_id=self.student.id, course_id=six.text_type(self.course.id), certificate_url=certs_api.get_certificate_url(self.student.id, self.course.id), certificate_id=cert.verify_uuid, enrollment_mode=cert.mode, generation_mode='batch' ) def test_xqueue_submit_task_error(self): with mock_passing_grade(): with self._mock_queue(is_successful=False): certs_api.generate_user_certificates(self.student, self.course.id) # Verify that the certificate has been marked with status error cert = GeneratedCertificate.eligible_certificates.get(user=self.student, course_id=self.course.id) self.assertEqual(cert.status, 'error') self.assertIn(self.ERROR_REASON, cert.error_reason) def test_generate_user_certificates_with_unverified_cert_status(self): """ Generate user certificate when the certificate is unverified will trigger an update to the certificate if the user has since verified. """ self._setup_course_certificate() # generate certificate with unverified status. GeneratedCertificateFactory.create( user=self.student, course_id=self.course.id, status=CertificateStatuses.unverified, mode='verified' ) with mock_passing_grade(): with self._mock_queue(): status = certs_api.generate_user_certificates(self.student, self.course.id) self.assertEqual(status, 'generating') @patch.dict(settings.FEATURES, {'CERTIFICATES_HTML_VIEW': True}) def test_new_cert_requests_returns_generating_for_html_certificate(self): """ Test no message sent to Xqueue if HTML certificate view is enabled """ self._setup_course_certificate() with mock_passing_grade(): certs_api.generate_user_certificates(self.student, self.course.id) # Verify that the certificate has status 'downloadable' cert = GeneratedCertificate.eligible_certificates.get(user=self.student, course_id=self.course.id) self.assertEqual(cert.status, CertificateStatuses.downloadable) @patch.dict(settings.FEATURES, {'CERTIFICATES_HTML_VIEW': False}) def test_cert_url_empty_with_invalid_certificate(self): """ Test certificate url is empty if html view is not enabled and certificate is not yet generated """ url = certs_api.get_certificate_url(self.student.id, self.course.id) self.assertEqual(url, "") @ddt.ddt class CertificateGenerationEnabledTest(EventTestMixin, TestCase): """Test enabling/disabling self-generated certificates for a course. """ COURSE_KEY = CourseLocator(org='test', course='test', run='test') def setUp(self): # pylint: disable=arguments-differ super(CertificateGenerationEnabledTest, self).setUp('lms.djangoapps.certificates.api.tracker') # Since model-based configuration is cached, we need # to clear the cache before each test. cache.clear() @ddt.data( (None, None, False), (False, None, False), (False, True, False), (True, None, False), (True, False, False), (True, True, True) ) @ddt.unpack def test_cert_generation_enabled(self, is_feature_enabled, is_course_enabled, expect_enabled): if is_feature_enabled is not None: CertificateGenerationConfiguration.objects.create(enabled=is_feature_enabled) if is_course_enabled is not None: certs_api.set_cert_generation_enabled(self.COURSE_KEY, is_course_enabled) cert_event_type = 'enabled' if is_course_enabled else 'disabled' event_name = '.'.join(['edx', 'certificate', 'generation', cert_event_type]) self.assert_event_emitted( event_name, course_id=six.text_type(self.COURSE_KEY), ) self._assert_enabled_for_course(self.COURSE_KEY, expect_enabled) def test_latest_setting_used(self): # Enable the feature CertificateGenerationConfiguration.objects.create(enabled=True) # Enable for the course certs_api.set_cert_generation_enabled(self.COURSE_KEY, True) self._assert_enabled_for_course(self.COURSE_KEY, True) # Disable for the course certs_api.set_cert_generation_enabled(self.COURSE_KEY, False) self._assert_enabled_for_course(self.COURSE_KEY, False) def test_setting_is_course_specific(self): # Enable the feature CertificateGenerationConfiguration.objects.create(enabled=True) # Enable for one course certs_api.set_cert_generation_enabled(self.COURSE_KEY, True) self._assert_enabled_for_course(self.COURSE_KEY, True) # Should be disabled for another course other_course = CourseLocator(org='other', course='other', run='other') self._assert_enabled_for_course(other_course, False) def _assert_enabled_for_course(self, course_key, expect_enabled): """Check that self-generated certificates are enabled or disabled for the course. """ actual_enabled = certs_api.cert_generation_enabled(course_key) self.assertEqual(expect_enabled, actual_enabled) class GenerateExampleCertificatesTest(ModuleStoreTestCase): """Test generation of example certificates. """ COURSE_KEY = CourseLocator(org='test', course='test', run='test') def test_generate_example_certs(self): # Generate certificates for the course CourseModeFactory.create(course_id=self.COURSE_KEY, mode_slug=CourseMode.HONOR) with self._mock_xqueue() as mock_queue: certs_api.generate_example_certificates(self.COURSE_KEY) # Verify that the appropriate certs were added to the queue self._assert_certs_in_queue(mock_queue, 1) # Verify that the certificate status is "started" self._assert_cert_status({ 'description': 'honor', 'status': 'started' }) def test_generate_example_certs_with_verified_mode(self): # Create verified and honor modes for the course CourseModeFactory.create(course_id=self.COURSE_KEY, mode_slug='honor') CourseModeFactory.create(course_id=self.COURSE_KEY, mode_slug='verified') # Generate certificates for the course with self._mock_xqueue() as mock_queue: certs_api.generate_example_certificates(self.COURSE_KEY) # Verify that the appropriate certs were added to the queue self._assert_certs_in_queue(mock_queue, 2) # Verify that the certificate status is "started" self._assert_cert_status( { 'description': 'verified', 'status': 'started' }, { 'description': 'honor', 'status': 'started' } ) @contextmanager def _mock_xqueue(self): """Mock the XQueue method for adding a task to the queue. """ with patch.object(XQueueCertInterface, 'add_example_cert') as mock_queue: yield mock_queue def _assert_certs_in_queue(self, mock_queue, expected_num): """Check that the certificate generation task was added to the queue. """ certs_in_queue = [call_args[0] for (call_args, __) in mock_queue.call_args_list] self.assertEqual(len(certs_in_queue), expected_num) for cert in certs_in_queue: self.assertTrue(isinstance(cert, ExampleCertificate)) def _assert_cert_status(self, *expected_statuses): """Check the example certificate status. """ actual_status = certs_api.example_certificates_status(self.COURSE_KEY) self.assertEqual(list(expected_statuses), actual_status) @override_settings(FEATURES=FEATURES_WITH_CERTS_ENABLED) class CertificatesBrandingTest(ModuleStoreTestCase): """Test certificates branding. """ COURSE_KEY = CourseLocator(org='test', course='test', run='test') configuration = { 'logo_image_url': 'test_site/images/header-logo.png', 'SITE_NAME': 'test_site.localhost', 'urls': { 'ABOUT': 'test-site/about', 'PRIVACY': 'test-site/privacy', 'TOS_AND_HONOR': 'test-site/tos-and-honor', }, } @with_site_configuration(domain='test_site.localhost', configuration=configuration) def test_certificate_header_data(self): """ Test that get_certificate_header_context from lms.djangoapps.certificates api returns data customized according to site branding. """ # Generate certificates for the course CourseModeFactory.create(course_id=self.COURSE_KEY, mode_slug=CourseMode.HONOR) data = certs_api.get_certificate_header_context(is_secure=True) # Make sure there are not unexpected keys in dict returned by 'get_certificate_header_context' six.assertCountEqual( self, list(data.keys()), ['logo_src', 'logo_url'] ) self.assertIn( self.configuration['logo_image_url'], data['logo_src'] ) self.assertIn( self.configuration['SITE_NAME'], data['logo_url'] ) @with_site_configuration(configuration=configuration) def test_certificate_footer_data(self): """ Test that get_certificate_footer_context from lms.djangoapps.certificates api returns data customized according to site branding. """ # Generate certificates for the course CourseModeFactory.create(course_id=self.COURSE_KEY, mode_slug=CourseMode.HONOR) data = certs_api.get_certificate_footer_context() # Make sure there are not unexpected keys in dict returned by 'get_certificate_footer_context' six.assertCountEqual( self, list(data.keys()), ['company_about_url', 'company_privacy_url', 'company_tos_url'] ) self.assertIn( self.configuration['urls']['ABOUT'], data['company_about_url'] ) self.assertIn( self.configuration['urls']['PRIVACY'], data['company_privacy_url'] ) self.assertIn( self.configuration['urls']['TOS_AND_HONOR'], data['company_tos_url'] )
agpl-3.0
minh10huy/HiringBossCRM
include/connectors/sources/default/source.php
15841
<?php if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point'); /********************************************************************************* * SugarCRM Community Edition is a customer relationship management program developed by * SugarCRM, Inc. Copyright (C) 2004-2012 SugarCRM Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by the * Free Software Foundation with the addition of the following permission added * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * 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 or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. * * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road, * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License version 3, * these Appropriate Legal Notices must retain the display of the "Powered by * SugarCRM" logo. If the display of the logo is not reasonably feasible for * technical reasons, the Appropriate Legal Notices must display the words * "Powered by SugarCRM". ********************************************************************************/ /** * source is the parent class of any source object. * */ abstract class source{ /** * The name of an wrapper to use if the class wants to provide an override */ public $wrapperName; protected $_config; protected $_mapping; protected $_field_defs; protected $_enable_in_wizard = true; protected $_enable_in_hover = false; protected $_has_testing_enabled = false; protected $_required_config_fields = array(); protected $_required_config_fields_for_button = array(); protected $config_decrypted = false; /** * The ExternalAPI Base that instantiated this connector. * @var _eapm */ protected $_eapm = null; public function __construct(){ $this->loadConfig(); $this->loadMapping(); $this->loadVardefs(); } public function init(){} //////// CALLED FROM component.php /////// public function loadMapping() { $mapping = array(); $dir = str_replace('_','/',get_class($this)); if(file_exists("custom/modules/Connectors/connectors/sources/{$dir}/mapping.php")) { require("custom/modules/Connectors/connectors/sources/{$dir}/mapping.php"); } else if(file_exists("modules/Connectors/connectors/sources/{$dir}/mapping.php")){ require("modules/Connectors/connectors/sources/{$dir}/mapping.php"); } $this->_mapping = $mapping; } public function saveMappingHook($mapping) { // Most classes don't care that the mapping has changed, but this is here if they do. return; } /** * Load source's vardef file */ public function loadVardefs() { $class = get_class($this); $dir = str_replace('_','/',$class); if(file_exists("custom/modules/Connectors/connectors/sources/{$dir}/vardefs.php")) { require("custom/modules/Connectors/connectors/sources/{$dir}/vardefs.php"); } else if(file_exists("modules/Connectors/connectors/sources/{$dir}/vardefs.php")){ require("modules/Connectors/connectors/sources/{$dir}/vardefs.php"); } $this->_field_defs = !empty($dictionary[$class]['fields']) ? $dictionary[$class]['fields'] : array(); } /** * Given a parameter in a vardef field, return the list of fields that match the param and value * * @param string $param_name * @param string $param_value * @return array */ public function getFieldsWithParams($param_name, $param_value) { if(empty($this->_field_defs)){ $this->loadVardefs(); } $fields_with_param = array(); foreach($this->_field_defs as $key => $def){ if(!empty($def[$param_name]) && ($def[$param_name] == $param_value)){ $fields_with_param[$key] = $def; } } return $fields_with_param; } /** * Save source's config to custom directory */ public function saveConfig() { $config_str = "<?php\n/***CONNECTOR SOURCE***/\n"; // Handle encryption if(!empty($this->_config['encrypt_properties']) && is_array($this->_config['encrypt_properties']) && !empty($this->_config['properties'])){ require_once('include/utils/encryption_utils.php'); foreach($this->_config['encrypt_properties'] as $name) { if(!empty($this->_config['properties'][$name])) { $this->_config['properties'][$name] = blowfishEncode(blowfishGetKey('encrypt_field'),$this->_config['properties'][$name]); } } } foreach($this->_config as $key => $val) { if(!empty($val)){ $config_str .= override_value_to_string_recursive2('config', $key, $val, false); } } $dir = str_replace('_', '/', get_class($this)); if(!file_exists("custom/modules/Connectors/connectors/sources/{$dir}")) { mkdir_recursive("custom/modules/Connectors/connectors/sources/{$dir}"); } file_put_contents("custom/modules/Connectors/connectors/sources/{$dir}/config.php", $config_str); } /** * Initialize config - decrypt encrypted fields */ public function initConfig() { if($this->config_decrypted) return; // Handle decryption require_once('include/utils/encryption_utils.php'); if(!empty($this->_config['encrypt_properties']) && is_array($this->_config['encrypt_properties']) && !empty($this->_config['properties'])){ foreach($this->_config['encrypt_properties'] as $name) { if(!empty($this->_config['properties'][$name])) { $this->_config['properties'][$name] = blowfishDecode(blowfishGetKey('encrypt_field'),$this->_config['properties'][$name]); } } } $this->config_decrypted = true; } /** * Load config.php for this source */ public function loadConfig() { $config = array(); $dir = str_replace('_','/',get_class($this)); if(file_exists("modules/Connectors/connectors/sources/{$dir}/config.php")){ require("modules/Connectors/connectors/sources/{$dir}/config.php"); } if(file_exists("custom/modules/Connectors/connectors/sources/{$dir}/config.php")) { require("custom/modules/Connectors/connectors/sources/{$dir}/config.php"); } $this->_config = $config; //If there are no required config fields specified, we will default them to all be required if(empty($this->_required_config_fields)) { foreach($this->_config['properties'] as $id=>$value) { $this->_required_config_fields[] = $id; } } } // Helper function for the settings panels /** * Filter which modules are allowed to connect * @param array $moduleList * @return array Allowed modules */ public function filterAllowedModules( $moduleList ) { // Most modules can connect to everything, no further filtering necessary return $moduleList; } ////////////// GETTERS and SETTERS //////////////////// public function getMapping() { return $this->_mapping; } public function getOriginalMapping() { $mapping = array(); $dir = str_replace('_','/',get_class($this)); if(file_exists("modules/Connectors/connectors/sources/{$dir}/mapping.php")) { require("modules/Connectors/connectors/sources/{$dir}/mapping.php"); } else if(file_exists("custom/modules/Connectors/connectors/sources/{$dir}/mapping.php")){ require("custom/modules/Connectors/connectors/sources/{$dir}/mapping.php"); } return $mapping; } public function setMapping($mapping) { $this->_mapping = $mapping; } public function getFieldDefs() { return $this->_field_defs; } public function getConfig() { if(!$this->config_decrypted) $this->initConfig(); return $this->_config; } public function setConfig($config) { $this->_config = $config; $this->config_decrypted = true; // Don't decrypt external configs } public function setEAPM(ExternalAPIBase $eapm) { $this->_eapm = $eapm; } public function getEAPM() { return $this->_eapm; } public function setProperties($properties=array()) { if(!empty($this->_config) && isset($this->_config['properties'])) { $this->_config['properties'] = $properties; $this->config_decrypted = true; // Don't decrypt external configs } } public function getProperties() { if(!empty($this->_config) && isset($this->_config['properties'])) { if(!$this->config_decrypted) $this->initConfig(); return $this->_config['properties']; } return array(); } /** * Check if certain property contains non-empty value * @param string $name * @return bool */ public function propertyExists($name) { return !empty($this->_config['properties'][$name]); } public function getProperty($name) { if(!empty($this->_config) && isset($this->_config['properties'][$name])) { // check if we're asking for encrypted property and we didn't decrypt yet if(!$this->config_decrypted && !empty($this->_config['encrypt_properties']) && in_array($name, $this->_config['encrypt_properties']) && !empty($this->_config['properties'][$name])) { $this->initConfig(); } return $this->_config['properties'][$name]; } else { return ''; } } /** * hasTestingEnabled * This method is used to indicate whether or not a data source has testing enabled so that * the administration interface may call the test method on the data source instance * * @return enabled boolean value indicating whether or not testing is enabled */ public function hasTestingEnabled() { return $this->_has_testing_enabled; } /** * test * This method is called from the administration interface to run a test of the service * It is up to subclasses to implement a test and set _has_testing_enabled to true so that * a test button is rendered in the administration interface * * @return result boolean result of the test function */ public function test() { return false; } /** * isEnabledInWizard * This method indicates whether or not the connector should be enabled in the wizard * Connectors that do not support the getList/getItem methods via API calls should * set the protected class variable _enable_in_wizard to false. * * @return $enabled boolean variable indicating whether or not the connector is enabled for the wizard */ public function isEnabledInWizard() { return $this->_enable_in_wizard; } /** * isEnabledInHover * This method indicates whether or not the connector should be enabled for the hover links * Connectors that do not provide a formatter implementation should not * set the protected class variable _enable_in_hover to true. * * @return $enabled boolean variable indicating whether or not the connector is enabled for the hover links * */ public function isEnabledInHover() { return $this->_enable_in_hover; } /** * getRequiredConfigFields * This method returns an Array of the configuration keys that are required for the Connector. * Subclasses should set the class variable _required_config_fields to * return an Array of keys as specified in the Connector's config.php that are required. * * @return $fields Array of Connector config fields that are required */ public function getRequiredConfigFields() { return $this->_required_config_fields; } /** * isRequiredConfigFieldsSet * This method checks the configuration parameters against the required config fields * to see if they are set * * @return $set boolean value indicating whether or not the required config fields are set */ public function isRequiredConfigFieldsSet() { //Check if required fields are set foreach($this->_required_config_fields as $field) { if(empty($this->_config['properties'][$field])) { return false; } } return true; } /** * getRequiredConfigFieldsForButton * This method returns an Array of the configuration keys that are required before the * "Get Data" button will include the Connector. We use it as a subset of the * $this->_required_config_fields Array. * * @return $fields Array of Connector config fields that are required to be set for the "Get Data" button to appear */ public function getRequiredConfigFieldsForButton() { return $this->_required_config_fields_for_button; } /** * isRequiredConfigFieldsForButtonSet * This method checks the configuration parameters against the required config fields * for the "Get Button" to see if they are set * * @return $set boolean value indicating whether or not the required config fields are set */ public function isRequiredConfigFieldsForButtonSet() { //Check if required fields for button are set foreach($this->_required_config_fields_for_button as $field) { if(empty($this->_config['properties'][$field])) { return false; } } return true; } /** * Allow data sources to log information * * @param string $log_data */ protected function log($log_data){ $name = get_class($this); $property_name = $this->getProperty('name'); if(!empty($property_name)){ $name = $property_name; } $GLOBALS['log']->info($name. ': '.$log_data); } /** * getItem * Returns an array containing a key/value pair(s) of a connector record. To be overridden by the implementation * source. * * @param $args Array of arguments to search/filter by * @param $module String optional value of the module that the connector framework is attempting to map to * @return Array of key/value pair(s) of connector record; empty Array if no results are found */ public abstract function getItem($args=array(), $module=null); /** * getList * Returns a nested array containing a key/value pair(s) of a connector record. To be overridden by the * implementation source. * * @param $args Array of arguments to search/filter by * @param $module String optional value of the module that the connector framework is attempting to map to * @return Array of key/value pair(s) of connector record; empty Array if no results are found */ public abstract function getList($args=array(), $module=null); /** * Default destructor * */ public function __destruct(){ // Bug # 47233 - This desctructor was originally removed by bug # 44533. // We have to add this destructor back in // because there are customers who upgrade from 61x to 623 // who have the Jigsaw connector enabled, and the jigsaw connector // makes a call to this destructor. } }
agpl-3.0
ErikPel/notes
l10n/sr.php
453
<?php $TRANSLATIONS = array( "Notes" => "Белешке", "New note" => "Нова белешка", "Note is currently saving. Leaving " => "Белешка се тренутно снима. Излазим", "_%n word_::_%n words_" => array("%n реч","%n речи","%n речи"), "Delete note" => "Обриши белешку" ); $PLURAL_FORMS = "nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);";
agpl-3.0
ecreall/lagendacommun
lac/graphql/schema.py
17979
import datetime from functools import lru_cache import pytz import graphene from graphene import relay from graphene.core.classtypes.scalar import Scalar from graphene.utils import LazyList from graphql.core.language import ast from graphql_relay.connection.arrayconnection import cursor_to_offset import graphene.core.types.custom_scalars from hypatia.interfaces import NBEST, STABLE from elasticsearch.helpers import scan from pyramid.threadlocal import get_current_request from substanced.objectmap import find_objectmap from dace.util import get_obj, find_catalog from lac.views.filter import find_entities from lac.content.interface import ICulturalEvent from lac.utilities.ical_date_utility import ( occurences_start, get_events_ical_calendar, get_schedules_ical_calendar) from lac.views.filter.util import or_op, and_op from lac.views.filter import ( start_end_date_query, zipcode_query, countries_query) from lac.content.resources import es from lac import log from lac.content.interface import ISmartFolder from lac.content.processes import get_states_mapping from lac.content.cultural_event import ( CulturalEvent as CulturalEventOrigin) from lac.layout import deserialize_phone DEFAULT_RADIUS = 15 def get_current_user(args): request = get_current_request() return request.user def current_date(): return datetime.datetime.now(tz=pytz.UTC) def get_current_hour(): now = current_date() return datetime.datetime.combine( now, datetime.time(now.hour, 0, 0, tzinfo=pytz.UTC)).isoformat() @lru_cache(maxsize=64) def get_venues_by_location(location, radius, hour_for_cache): """Return a list of venues oid that are in location ('latitude,longitude') in the given radius. Cache results for one hour. """ lat_lon = location.split(',') body = { "query": { "filtered": { "query": {"match_all": {}}, "filter": { "geo_distance": { "distance": str(radius) + 'km', "location": { "lat": float(lat_lon[0]), "lon": float(lat_lon[1]) } } } } }, "_source": { "include": ["oid"] } } try: result = scan( es, index='lac', doc_type='geo_location', query=body, size=500) return [v['_source']['oid'] for v in result] except Exception as e: log.exception(e) return [] def get_location_query(venues): lac_catalog = find_catalog('lac') object_venue_index = lac_catalog['object_venue'] query = object_venue_index.any(venues) return query def get_cities_query(args): cities = args.get('cities', []) query = None if cities: countries = {} for city in cities: data = city.split('@') countries.setdefault(data[0], []) countries[data[0]].append(data[1]) for country, zipcodes in countries.items(): geographic_filter = { 'geographic_filter': { 'zipcodes_exp': zipcodes, 'country': country } } query = and_op( query, and_op(zipcode_query(None, **geographic_filter), countries_query(None, **geographic_filter))) return query def get_dates_query(args): dates = args.get('dates', []) query = None for date in dates: temporal_filter = { 'temporal_filter': { 'start_end_dates': { 'start_date': date, # will be transformed to 00:00:00 UTC 'end_date': date # will be transformed to 23:59:59 UTC } } } query = or_op( query, start_end_date_query( None, **temporal_filter)) return query def get_dates_range(args): dates = args.get('datesRange') if not dates: return None, None if len(dates) == 2: return dates[0], dates[1] elif len(dates) == 1: return dates[0], None return None, None def get_start_end_dates(args): dates = args.get('dates') if dates: start, end = dates[0], dates[-1] else: start, end = get_dates_range(args) if start: start = datetime.datetime.combine( start, datetime.time(0, 0, 0, tzinfo=pytz.UTC)) if end: end = datetime.datetime.combine( end, datetime.time(23, 59, 59, tzinfo=pytz.UTC)) return start, end def get_dates_range_query(args): dates = args.get('datesRange') if not dates: return None start, end = get_dates_range(args) temporal_filter = { 'temporal_filter': { 'start_end_dates': { 'start_date': start, # will be transformed to 00:00:00 UTC 'end_date': end # will be transformed to 23:59:59 UTC } } } query = start_end_date_query(None, **temporal_filter) return query def get_cultural_events(args, info): start, end = get_start_end_dates(args) request = get_current_request() request.start_end = (start, end) # used in resolve_next_date location = args.get('geo_location', None) venues = [] if location: radius = args.get('radius', DEFAULT_RADIUS) venues = get_venues_by_location(location, radius, get_current_hour()) if not venues: return [] cities_query = get_cities_query(args) dates_query = get_dates_query(args) dates_range_query = get_dates_range_query(args) location_query = get_location_query(venues) query = and_op(location_query, dates_query) query = and_op(query, dates_range_query) query = and_op(query, cities_query) try: after = cursor_to_offset(args.get('after')) first = args.get('first') if after is None: limit = first else: limit = after + 1 + first limit = limit + 1 # retrieve one more so the hasNextPage works except Exception: limit = None # For the scrolling of the results, it's important that the sort is stable. # release_date is set to datetime.datetime.now(tz=pytz.UTC) when the event # is published, so we have microsecond resolution and so have a stable sort # even with not stable sort algorithms like nbest (because it's unlikely # we have several events with the same date). # When we specify limit in the query, the sort algorithm chosen will # most likely be nbest instead of stable timsort (python sorted). # The sort is ascending, meaning we will get new events published during # the scroll, it's ok. # The only issue we can found here is if x events are removed or unpublished # during the scroll, we will skip x new events during the scroll. # A naive solution is to implement our own graphql arrayconnection to slice # from the last known oid + 1, but the last known oid may not be in the # array anymore, so it doesn't work. It's not too bad we skip x events, in # reality it should rarely happen. rs = find_entities( add_query=query, # sort_on="release_date", # limit=limit, sort_on=None, interfaces=[ICulturalEvent], metadata_filter={'states': ['published', 'archived']}, text_filter={'text_to_search': args.get('text', '')}, keywords=args.get('categories', ''), force_publication_date=None # None to avoid intersect with publication_start_date index ) lac_catalog = find_catalog('lac') sort_on = args.get('sort_on', 'release_date') if sort_on == 'start_date': start_date_index = lac_catalog['start_date'] return list(start_date_index.sort( list(rs.ids), limit=limit, from_=start, until=end, sort_type=STABLE)) else: release_date_index = lac_catalog['release_date'] return list(release_date_index.sort( list(rs.ids), limit=limit, sort_type=NBEST)) class Date(Scalar): '''Date in ISO 8601 format''' @staticmethod def serialize(date): return date.isoformat() @staticmethod def parse_literal(node): if isinstance(node, ast.StringValue): return datetime.datetime.strptime( node.value, "%Y-%m-%d").date() @staticmethod def parse_value(value): return datetime.datetime.strptime(value, "%Y-%m-%d").date() class DateTime(Scalar): '''DateTime in ISO 8601 format''' @staticmethod def serialize(dt): return dt.isoformat() @staticmethod def parse_literal(node): if isinstance(node, ast.StringValue): return datetime.datetime.strptime( node.value, "%Y-%m-%dT%H:%M:%S.%fZ").replace(tzinfo=pytz.UTC) @staticmethod def parse_value(value): return datetime.datetime.strptime( value, "%Y-%m-%dT%H:%M:%S.%fZ").replace(tzinfo=pytz.UTC) class Node(object): @classmethod def get_node(cls, id, info): oid = int(id) return cls(_root=get_obj(oid)) @property def id(self): return self.__oid__ def __getattr__(self, name): try: return super(Node, self).__getattr__(name) except Exception: log.exception("Error in node %s id:%s attr:%s", self.__class__.__name__, self.id, name) raise class Artist(relay.Node, Node): title = graphene.String() class Address(relay.Node, Node): title = graphene.String() address = graphene.String() country = graphene.String() city = graphene.String() zipcode = graphene.String() department = graphene.String() addressStr = graphene.String() geoLocation = graphene.String() class Contact(relay.Node, Node): title = graphene.String() email = graphene.String() phone = graphene.String() surtax = graphene.String() fax = graphene.String() website = graphene.String() def __getattr__(self, name): return self.__dict__.get(name, '') def resolve_phone(self, args, info): return deserialize_phone(self.phone) class Venue(relay.Node, Node): title = graphene.String() description = graphene.String() address = relay.ConnectionField(Address) def resolve_address(self, args, info): addresses = getattr(self, 'addresses', []) address = addresses[0] if addresses else {} addressStr = self.address_str(address) title = address.get('title', '') addressDetail = address.get('address', None) country = address.get('country', None) city = address.get('city', None) zipcode = address.get('zipcode', None) department = address.get('department', None) geoLocation = address.get('coordinates', None) return [Address( title=title, address=addressDetail, country=country, city=city, zipcode=zipcode, department=department, addressStr=addressStr, geoLocation=geoLocation)] # class TimeInterval(graphene.ObjectType): # start = graphene.core.types.custom_scalars.DateTime() # end = graphene.core.types.custom_scalars.DateTime() # # # class ScheduleDate(graphene.ObjectType): # date = graphene.core.types.custom_scalars.DateTime() # time_intervals = graphene.List(TimeInterval) def resolve_next_date(self, args, info): """Return first date in the start_end interval. """ request = get_current_request() start, end = getattr(request, 'start_end', (None, None)) dates = occurences_start(self._root, 'dates', from_=start, until=end) return dates[0].date() if dates else None class Schedule(relay.Node, Node): dates_str = graphene.String() calendar = graphene.String() venue = relay.ConnectionField(Venue) price = graphene.String() ticket_type = graphene.String() ticketing_url = graphene.String() next_date = Date() is_expired = graphene.Boolean() def resolve_venue(self, args, info): return [Venue(_root=self.venue)] def resolve_ticketing_url(self, args, info): return self.get_ticketing_url() def resolve_dates_str(self, args, info): return self.dates def resolve_calendar(self, args, info): """cost: 50ms for 50 events """ return get_schedules_ical_calendar( [self], pytz.timezone('Europe/Paris')) def resolve_next_date(self, args, info): """cost: 10ms for 50 events """ return resolve_next_date(self, args, info) def resolve_is_expired(self, args, info): return 'archived' in self.state class CulturalEvent(relay.Node, Node): title = graphene.String() calendar = graphene.String() description = graphene.String() details = graphene.String() artists = relay.ConnectionField(Artist) picture = graphene.String(size=graphene.String()) schedules = relay.ConnectionField(Schedule) state = graphene.String() url = graphene.String() categories = graphene.List(graphene.String()) contacts = relay.ConnectionField(Contact) next_date = Date() def resolve_contacts(self, args, info): contacts = self.get_contacts() return [Contact(**c) for c in contacts] def resolve_state(self, args, info): request = get_current_request() state = get_states_mapping( request.user, self, getattr(self, 'state_or_none', [None])[0]) return request.localizer.translate(state) def resolve_picture(self, args, info): size = args.get('size', 'small') picture = getattr(self, 'picture', None) return None if picture is None else picture.url + size def resolve_calendar(self, args, info): return get_events_ical_calendar( [self], pytz.timezone('Europe/Paris')) def resolve_url(self, args, info): return get_current_request().resource_url(self._root, '@@index') def resolve_categories(self, args, info): return self.sections def resolve_next_date(self, args, info): """cost: 10ms for 50 events """ return resolve_next_date(self, args, info) class User(relay.Node, Node): title = graphene.String() first_name = graphene.String() last_name = graphene.String() email = graphene.String() picture = graphene.String(size=graphene.String()) my_events = relay.ConnectionField(CulturalEvent) def resolve_my_events(self, args, info): return [CulturalEvent(_root=contribution) for contribution in self.all_contributions if isinstance(contribution, CulturalEventOrigin)] class ResolverLazyList(LazyList): def __init__(self, origin, object_type): super(ResolverLazyList, self).__init__(origin, state=None) objectmap = find_objectmap(get_current_request().root) self.resolver = objectmap.object_for self.object_type = object_type def __next__(self): try: if not self._origin_iter: self._origin_iter = self._origin.__iter__() oid = next(self._origin_iter) n = self.object_type(_root=self.resolver(oid)) except StopIteration as e: self._finished = True raise e else: self._state.append(n) return n def __getitem__(self, key): item = self._origin[key] if isinstance(key, slice): return self.__class__(item, object_type=self.object_type) return item class Query(graphene.ObjectType): node = relay.NodeField() cultural_events = relay.ConnectionField( CulturalEvent, cities=graphene.List(graphene.String()), geo_location=graphene.String(), radius=graphene.Int(), categories=graphene.List(graphene.String()), dates=graphene.List(Date()), datesRange=graphene.List(DateTime()), text=graphene.String(), sort_on=graphene.String(), ) current_user = relay.ConnectionField(User) categories = graphene.List(graphene.String()) def resolve_current_user(self, args, info): current = get_current_user(args) if not current: return [] return [User(_root=current)] def resolve_cultural_events(self, args, info): oids = get_cultural_events(args, info) return ResolverLazyList(oids, CulturalEvent) def resolve_categories(self, args, info): root_folders = [folder for folder in find_entities( interfaces=[ISmartFolder], metadata_filter={'states': ['published']}, force_local_control=True) if not folder.parents] sections = set() for folder in root_folders: for filter in folder.filters: #pylint: disable=W0622 if 'cultural_event' in filter[ 'metadata_filter'].get('content_types', ()) and \ 'Rubrique' in filter['metadata_filter']['tree']: keywords = list(filter['metadata_filter']['tree'][ 'Rubrique'].keys()) for keyword in keywords: sections.add(keyword) sections = sorted(sections) return sections schema = graphene.Schema(query=Query) if __name__ == '__main__': import json # import importlib # i = importlib.import_module(schema) # schema_dict = {'data': i.schema.introspect()} schema_dict = {'data': schema.introspect()} with open('schema.json', 'w') as outfile: json.dump(schema_dict, outfile)
agpl-3.0
NicolasEYSSERIC/Silverpeas-Components
kmelia/kmelia-ejb/src/main/java/com/stratelia/webactiv/kmelia/control/ejb/KmeliaBmEJB.java
204957
/** * Copyright (C) 2000 - 2011 Silverpeas * * 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. * * As a special exception to the terms and conditions of version 3.0 of * the GPL, you may redistribute this Program in connection with Free/Libre * Open Source Software ("FLOSS") applications as described in Silverpeas's * FLOSS exception. You should have received a copy of the text describing * the FLOSS exception, and it is also available here: * "http://www.silverpeas.com/legal/licensing" * * 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 com.stratelia.webactiv.kmelia.control.ejb; import static com.silverpeas.util.StringUtil.getBooleanValue; import static com.silverpeas.util.StringUtil.isDefined; import static com.stratelia.webactiv.kmelia.model.KmeliaPublication.aKmeliaPublicationFromCompleteDetail; import static com.stratelia.webactiv.kmelia.model.KmeliaPublication.aKmeliaPublicationFromDetail; import static com.stratelia.webactiv.kmelia.model.KmeliaPublication.aKmeliaPublicationWithPk; import static com.stratelia.webactiv.util.JNDINames.COORDINATESBM_EJBHOME; import static com.stratelia.webactiv.util.JNDINames.NODEBM_EJBHOME; import static com.stratelia.webactiv.util.JNDINames.PDCBM_EJBHOME; import static com.stratelia.webactiv.util.JNDINames.PUBLICATIONBM_EJBHOME; import static com.stratelia.webactiv.util.JNDINames.SILVERPEAS_DATASOURCE; import static com.stratelia.webactiv.util.JNDINames.STATISTICBM_EJBHOME; import static com.stratelia.webactiv.util.JNDINames.VERSIONING_EJBHOME; import static com.stratelia.webactiv.util.exception.SilverpeasRuntimeException.ERROR; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.rmi.RemoteException; import java.sql.Connection; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import javax.activation.FileTypeMap; import javax.ejb.SessionBean; import javax.ejb.SessionContext; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Response.Status; import org.apache.commons.io.FilenameUtils; import org.silverpeas.component.kmelia.InstanceParameters; import com.silverpeas.comment.service.CommentService; import com.silverpeas.comment.service.CommentServiceFactory; import com.silverpeas.form.DataRecord; import com.silverpeas.form.FormException; import com.silverpeas.form.RecordSet; import com.silverpeas.form.importExport.XMLField; import com.silverpeas.formTemplate.dao.ModelDAO; import com.silverpeas.kmelia.notification.KmeliaAttachmentSubscriptionPublicationUserNotification; import com.silverpeas.kmelia.notification.KmeliaDefermentPublicationUserNotification; import com.silverpeas.kmelia.notification.KmeliaDocumentSubscriptionPublicationUserNotification; import com.silverpeas.kmelia.notification.KmeliaModificationPublicationUserNotification; import com.silverpeas.kmelia.notification.KmeliaPendingValidationPublicationUserNotification; import com.silverpeas.kmelia.notification.KmeliaSubscriptionPublicationUserNotification; import com.silverpeas.kmelia.notification.KmeliaSupervisorPublicationUserNotification; import com.silverpeas.kmelia.notification.KmeliaTopicUserNotification; import com.silverpeas.kmelia.notification.KmeliaValidationPublicationUserNotification; import com.silverpeas.notification.builder.helper.UserNotificationHelper; import com.silverpeas.pdc.PdcServiceFactory; import com.silverpeas.pdc.ejb.PdcBm; import com.silverpeas.pdc.ejb.PdcBmHome; import com.silverpeas.pdc.ejb.PdcBmRuntimeException; import com.silverpeas.pdc.model.PdcClassification; import com.silverpeas.pdc.service.PdcClassificationService; import com.silverpeas.pdcSubscription.util.PdcSubscriptionUtil; import com.silverpeas.publicationTemplate.PublicationTemplate; import com.silverpeas.publicationTemplate.PublicationTemplateException; import com.silverpeas.publicationTemplate.PublicationTemplateManager; import com.silverpeas.subscribe.Subscription; import com.silverpeas.subscribe.SubscriptionService; import com.silverpeas.subscribe.SubscriptionServiceFactory; import com.silverpeas.subscribe.service.NodeSubscription; import com.silverpeas.thumbnail.ThumbnailException; import com.silverpeas.thumbnail.control.ThumbnailController; import com.silverpeas.thumbnail.model.ThumbnailDetail; import com.silverpeas.thumbnail.service.ThumbnailServiceImpl; import com.silverpeas.util.ForeignPK; import com.silverpeas.util.StringUtil; import com.stratelia.silverpeas.notificationManager.NotificationMetaData; import com.stratelia.silverpeas.notificationManager.constant.NotifAction; import com.stratelia.silverpeas.pdc.model.ClassifyPosition; import com.stratelia.silverpeas.silverpeasinitialize.CallBackManager; import com.stratelia.silverpeas.silvertrace.SilverTrace; import com.stratelia.silverpeas.versioning.ejb.VersioningBm; import com.stratelia.silverpeas.versioning.ejb.VersioningBmHome; import com.stratelia.silverpeas.versioning.model.Document; import com.stratelia.silverpeas.versioning.model.DocumentPK; import com.stratelia.silverpeas.versioning.model.DocumentVersion; import com.stratelia.silverpeas.versioning.model.Worker; import com.stratelia.silverpeas.versioning.util.VersioningUtil; import com.stratelia.silverpeas.wysiwyg.control.WysiwygController; import com.stratelia.webactiv.SilverpeasRole; import com.stratelia.webactiv.beans.admin.AdminController; import com.stratelia.webactiv.beans.admin.ObjectType; import com.stratelia.webactiv.beans.admin.OrganizationController; import com.stratelia.webactiv.calendar.backbone.TodoBackboneAccess; import com.stratelia.webactiv.calendar.backbone.TodoDetail; import com.stratelia.webactiv.calendar.model.Attendee; import com.stratelia.webactiv.kmelia.KmeliaContentManager; import com.stratelia.webactiv.kmelia.KmeliaSecurity; import com.stratelia.webactiv.kmelia.PublicationImport; import com.stratelia.webactiv.kmelia.model.KmaxRuntimeException; import com.stratelia.webactiv.kmelia.model.KmeliaPublication; import com.stratelia.webactiv.kmelia.model.KmeliaRuntimeException; import com.stratelia.webactiv.kmelia.model.TopicComparator; import com.stratelia.webactiv.kmelia.model.TopicDetail; import com.stratelia.webactiv.util.DBUtil; import com.stratelia.webactiv.util.DateUtil; import com.stratelia.webactiv.util.EJBUtilitaire; import com.stratelia.webactiv.util.FileRepositoryManager; import com.stratelia.webactiv.util.ResourceLocator; import com.stratelia.webactiv.util.WAPrimaryKey; import com.stratelia.webactiv.util.attachment.control.AttachmentController; import com.stratelia.webactiv.util.attachment.ejb.AttachmentException; import com.stratelia.webactiv.util.attachment.ejb.AttachmentPK; import com.stratelia.webactiv.util.attachment.model.AttachmentDetail; import com.stratelia.webactiv.util.coordinates.control.CoordinatesBm; import com.stratelia.webactiv.util.coordinates.control.CoordinatesBmHome; import com.stratelia.webactiv.util.coordinates.model.Coordinate; import com.stratelia.webactiv.util.coordinates.model.CoordinatePK; import com.stratelia.webactiv.util.coordinates.model.CoordinatePoint; import org.silverpeas.search.indexEngine.model.IndexManager; import com.stratelia.webactiv.util.node.control.NodeBm; import com.stratelia.webactiv.util.node.control.NodeBmHome; import com.stratelia.webactiv.util.node.model.NodeDetail; import com.stratelia.webactiv.util.node.model.NodePK; import com.stratelia.webactiv.util.publication.control.PublicationBm; import com.stratelia.webactiv.util.publication.control.PublicationBmHome; import com.stratelia.webactiv.util.publication.info.model.InfoDetail; import com.stratelia.webactiv.util.publication.info.model.InfoImageDetail; import com.stratelia.webactiv.util.publication.info.model.ModelDetail; import com.stratelia.webactiv.util.publication.info.model.ModelPK; import com.stratelia.webactiv.util.publication.model.Alias; import com.stratelia.webactiv.util.publication.model.CompletePublication; import com.stratelia.webactiv.util.publication.model.NodeTree; import com.stratelia.webactiv.util.publication.model.PublicationDetail; import com.stratelia.webactiv.util.publication.model.PublicationPK; import com.stratelia.webactiv.util.publication.model.ValidationStep; import com.stratelia.webactiv.util.statistic.control.StatisticBm; import com.stratelia.webactiv.util.statistic.control.StatisticBmHome; /** * This is the KMelia EJB-tier controller of the MVC. It is implemented as a session EJB. It * controls all the activities that happen in a client session. It also provides mechanisms to * access other session EJBs. * @author Nicolas Eysseric */ public class KmeliaBmEJB implements KmeliaBmBusinessSkeleton, SessionBean { private static final long serialVersionUID = 1L; private CommentService commentService = null; public KmeliaBmEJB() { } public void ejbCreate() { SilverTrace.info("kmelia", "KmeliaBmEJB.ejbCreate()", "root.MSG_GEN_ENTER_METHOD"); } @Override public void ejbRemove() { SilverTrace.info("kmelia", "KmeliaBmEJB.ejbRemove()", "root.MSG_GEN_ENTER_METHOD"); } @Override public void ejbActivate() { SilverTrace.info("kmelia", "KmeliaBmEJB.ejbActivate()", "root.MSG_GEN_ENTER_METHOD"); } @Override public void ejbPassivate() { SilverTrace.info("kmelia", "KmeliaBmEJB.ejbPassivate()", "root.MSG_GEN_ENTER_METHOD"); } private OrganizationController getOrganizationController() { // must return a new instance each time // This is to resolve Serializable problems OrganizationController orga = new OrganizationController(); return orga; } @Override public void setSessionContext(SessionContext sc) { } private int getNbPublicationsOnRoot(String componentId) { String parameterValue = getOrganizationController().getComponentParameterValue(componentId, "nbPubliOnRoot"); SilverTrace.info("kmelia", "KmeliaBmEJB.getNbPublicationsOnRoot()", "root.MSG_GEN_PARAM_VALUE", "parameterValue=" + parameterValue); if (isDefined(parameterValue)) { return Integer.parseInt(parameterValue); } else { if (KmeliaHelper.isToolbox(componentId)) { return 0; } // lecture du properties ResourceLocator settings = getSettings(); return Integer.parseInt(settings.getString("HomeNbPublications")); } } private ResourceLocator getSettings() { return new ResourceLocator("org.silverpeas.kmelia.settings.kmeliaSettings", "fr"); } private boolean isDraftModeUsed(String componentId) { return "yes".equals(getOrganizationController().getComponentParameterValue(componentId, "draft")); } @Override public NodeBm getNodeBm() { NodeBm nodeBm = null; try { NodeBmHome nodeBmHome = EJBUtilitaire.getEJBObjectRef(NODEBM_EJBHOME, NodeBmHome.class); nodeBm = nodeBmHome.create(); } catch (Exception e) { throw new KmeliaRuntimeException("KmeliaBmEJB.getNodeBm()", ERROR, "kmelia.EX_IMPOSSIBLE_DE_FABRIQUER_NODEBM_HOME", e); } return nodeBm; } @Override public PublicationBm getPublicationBm() { PublicationBm publicationBm = null; try { PublicationBmHome publicationBmHome = EJBUtilitaire.getEJBObjectRef(PUBLICATIONBM_EJBHOME, PublicationBmHome.class); publicationBm = publicationBmHome.create(); } catch (Exception e) { throw new KmeliaRuntimeException("KmeliaBmEJB.getPublicationBm()", ERROR, "kmelia.EX_IMPOSSIBLE_DE_FABRIQUER_PUBLICATIONBM_HOME", e); } return publicationBm; } public SubscriptionService getSubscribeBm() { return SubscriptionServiceFactory.getFactory().getSubscribeService(); } public StatisticBm getStatisticBm() { StatisticBm statisticBm = null; try { StatisticBmHome statisticBmHome = EJBUtilitaire.getEJBObjectRef(STATISTICBM_EJBHOME, StatisticBmHome.class); statisticBm = statisticBmHome.create(); } catch (Exception e) { throw new KmeliaRuntimeException("KmeliaBmEJB.getStatisticBm()", ERROR, "kmelia.EX_IMPOSSIBLE_DE_FABRIQUER_STATISTICBM_HOME", e); } return statisticBm; } public VersioningBm getVersioningBm() { VersioningBm versioningBm = null; try { VersioningBmHome versioningBmHome = EJBUtilitaire.getEJBObjectRef(VERSIONING_EJBHOME, VersioningBmHome.class); versioningBm = versioningBmHome.create(); } catch (Exception e) { throw new KmeliaRuntimeException("KmeliaBmEJB.getVersioningBm()", ERROR, "kmelia.EX_IMPOSSIBLE_DE_FABRIQUER_VERSIONING_EJBHOME", e); } return versioningBm; } @Override public PdcBm getPdcBm() { PdcBm pdcBm = null; try { PdcBmHome pdcBmHome = EJBUtilitaire.getEJBObjectRef(PDCBM_EJBHOME, PdcBmHome.class); pdcBm = pdcBmHome.create(); } catch (Exception e) { throw new PdcBmRuntimeException("KmeliaBmEJB.getPdcBm", ERROR, "root.EX_CANT_GET_REMOTE_OBJECT", e); } return pdcBm; } /** * "Kmax" method * @return */ public CoordinatesBm getCoordinatesBm() { CoordinatesBm currentCoordinatesBm = null; try { CoordinatesBmHome coordinatesBmHome = EJBUtilitaire.getEJBObjectRef(COORDINATESBM_EJBHOME, CoordinatesBmHome.class); currentCoordinatesBm = coordinatesBmHome.create(); } catch (Exception e) { throw new KmeliaRuntimeException("KmeliaBmEJB.getCoordinatesBm()", ERROR, "kmax.EX_IMPOSSIBLE_DE_FABRIQUER_COORDINATESBM_HOME", e); } return currentCoordinatesBm; } /** * Return a the detail of a topic * @param pk the id of the topic * @param userId * @param isTreeStructureUsed * @param userProfile * @param isRightsOnTopicsUsed * @return */ @Override public TopicDetail goTo(NodePK pk, String userId, boolean isTreeStructureUsed, String userProfile, boolean isRightsOnTopicsUsed) { SilverTrace.info("kmelia", "KmeliaBmEJB.goTo()", "root.MSG_GEN_ENTER_METHOD"); Collection<NodeDetail> newPath = new ArrayList<NodeDetail>(); NodeDetail nodeDetail = null; NodeBm nodeBm = getNodeBm(); // get the basic information (Header) of this topic SilverTrace.info("kmelia", "KmeliaBmEJB.goTo()", "root.MSG_GEN_PARAM_VALUE", "nodeBm.getDetail(pk) BEGIN"); try { nodeDetail = nodeBm.getDetail(pk); if (isRightsOnTopicsUsed) { OrganizationController orga = getOrganizationController(); if (nodeDetail.haveRights() && !orga.isObjectAvailable(nodeDetail.getRightsDependsOn(), ObjectType.NODE, pk.getInstanceId(), userId)) { nodeDetail.setUserRole("noRights"); } List<NodeDetail> availableChildren = getAllowedSubfolders(nodeDetail, userId); nodeDetail.setChildrenDetails(availableChildren); } } catch (Exception e) { throw new KmeliaRuntimeException("KmeliaBmEJB.goTo()", ERROR, "kmelia.EX_IMPOSSIBLE_DACCEDER_AU_THEME", e); } SilverTrace.info("kmelia", "KmeliaBmEJB.goTo()", "root.MSG_GEN_PARAM_VALUE", "nodeBm.getDetail(pk) END"); // get publications List<KmeliaPublication> pubDetails = getPublicationsOfFolder(pk, userProfile, userId, isTreeStructureUsed, isRightsOnTopicsUsed); // get the path to this topic SilverTrace.info("kmelia", "KmeliaBmEJB.goTo()", "root.MSG_GEN_PARAM_VALUE", "GetPath BEGIN"); if (pk.isRoot()) { newPath.add(nodeDetail); } else { newPath = getPathFromAToZ(nodeDetail); } SilverTrace.info("kmelia", "KmeliaBmEJB.goTo()", "root.MSG_GEN_PARAM_VALUE", "GetPath END"); SilverTrace.info("kmelia", "KmeliaBmEJB.goTo()", "root.MSG_GEN_EXIT_METHOD"); // set the currentTopic and return it return new TopicDetail(newPath, nodeDetail, pubDetails); } public List<KmeliaPublication> getPublicationsOfFolder(NodePK pk, String userProfile, String userId, boolean isTreeStructureUsed, boolean isRightsOnTopicsUsed) { Collection<PublicationDetail> pubDetails = null; PublicationBm pubBm = getPublicationBm(); // get the publications associated to this topic if (pk.isTrash()) { // Topic = Basket pubDetails = getPublicationsInBasket(pk, userProfile, userId); } else if (pk.isRoot()) { try { int nbPublisOnRoot = getNbPublicationsOnRoot(pk.getInstanceId()); if (nbPublisOnRoot == 0 || !isTreeStructureUsed || KmeliaHelper.isToolbox(pk.getInstanceId())) { pubDetails = pubBm.getDetailsByFatherPK(pk, "P.pubUpdateDate desc", false); } else { return getLatestPublications(pk.getInstanceId(), nbPublisOnRoot, isRightsOnTopicsUsed, userId); } } catch (Exception e) { throw new KmeliaRuntimeException("KmeliaBmEJB.getPublicationsOfFolder()", ERROR, "kmelia.EX_IMPOSSIBLE_DAVOIR_LES_DERNIERES_PUBLICATIONS", e); } } else { SilverTrace.info("kmelia", "KmeliaBmEJB.getPublicationsOfFolder()", "root.MSG_GEN_PARAM_VALUE", "pubBm.getDetailsByFatherPK(pk) BEGIN"); try { // get the publication details linked to this topic pubDetails = pubBm.getDetailsByFatherPK(pk, "P.pubUpdateDate DESC, P.pubId DESC", false); } catch (Exception e) { throw new KmeliaRuntimeException("KmeliaBmEJB.getPublicationsOfFolder()", ERROR, "kmelia.EX_IMPOSSIBLE_DAVOIR_LA_LISTE_DES_PUBLICATIONS", e); } SilverTrace.info("kmelia", "KmeliaBmEJB.getPublicationsOfFolder()", "root.MSG_GEN_PARAM_VALUE", "pubBm.getDetailsByFatherPK(pk) END"); } return pubDetails2userPubs(pubDetails); } public List<KmeliaPublication> getLatestPublications(String instanceId, int nbPublisOnRoot, boolean isRightsOnTopicsUsed, String userId) throws RemoteException { PublicationPK pubPK = new PublicationPK("unknown", instanceId); Collection<PublicationDetail> pubDetails = getPublicationBm().getDetailsByBeginDateDescAndStatusAndNotLinkedToFatherId(pubPK, PublicationDetail.VALID, nbPublisOnRoot, NodePK.BIN_NODE_ID); if (isRightsOnTopicsUsed) {// The list of publications must be filtered List<PublicationDetail> filteredList = new ArrayList<PublicationDetail>(); KmeliaSecurity security = new KmeliaSecurity(); for (PublicationDetail pubDetail : pubDetails) { if (security .isObjectAvailable(instanceId, userId, pubDetail.getPK().getId(), "Publication")) { filteredList.add(pubDetail); } } pubDetails.clear(); pubDetails.addAll(filteredList); } return pubDetails2userPubs(pubDetails); } public List<NodeDetail> getAllowedSubfolders(NodeDetail folder, String userId) throws RemoteException { OrganizationController orga = getOrganizationController(); NodePK pk = folder.getNodePK(); List<NodeDetail> children = (List<NodeDetail>) folder.getChildrenDetails(); List<NodeDetail> availableChildren = new ArrayList<NodeDetail>(); for (NodeDetail child : children) { String childId = child.getNodePK().getId(); if (child.getNodePK().isTrash() || childId.equals("2") || !child.haveRights()) { availableChildren.add(child); } else { int rightsDependsOn = child.getRightsDependsOn(); boolean nodeAvailable = orga.isObjectAvailable(rightsDependsOn, ObjectType.NODE, pk. getInstanceId(), userId); if (nodeAvailable) { availableChildren.add(child); } else { // check if at least one descendant is available Iterator<NodeDetail> descendants = getNodeBm().getDescendantDetails(child).iterator(); NodeDetail descendant = null; boolean childAllowed = false; while (!childAllowed && descendants.hasNext()) { descendant = descendants.next(); if (descendant.getRightsDependsOn() == rightsDependsOn) { // same rights of father (which is not available) so it is not available too } else { // different rights of father check if it is available if (orga.isObjectAvailable(descendant.getRightsDependsOn(), ObjectType.NODE, pk. getInstanceId(), userId)) { childAllowed = true; if (!availableChildren.contains(child)) { availableChildren.add(child); } } } } } } } return availableChildren; } private Collection<NodeDetail> getPathFromAToZ(NodeDetail nd) { Collection<NodeDetail> newPath = new ArrayList<NodeDetail>(); try { List<NodeDetail> pathInReverse = (List<NodeDetail>) getNodeBm().getPath(nd.getNodePK()); // reverse the path from root to leaf for (int i = pathInReverse.size() - 1; i >= 0; i--) { newPath.add(pathInReverse.get(i)); } } catch (Exception e) { throw new KmeliaRuntimeException("KmeliaBmEJB.getPathFromAToZ()", ERROR, "kmelia.EX_IMPOSSIBLE_DAVOIR_LE_CHEMIN_COURANT", e); } return newPath; } /** * Add a subtopic to a topic - If a subtopic of same name already exists a NodePK with id=-1 is * returned else the new topic NodePK * @param fatherPK the topic Id of the future father * @param subTopic the NodeDetail of the new sub topic * @return If a subtopic of same name already exists a NodePK with id=-1 is returned else the new * topic NodePK * @see com.stratelia.webactiv.util.node.model.NodeDetail * @see com.stratelia.webactiv.util.node.model.NodePK */ @Override public NodePK addToTopic(NodePK fatherPK, NodeDetail subTopic) { SilverTrace.info("kmelia", "KmeliaBmEJB.addToTopic()", "root.MSG_GEN_ENTER_METHOD"); NodePK theNodePK = null; try { NodeDetail fatherDetail = getNodeBm().getHeader(fatherPK); theNodePK = getNodeBm().createNode(subTopic, fatherDetail); } catch (Exception e) { throw new KmeliaRuntimeException("KmeliaBmEJB.addToTopic()", ERROR, "kmelia.EX_IMPOSSIBLE_DE_CREER_LE_THEME", e); } SilverTrace.info("kmelia", "KmeliaBmEJB.addToTopic()", "root.MSG_GEN_EXIT_METHOD"); return theNodePK; } /** * Add a subtopic to currentTopic and alert users - If a subtopic of same name already exists a * NodePK with id=-1 is returned else the new topic NodePK * @param fatherPK * @param subTopic the NodeDetail of the new sub topic * @param alertType Alert all users, only publishers or nobody of the topic creation alertType = * "All"|"Publisher"|"None" * @return If a subtopic of same name already exists a NodePK with id=-1 is returned else the new * topic NodePK */ @Override public NodePK addSubTopic(NodePK fatherPK, NodeDetail subTopic, String alertType) { SilverTrace.info("kmelia", "KmeliaBmEJB.addSubTopic()", "root.MSG_GEN_ENTER_METHOD"); // Construction de la date de création (date courante) String creationDate = DateUtil.today2SQLDate(); subTopic.setCreationDate(creationDate); // Web visibility parameter. The topic is by default invisible. subTopic.setStatus("Invisible"); // add new topic to current topic NodePK pk = addToTopic(fatherPK, subTopic); SilverTrace.info("kmelia", "KmeliaBmEJB.addSubTopic()", "root.MSG_GEN_PARAM_VALUE", "pk = " + pk.toString()); // Creation alert if (!"-1".equals(pk.getId())) { topicCreationAlert(pk, fatherPK, alertType); } SilverTrace.info("kmelia", "KmeliaBmEJB.addSubTopic()", "root.MSG_GEN_EXIT_METHOD"); return pk; } private String displayPath(Collection<NodeDetail> path, int beforeAfter, String language) { StringBuilder pathString = new StringBuilder(); boolean first = true; List<NodeDetail> pathAsList = new ArrayList<NodeDetail>(path); Collections.reverse(pathAsList); // reverse path from root to node for (NodeDetail nodeInPath : pathAsList) { if (!first) { pathString.append(" > "); } first = false; pathString.append(nodeInPath.getName(language)); } return pathString.toString(); } /** * Alert all users, only publishers or nobody of the topic creation or update * @param pk the NodePK of the new sub topic * @param alertType alertType = "All"|"Publisher"|"None" * @see com.stratelia.webactiv.util.node.model.NodePK * @since 1.0 */ private void topicCreationAlert(final NodePK nodePK, final NodePK fatherPK, final String alertType) { SilverTrace.info("kmelia", "KmeliaBmEJB.topicCreationAlert()", "root.MSG_GEN_ENTER_METHOD"); UserNotificationHelper.buildAndSend(new KmeliaTopicUserNotification(nodePK, fatherPK, alertType)); SilverTrace.info("kmelia", "KmeliaBmEJB.topicCreationAlert()", "root.MSG_GEN_PARAM_VALUE", "AlertType alert = " + alertType); SilverTrace.info("kmelia", "KmeliaBmEJB.topicCreationAlert()", "root.MSG_GEN_EXIT_METHOD"); } /** * Update a subtopic to currentTopic and alert users - If a subtopic of same name already exists a * NodePK with id=-1 is returned else the new topic NodePK * @param topic the NodeDetail of the updated sub topic * @param alertType Alert all users, only publishers or nobody of the topic creation alertType = * "All"|"Publisher"|"None" * @return If a subtopic of same name already exists a NodePK with id=-1 is returned else the new * topic NodePK * @see com.stratelia.webactiv.util.node.model.NodeDetail * @see com.stratelia.webactiv.util.node.model.NodePK * @since 1.0 */ @Override public NodePK updateTopic(NodeDetail topic, String alertType) { try { // Order of the node must be unchanged NodeDetail node = getNodeBm().getHeader(topic.getNodePK()); int order = node.getOrder(); topic.setOrder(order); getNodeBm().setDetail(topic); } catch (Exception e) { throw new KmeliaRuntimeException("KmeliaBmEJB.updateTopic()", ERROR, "kmelia.EX_IMPOSSIBLE_DE_MODIFIER_THEME", e); } // Update Alert topicCreationAlert(topic.getNodePK(), null, alertType); return topic.getNodePK(); } @Override public NodeDetail getSubTopicDetail(NodePK pk) { NodeDetail subTopic = null; // get the basic information (Header) of this topic try { subTopic = getNodeBm().getDetail(pk); } catch (Exception e) { throw new KmeliaRuntimeException("KmeliaBmEJB.getSubTopicDetail()", ERROR, "kmelia.EX_IMPOSSIBLE_DACCEDER_AU_THEME", e); } return subTopic; } /** * Delete a topic and all descendants. Delete all links between descendants and publications. This * publications will be visible in the Declassified zone. Delete All subscriptions and favorites * on this topics and all descendants * @param pkToDelete the id of the topic to delete * @since 1.0 */ @Override public void deleteTopic(NodePK pkToDelete) { SilverTrace.info("kmelia", "KmeliaBmEJB.deleteTopic()", "root.MSG_GEN_ENTER_METHOD"); PublicationBm pubBm = getPublicationBm(); NodeBm nodeBm = getNodeBm(); try { // get all nodes which will be deleted Collection<NodePK> nodesToDelete = nodeBm.getDescendantPKs(pkToDelete); nodesToDelete.add(pkToDelete); SilverTrace.info("kmelia", "KmeliaBmEJB.deleteTopic()", "root.MSG_GEN_PARAM_VALUE", "nodesToDelete = " + nodesToDelete.toString()); Iterator<PublicationPK> itPub = null; Collection<PublicationPK> pubsToCheck = null; // contains all PubPKs concerned by // the delete NodePK oneNodeToDelete = null; // current node to delete Collection<NodePK> pubFathers = null; // contains all fatherPKs to a given // publication PublicationPK onePubToCheck = null; // current pub to check Iterator<NodePK> itNode = nodesToDelete.iterator(); List<Alias> aliases = new ArrayList<Alias>(); while (itNode.hasNext()) { oneNodeToDelete = itNode.next(); // get pubs linked to current node (includes alias) pubsToCheck = pubBm.getPubPKsInFatherPK(oneNodeToDelete); itPub = pubsToCheck.iterator(); // check each pub contained in current node while (itPub.hasNext()) { onePubToCheck = itPub.next(); if (onePubToCheck.getInstanceId().equals(oneNodeToDelete.getInstanceId())) { // get fathers of the pub pubFathers = pubBm.getAllFatherPK(onePubToCheck); if (pubFathers.size() >= 2) { // the pub have got many fathers // delete only the link between pub and current node pubBm.removeFather(onePubToCheck, oneNodeToDelete); SilverTrace.info("kmelia", "KmeliaBmEJB.deleteTopic()", "root.MSG_GEN_PARAM_VALUE", "RemoveFather(pubId, fatherId) with pubId = " + onePubToCheck.getId() + ", fatherId = " + oneNodeToDelete); } else { sendPublicationToBasket(onePubToCheck); SilverTrace.info("kmelia", "KmeliaBmEJB.deleteTopic()", "root.MSG_GEN_PARAM_VALUE", "RemoveAllFather(pubId) with pubId = " + onePubToCheck.getId()); } } else { // remove alias aliases.clear(); aliases.add(new Alias(oneNodeToDelete.getId(), oneNodeToDelete.getInstanceId())); pubBm.removeAlias(onePubToCheck, aliases); } } } // Delete all subscriptions on this topic and on its descendants removeSubscriptionsByTopic(pkToDelete); // Delete the topic nodeBm.removeNode(pkToDelete); } catch (Exception e) { throw new KmeliaRuntimeException("KmeliaBmEJB.deleteTopic()", ERROR, "kmelia.EX_IMPOSSIBLE_DE_SUPPRIMER_THEME", e); } SilverTrace.info("kmelia", "KmeliaBmEJB.deleteTopic()", "root.MSG_GEN_EXIT_METHOD"); } @Override public void changeSubTopicsOrder(String way, NodePK subTopicPK, NodePK fatherPK) { SilverTrace.info("kmelia", "KmeliaBmEJB.changeSubTopicsOrder()", "root.MSG_GEN_ENTER_METHOD", "way = " + way + ", subTopicPK = " + subTopicPK.toString()); List<NodeDetail> subTopics = null; try { subTopics = (List<NodeDetail>) getNodeBm().getChildrenDetails(fatherPK); } catch (Exception e) { throw new KmeliaRuntimeException("KmeliaBmEJB.changeSubTopicsOrder()", ERROR, "kmelia.EX_IMPOSSIBLE_DE_LISTER_THEMES", e); } if (subTopics != null && !subTopics.isEmpty()) { int indexOfTopic = 0; if (fatherPK.isRoot() && !KmeliaHelper.isToolbox(subTopicPK.getInstanceId())) { // search the place of the basket indexOfTopic = getIndexOfNode("1", subTopics); // remove the node subTopics.remove(indexOfTopic); // search the place of the declassified indexOfTopic = getIndexOfNode("2", subTopics); // remove the node subTopics.remove(indexOfTopic); } // search the place of the topic we want to move indexOfTopic = getIndexOfNode(subTopicPK.getId(), subTopics); // get the node to move NodeDetail node2move = subTopics.get(indexOfTopic); // remove the node to move subTopics.remove(indexOfTopic); if (way.equals("up")) { subTopics.add(indexOfTopic - 1, node2move); } else { subTopics.add(indexOfTopic + 1, node2move); } // for each node, change the order and store it for (int i = 0; i < subTopics.size(); i++) { NodeDetail nodeDetail = subTopics.get(i); SilverTrace.info("kmelia", "KmeliaBmEJB.changeSubTopicsOrder()", "root.MSG_GEN_PARAM_VALUE", "updating Node : nodeId = " + nodeDetail.getNodePK().getId() + ", order = " + i); try { nodeDetail.setOrder(i); getNodeBm().setDetail(nodeDetail); } catch (Exception e) { throw new KmeliaRuntimeException("KmeliaBmEJB.changeSubTopicsOrder()", ERROR, "kmelia.EX_IMPOSSIBLE_DE_MODIFIER_THEME", e); } } } } private int getIndexOfNode(String nodeId, List<NodeDetail> nodes) { SilverTrace.debug("kmelia", "KmeliaBmEJB.getIndexOfNode()", "root.MSG_GEN_ENTER_METHOD", "nodeId = " + nodeId); int index = 0; if (nodes != null) { for (NodeDetail node : nodes) { if (nodeId.equals(node.getNodePK().getId())) { SilverTrace.debug("kmelia", "KmeliaBmEJB.getIndexOfNode()", "root.MSG_GEN_EXIT_METHOD", "index = " + index); return index; } index++; } } SilverTrace.debug("kmelia", "KmeliaBmEJB.getIndexOfNode()", "root.MSG_GEN_EXIT_METHOD", "index = " + index); return index; } @Override public void changeTopicStatus(String newStatus, NodePK nodePK, boolean recursiveChanges) { SilverTrace.info("kmelia", "KmeliaBmEJB.changeTopicStatus()", "root.MSG_GEN_ENTER_METHOD", "newStatus = " + newStatus + ", nodePK = " + nodePK.toString() + ", recursiveChanges = " + recursiveChanges); try { if (!recursiveChanges) { NodeDetail nodeDetail = getNodeBm().getHeader(nodePK); changeTopicStatus(newStatus, nodeDetail); } else { List<NodeDetail> subTree = getNodeBm().getSubTree(nodePK); for (NodeDetail aSubTree : subTree) { NodeDetail nodeDetail = aSubTree; changeTopicStatus(newStatus, nodeDetail); } } } catch (Exception e) { throw new KmeliaRuntimeException("KmeliaBmEJB.changeTopicStatus()", ERROR, "kmelia.EX_IMPOSSIBLE_DE_MODIFIER_THEME", e); } } @Override public void sortSubTopics(NodePK fatherPK) { sortSubTopics(fatherPK, false, null); } @Override public void sortSubTopics(NodePK fatherPK, boolean recursive, String[] criteria) { SilverTrace.info("kmelia", "KmeliaBmEJB.sortSubTopics()", "root.MSG_GEN_ENTER_METHOD", "fatherPK = " + fatherPK.toString()); List<NodeDetail> subTopics = null; try { subTopics = (List<NodeDetail>) getNodeBm().getChildrenDetails(fatherPK); } catch (Exception e) { throw new KmeliaRuntimeException("KmeliaBmEJB.sortSubTopics()", ERROR, "kmelia.EX_IMPOSSIBLE_DE_LISTER_THEMES", e); } if (subTopics != null && subTopics.size() > 0) { Collections.sort(subTopics, new TopicComparator(criteria)); // for each node, change the order and store it for (int i = 0; i < subTopics.size(); i++) { NodeDetail nodeDetail = subTopics.get(i); SilverTrace.info("kmelia", "KmeliaBmEJB.sortSubTopics()", "root.MSG_GEN_PARAM_VALUE", "updating Node : nodeId = " + nodeDetail.getNodePK().getId() + ", order = " + i); try { nodeDetail.setOrder(i); getNodeBm().setDetail(nodeDetail); } catch (Exception e) { throw new KmeliaRuntimeException("KmeliaBmEJB.sortSubTopics()", ERROR, "kmelia.EX_IMPOSSIBLE_DE_MODIFIER_THEME", e); } if (recursive) { sortSubTopics(nodeDetail.getNodePK(), true, criteria); } } } } private void changeTopicStatus(String newStatus, NodeDetail topic) { SilverTrace.info("kmelia", "KmeliaBmEJB.changeTopicStatus()", "root.MSG_GEN_ENTER_METHOD", "newStatus = " + newStatus + ", nodePK = " + topic.getNodePK().toString()); try { topic.setStatus(newStatus); getNodeBm().setDetail(topic); } catch (Exception e) { throw new KmeliaRuntimeException("KmeliaBmEJB.changeTopicStatus()", ERROR, "kmelia.EX_IMPOSSIBLE_DE_MODIFIER_THEME", e); } } @Override public List<NodeDetail> getTreeview(NodePK nodePK, String profile, boolean coWritingEnable, boolean draftVisibleWithCoWriting, String userId, boolean displayNb, boolean isRightsOnTopicsUsed) { String instanceId = nodePK.getInstanceId(); try { List<NodeDetail> tree = getNodeBm().getSubTree(nodePK); List<NodeDetail> allowedTree = new ArrayList<NodeDetail>(); OrganizationController orga = getOrganizationController(); if (isRightsOnTopicsUsed) { // filter allowed nodes for (NodeDetail node2Check : tree) { if (!node2Check.haveRights()) { allowedTree.add(node2Check); if (node2Check.getNodePK().isRoot()) {// case of root. Check if publications on root are // allowed int nbPublisOnRoot = Integer.parseInt(orga.getComponentParameterValue(nodePK. getInstanceId(), "nbPubliOnRoot")); if (nbPublisOnRoot != 0) { node2Check.setUserRole("user"); } } } else { int rightsDependsOn = node2Check.getRightsDependsOn(); String[] profiles = orga.getUserProfiles(userId, instanceId, rightsDependsOn, ObjectType.NODE); if (profiles != null && profiles.length > 0) { node2Check.setUserRole(KmeliaHelper.getProfile(profiles)); allowedTree.add(node2Check); } else { // check if at least one descendant is available Iterator<NodeDetail> descendants = getNodeBm().getDescendantDetails(node2Check). iterator(); NodeDetail descendant = null; boolean node2CheckAllowed = false; while (!node2CheckAllowed && descendants.hasNext()) { descendant = descendants.next(); if (descendant.getRightsDependsOn() != rightsDependsOn) { // different rights of father check if it is available profiles = orga.getUserProfiles(userId, instanceId, descendant.getRightsDependsOn(), ObjectType.NODE); if (profiles != null && profiles.length > 0) { node2Check.setUserRole(KmeliaHelper.getProfile(profiles)); allowedTree.add(node2Check); node2CheckAllowed = true; } } } } } } } else { if (tree != null && !tree.isEmpty()) { // case of root. Check if publications on root are allowed String sNB = orga.getComponentParameterValue(nodePK.getInstanceId(), "nbPubliOnRoot"); if (!isDefined(sNB)) { sNB = "0"; } int nbPublisOnRoot = Integer.parseInt(sNB); if (nbPublisOnRoot != 0) { NodeDetail root = tree.get(0); root.setUserRole("user"); } } allowedTree.addAll(tree); } if (displayNb) { boolean checkVisibility = false; StringBuilder statusSubQuery = new StringBuilder(); if (profile.equals("user")) { checkVisibility = true; statusSubQuery.append(" AND sb_publication_publi.pubStatus = 'Valid' "); } else if (profile.equals("writer")) { statusSubQuery.append(" AND ("); if (coWritingEnable && draftVisibleWithCoWriting) { statusSubQuery.append("sb_publication_publi.pubStatus = 'Valid' OR ").append( "sb_publication_publi.pubStatus = 'Draft' OR ").append( "sb_publication_publi.pubStatus = 'Unvalidate' "); } else { checkVisibility = true; statusSubQuery.append("sb_publication_publi.pubStatus = 'Valid' OR ").append( "(sb_publication_publi.pubStatus = 'Draft' AND ").append( "sb_publication_publi.pubUpdaterId = '"). append(userId).append( "') OR (sb_publication_publi.pubStatus = 'Unvalidate' AND "). append("sb_publication_publi.pubUpdaterId = '").append(userId).append("') "); } statusSubQuery.append("OR (sb_publication_publi.pubStatus = 'ToValidate' ").append( "AND sb_publication_publi.pubUpdaterId = '").append(userId).append("') "); statusSubQuery.append("OR sb_publication_publi.pubUpdaterId = '").append(userId).append( "')"); } else { statusSubQuery.append(" AND ("); if (coWritingEnable && draftVisibleWithCoWriting) { statusSubQuery.append( "sb_publication_publi.pubStatus IN ('Valid','ToValidate','Draft') "); } else { if (profile.equals("publisher")) { checkVisibility = true; } statusSubQuery.append("sb_publication_publi.pubStatus IN ('Valid','ToValidate') OR "). append( "(sb_publication_publi.pubStatus = 'Draft' AND sb_publication_publi.pubUpdaterId = '"). append(userId).append("') "); } statusSubQuery.append("OR sb_publication_publi.pubUpdaterId = '").append(userId).append( "')"); } NodeTree root = getPublicationBm().getDistributionTree(nodePK.getInstanceId(), statusSubQuery.toString(), checkVisibility); // set right number of publications in basket NodePK trashPk = new NodePK(NodePK.BIN_NODE_ID, nodePK.getInstanceId()); int nbPubsInTrash = getPublicationsInBasket(trashPk, profile, userId).size(); for (NodeTree node : root.getChildren()) { if (node.getKey().isTrash()) { node.setNbPublications(nbPubsInTrash); } } Map<NodePK, NodeDetail> allowedNodes = new HashMap<NodePK, NodeDetail>(allowedTree.size()); for (NodeDetail allowedNode : allowedTree) { allowedNodes.put(allowedNode.getNodePK(), allowedNode); } countPublisInNodes(allowedNodes, root); } return allowedTree; } catch (RemoteException e) { throw new KmeliaRuntimeException("KmeliaBmEJB.getTreeview()", ERROR, "kmelia.EX_IMPOSSIBLE_DAVOIR_LA_LISTE_DES_PUBLICATIONS", e); } } private Collection<PublicationDetail> getPublicationsInBasket(NodePK pk, String userProfile, String userId) { String currentUserId = userId; SilverTrace.info("kmelia", "KmeliaBmEJB.getPublicationsInBasket()", "root.MSG_GEN_ENTER_METHOD", "pk = " + pk.toString() + ", userProfile = " + userProfile + ", userId = " + currentUserId); try { // Give the publications associated to basket topic and visibility period expired if (SilverpeasRole.admin.isInRole(userProfile)) {// Admin can see all Publis in the basket. currentUserId = null; } Collection<PublicationDetail> pubDetails = getPublicationBm().getDetailsByFatherPK(pk, null, false, currentUserId); SilverTrace.info("kmelia", "KmeliaBmEJB.getPublicationsInBasket()", "root.MSG_GEN_EXIT_METHOD", "nbPublis = " + pubDetails.size()); return pubDetails; } catch (Exception e) { throw new KmeliaRuntimeException("KmeliaBmEJB.getPublicationsInBasket()", ERROR, "kmelia.EX_IMPOSSIBLE_DAVOIR_LE_CONTENU_DE_LA_CORBEILLE", e); } } private void countPublisInNodes(Map<NodePK, NodeDetail> allowedNodes, NodeTree tree) { for (NodeDetail node : allowedNodes.values()) { NodeTree nodeTree = findNode(node, tree); if (nodeTree != null) { int nbPublis = countNbPublis(nodeTree); SilverTrace.debug("kmelia", "KmeliaBmEJB.countPublisInNodes", "root.MSG_GEN_PARAM_VALUE", nbPublis + " pubs in node " + node.getNodePK().getId()); node.setNbObjects(nbPublis); } } } private NodeTree findNode(NodeDetail node, NodeTree tree) { SilverTrace.debug("kmelia", "KmeliaBmEJB.findNode", "root.MSG_GEN_ENTER_METHOD", "looking for node " + node.getNodePK().getId()); String path = node.getFullPath(); if (path.length() > 1) { path = path.substring(1, path.length()-1); // remove starting and ending slash SilverTrace.debug("kmelia", "KmeliaBmEJB.findNode", "root.MSG_GEN_PARAM_VALUE", " path = " + path); ArrayList<String> pathItems = new ArrayList<String>(Arrays.asList(path.split("/"))); pathItems.remove(0); // remove root NodeTree current = tree; for (String pathItem : pathItems) { if (current != null) { current = findNodeTree(pathItem, current.getChildren()); } } SilverTrace.debug("kmelia", "KmeliaBmEJB.findNode", "root.MSG_GEN_EXIT_METHOD", "node " + current.getKey().getId()+" found"); return current; } SilverTrace.debug("kmelia", "KmeliaBmEJB.findNode", "root.MSG_GEN_EXIT_METHOD", "node " + node.getNodePK().getId()+" not found"); return null; } private NodeTree findNodeTree(String nodeId, List<NodeTree> children) { for (NodeTree node : children) { if (node.getKey().getId().equals(nodeId)) { return node; } } return null; } private int countNbPublis(NodeTree tree) { SilverTrace.debug("kmelia", "KmeliaBmEJB.countNbPublis", "root.MSG_GEN_ENTER_METHOD", "id = " + tree.getKey().getId()); int nb = tree.getNbPublications(); // add nb of each descendant for (NodeTree node : tree.getChildren()) { nb += countNbPublis(node); } return nb; } /** * Subscriptions - get the subscription list of the current user * @param userId * @param componentId * @return a Path Collection - it's a Collection of NodeDetail collection * @see com.stratelia.webactiv.util.node.model.NodeDetail * @since 1.0 */ @Override public Collection<Collection<NodeDetail>> getSubscriptionList(String userId, String componentId) { SilverTrace.info("kmelia", "KmeliaBmEJB.getSubscriptionList()", "root.MSG_GEN_ENTER_METHOD"); try { Collection<? extends Subscription> list = getSubscribeBm().getUserSubscriptionsByComponent( userId, componentId); Collection<Collection<NodeDetail>> detailedList = new ArrayList<Collection<NodeDetail>>(); // For each favorite, get the path from root to favorite for (Subscription subscription : list) { Collection<NodeDetail> path = getNodeBm().getPath((NodePK) subscription.getTopic()); detailedList.add(path); } SilverTrace.info("kmelia", "KmeliaBmEJB.getSubscriptionList()", "root.MSG_GEN_EXIT_METHOD"); return detailedList; } catch (Exception e) { throw new KmeliaRuntimeException("KmeliaBmEJB.getSubscriptionList()", ERROR, "kmelia.EX_IMPOSSIBLE_DOBTENIR_LES_ABONNEMENTS", e); } } /** * Subscriptions - remove a subscription to the subscription list of the current user * @param topicPK the subscribe topic Id to remove * @param userId * @since 1.0 */ @Override public void removeSubscriptionToCurrentUser(NodePK topicPK, String userId) { SilverTrace.info("kmelia", "KmeliaBmEJB.removeSubscriptionToCurrentUser()", "root.MSG_GEN_ENTER_METHOD"); try { getSubscribeBm().unsubscribe(new NodeSubscription(userId, topicPK)); } catch (Exception e) { throw new KmeliaRuntimeException("KmeliaBmEJB.removeSubscriptionToCurrentUser()", ERROR, "kmelia.EX_IMPOSSIBLE_DE_SUPPRIMER_ABONNEMENT", e); } SilverTrace.info("kmelia", "KmeliaBmEJB.removeSubscriptionToCurrentUser()", "root.MSG_GEN_EXIT_METHOD"); } /** * Subscriptions - remove all subscriptions from topic * @param topicPK the subscription topic Id to remove * @since 1.0 */ private void removeSubscriptionsByTopic(NodePK topicPK) { SilverTrace.info("kmelia", "KmeliaBmEJB.removeSubscriptionsByTopic()", "root.MSG_GEN_ENTER_METHOD"); NodeDetail nodeDetail = null; try { nodeDetail = getNodeBm().getDetail(topicPK); } catch (Exception e) { throw new KmeliaRuntimeException("KmeliaBmEJB.removeSubscriptionsByTopic()", ERROR, "kmelia.EX_IMPOSSIBLE_DE_SUPPRIMER_LES_ABONNEMENTS", e); } try { getSubscribeBm().unsubscribeByPath(topicPK, nodeDetail.getPath()); } catch (Exception e) { throw new KmeliaRuntimeException("KmeliaBmEJB.removeSubscriptionsByTopic()", ERROR, "kmelia.EX_IMPOSSIBLE_DE_SUPPRIMER_LES_ABONNEMENTS", e); } SilverTrace.info("kmelia", "KmeliaBmEJB.removeSubscriptionsByTopic()", "root.MSG_GEN_EXIT_METHOD"); } /** * Subscriptions - add a subscription * @param topicPK the subscription topic Id to add * @param userId the subscription userId * @since 1.0 */ @Override public void addSubscription(NodePK topicPK, String userId) { SilverTrace.info("kmelia", "KmeliaBmEJB.addSubscription()", "root.MSG_GEN_ENTER_METHOD"); if (!checkSubscription(topicPK, userId)) { return; } getSubscribeBm().subscribe(new NodeSubscription(userId, topicPK)); SilverTrace.info("kmelia", "KmeliaBmEJB.addSubscription()", "root.MSG_GEN_EXIT_METHOD"); } /** * * @param topicPK * @param userId * @return true if this topic does not exists in user subscriptions and can be added to them. */ @Override public boolean checkSubscription(NodePK topicPK, String userId) { try { Collection<? extends Subscription> subscriptions = getSubscribeBm(). getUserSubscriptionsByComponent(userId, topicPK.getInstanceId()); for (Subscription subscription : subscriptions) { if (topicPK.getId().equals(subscription.getTopic().getId())) { return false; } } return true; } catch (Exception e) { throw new KmeliaRuntimeException("KmeliaBmEJB.checkSubscription()", ERROR, "kmelia.EX_IMPOSSIBLE_DOBTENIR_LES_ABONNEMENTS", e); } } /**************************************************************************************/ /* Interface - Gestion des publications */ /**************************************************************************************/ private List<KmeliaPublication> pubDetails2userPubs(Collection<PublicationDetail> pubDetails) { List<KmeliaPublication> publications = new ArrayList<KmeliaPublication>(); int i = -1; for (PublicationDetail publicationDetail : pubDetails) { publications.add(aKmeliaPublicationFromDetail(publicationDetail, i++)); } return publications; } /** * Return the detail of a publication (only the Header) * @param pubPK the id of the publication * @return a PublicationDetail * @see com.stratelia.webactiv.util.publication.model.PublicationDetail * @since 1.0 */ @Override public PublicationDetail getPublicationDetail(PublicationPK pubPK) { SilverTrace.info("kmelia", "KmeliaBmEJB.getPublicationDetail()", "root.MSG_GEN_ENTER_METHOD"); try { SilverTrace.info("kmelia", "KmeliaBmEJB.getPublicationDetail()", "root.MSG_GEN_EXIT_METHOD"); return getPublicationBm().getDetail(pubPK); } catch (Exception e) { throw new KmeliaRuntimeException("KmeliaBmEJB.getPublicationDetail()", ERROR, "kmelia.EX_IMPOSSIBLE_DOBTENIR_LA_PUBLICATION", e); } } /** * Return list of all path to this publication - it's a Collection of NodeDetail collection * @param pubPK the id of the publication * @return a Collection of NodeDetail collection * @see com.stratelia.webactiv.util.node.model.NodeDetail * @since 1.0 */ @Override public Collection<Collection<NodeDetail>> getPathList(PublicationPK pubPK) { SilverTrace.info("kmelia", "KmeliaBmEJB.getPathList()", "root.MSG_GEN_ENTER_METHOD"); Collection<NodePK> fatherPKs = null; try { // get all nodePK whick contains this publication fatherPKs = getPublicationBm().getAllFatherPK(pubPK); } catch (Exception e) { throw new KmeliaRuntimeException("KmeliaBmEJB.getPathList()", ERROR, "kmelia.EX_IMPOSSIBLE_DOBTENIR_LES_EMPLACEMENTS_DE_LA_PUBLICATION", e); } try { List<Collection<NodeDetail>> pathList = new ArrayList<Collection<NodeDetail>>(); if (fatherPKs != null) { // For each topic, get the path to it for (NodePK pk : fatherPKs) { Collection<NodeDetail> path = getNodeBm().getAnotherPath(pk); // add this path pathList.add(path); } } SilverTrace.info("kmelia", "KmeliaBmEJB.getPathList()", "root.MSG_GEN_EXIT_METHOD"); return pathList; } catch (Exception e) { throw new KmeliaRuntimeException("KmeliaBmEJB.getPathList()", ERROR, "kmelia.EX_IMPOSSIBLE_DOBTENIR_LES_EMPLACEMENTS_DE_LA_PUBLICATION", e); } } /** * Create a new Publication (only the header - parameters) to the current Topic * @param pubDetail a PublicationDetail * @return the id of the new publication * @see com.stratelia.webactiv.util.publication.model.PublicationDetail * @since 1.0 */ @Override public String createPublicationIntoTopic(PublicationDetail pubDetail, NodePK fatherPK) { PdcClassificationService classifier = PdcServiceFactory.getFactory(). getPdcClassificationService(); PdcClassification predefinedClassification = classifier.findAPreDefinedClassification(fatherPK.getId(), pubDetail.getInstanceId()); return createPublicationIntoTopic(pubDetail, fatherPK, predefinedClassification); } @Override public String createPublicationIntoTopic(PublicationDetail pubDetail, NodePK fatherPK, PdcClassification classification) { SilverTrace.info("kmelia", "KmeliaBmEJB.createPublicationIntoTopic()", "root.MSG_GEN_ENTER_METHOD"); String pubId = null; try { pubId = createPublicationIntoTopicWithoutNotifications(pubDetail, fatherPK, classification); // creates todos for publishers createTodosForPublication(pubDetail, true); // alert supervisors sendAlertToSupervisors(fatherPK, pubDetail); // alert subscribers sendSubscriptionsNotification(pubDetail, false); } catch (Exception e) { throw new KmeliaRuntimeException( "KmeliaBmEJB.createPublicationIntoTopic()", ERROR, "kmelia.EX_IMPOSSIBLE_DE_CREER_LA_PUBLICATION", e); } SilverTrace.info("kmelia", "KmeliaBmEJB.createPublicationIntoTopic()", "root.MSG_GEN_EXIT_METHOD"); return pubId; } public String createPublicationIntoTopicWithoutNotifications(PublicationDetail pubDetail, NodePK fatherPK, PdcClassification classification) { SilverTrace.info("kmelia", "KmeliaBmEJB.createPublicationIntoTopic()", "root.MSG_GEN_ENTER_METHOD"); PublicationPK pubPK = null; try { pubDetail = changePublicationStatusOnCreation(pubDetail, fatherPK); // create the publication pubPK = getPublicationBm().createPublication(pubDetail); pubDetail.getPK().setId(pubPK.getId()); // register the new publication as a new content to content manager createSilverContent(pubDetail, pubDetail.getCreatorId()); // add this publication to the current topic addPublicationToTopicWithoutNotifications(pubPK, fatherPK, true); // classify the publication on the PdC if its classification is defined if (!classification.isEmpty()) { PdcClassificationService service = PdcServiceFactory.getFactory(). getPdcClassificationService(); classification.ofContent(pubPK.getId()); service.classifyContent(pubDetail, classification); } } catch (Exception e) { throw new KmeliaRuntimeException("KmeliaBmEJB.createPublicationIntoTopic()", ERROR, "kmelia.EX_IMPOSSIBLE_DE_CREER_LA_PUBLICATION", e); } SilverTrace.info("kmelia", "KmeliaBmEJB.createPublicationIntoTopic()", "root.MSG_GEN_EXIT_METHOD"); return pubPK.getId(); } private String getProfile(String userId, NodePK nodePK) throws RemoteException { String profile = null; OrganizationController orgCtrl = getOrganizationController(); if (StringUtil.getBooleanValue(orgCtrl.getComponentParameterValue(nodePK.getInstanceId(), "rightsOnTopics"))) { NodeDetail topic = getNodeBm().getHeader(nodePK); if (topic.haveRights()) { profile = KmeliaHelper.getProfile(orgCtrl.getUserProfiles(userId, nodePK.getInstanceId(), topic.getRightsDependsOn(), ObjectType.NODE)); } else { profile = KmeliaHelper.getProfile(orgCtrl.getUserProfiles(userId, nodePK.getInstanceId())); } } else { profile = KmeliaHelper.getProfile(orgCtrl.getUserProfiles(userId, nodePK.getInstanceId())); } return profile; } private String getProfileOnPublication(String userId, PublicationPK pubPK) { List<NodePK> fathers = (List<NodePK>) getPublicationFathers(pubPK); NodePK nodePK = new NodePK("unknown", pubPK.getInstanceId()); if (fathers != null && !fathers.isEmpty()) { nodePK = fathers.get(0); } String profile = null; try { profile = getProfile(userId, nodePK); } catch (RemoteException e) { SilverTrace.error("kmelia", "KmeliaBmEJB.externalElementsOfPublicationHaveChanged", "kmelia.ERROR_ON_GETTING_PROFILE", "userId = " + userId + ", node = " + nodePK.toString(), e); } return profile; } private PublicationDetail changePublicationStatusOnCreation( PublicationDetail pubDetail, NodePK nodePK) throws RemoteException { SilverTrace.info("kmelia", "KmeliaBmEJB.changePublicationStatusOnCreation()", "root.MSG_GEN_ENTER_METHOD", "status = " + pubDetail.getStatus()); String status = pubDetail.getStatus(); if (!isDefined(status)) { status = PublicationDetail.TO_VALIDATE; boolean draftModeUsed = isDraftModeUsed(pubDetail.getPK().getInstanceId()); if (draftModeUsed) { status = PublicationDetail.DRAFT; } else { String profile = getProfile(pubDetail.getCreatorId(), nodePK); if (SilverpeasRole.publisher.isInRole(profile) || SilverpeasRole.admin.isInRole(profile)) { status = PublicationDetail.VALID; } } } pubDetail.setStatus(status); KmeliaHelper.checkIndex(pubDetail); SilverTrace.info("kmelia", "KmeliaBmEJB.changePublicationStatusOnCreation()", "root.MSG_GEN_EXIT_METHOD", "status = " + pubDetail.getStatus() + ", indexOperation = " + pubDetail.getIndexOperation()); return pubDetail; } private boolean changePublicationStatusOnMove(PublicationDetail pub, NodePK to) throws RemoteException { SilverTrace.info("kmelia", "KmeliaBmEJB.changePublicationStatusOnMove()", "root.MSG_GEN_ENTER_METHOD", "status = " + pub.getStatus()); String oldStatus = pub.getStatus(); String status = pub.getStatus(); if (!status.equals(PublicationDetail.DRAFT)) { status = PublicationDetail.TO_VALIDATE; String profile = getProfile(pub.getUpdaterId(), to); if (SilverpeasRole.publisher.isInRole(profile) || SilverpeasRole.admin.isInRole(profile)) { status = PublicationDetail.VALID; } } pub.setStatus(status); KmeliaHelper.checkIndex(pub); SilverTrace.info("kmelia", "KmeliaBmEJB.changePublicationStatusOnMove()", "root.MSG_GEN_EXIT_METHOD", "status = " + pub.getStatus() + ", indexOperation = " + pub.getIndexOperation()); return !oldStatus.equals(status); } /** * determine new publication's status according to actual status and current user's profile * @param pubDetail * @return true if status has changed, false otherwise */ private boolean changePublicationStatusOnUpdate(PublicationDetail pubDetail) throws RemoteException { String oldStatus = pubDetail.getStatus(); String newStatus = oldStatus; List<NodePK> fathers = (List<NodePK>) getPublicationFathers(pubDetail.getPK()); if (pubDetail.isStatusMustBeChecked()) { if (!pubDetail.isDraft() && !pubDetail.isClone()) { newStatus = PublicationDetail.TO_VALIDATE; NodePK nodePK = new NodePK("unknown", pubDetail.getPK().getInstanceId()); if (fathers != null && fathers.size() > 0) { nodePK = fathers.get(0); } String profile = getProfile(pubDetail.getUpdaterId(), nodePK); if ("supervisor".equals(profile) || SilverpeasRole.publisher.isInRole(profile) || SilverpeasRole.admin.isInRole(profile)) { newStatus = PublicationDetail.VALID; } pubDetail.setStatus(newStatus); } } KmeliaHelper.checkIndex(pubDetail); if (fathers == null || fathers.isEmpty() || (fathers.size() == 1 && fathers.get(0).isTrash())) { // la publication est dans la corbeille pubDetail.setIndexOperation(IndexManager.NONE); } return !oldStatus.equalsIgnoreCase(newStatus); } /** * Update a publication (only the header - parameters) * @param pubDetail a PublicationDetail * @see com.stratelia.webactiv.util.publication.model.PublicationDetail * @since 1.0 */ @Override public void updatePublication(PublicationDetail pubDetail) { updatePublication(pubDetail, KmeliaHelper.PUBLICATION_HEADER, false); } @Override public void updatePublication(PublicationDetail pubDetail, boolean forceUpdateDate) { updatePublication(pubDetail, KmeliaHelper.PUBLICATION_HEADER, forceUpdateDate); } private void updatePublication(PublicationDetail pubDetail, int updateScope, boolean forceUpdateDate) { SilverTrace.info("kmelia", "KmeliaBmEJB.updatePublication()", "root.MSG_GEN_ENTER_METHOD", "updateScope = " + updateScope); try { // if pubDetail is a clone boolean isClone = isDefined(pubDetail.getCloneId()) && !"-1".equals(pubDetail.getCloneId()) && !isDefined(pubDetail.getCloneStatus()); SilverTrace.info("kmelia", "KmeliaBmEJB.updatePublication()", "root.MSG_GEN_PARAM_VALUE", "This publication is clone ? " + isClone); if (isClone) { // update only updateDate getPublicationBm().setDetail(pubDetail, forceUpdateDate); } else { PublicationDetail old = getPublicationDetail(pubDetail.getPK()); boolean statusChanged = changePublicationStatusOnUpdate(pubDetail); getPublicationBm().setDetail(pubDetail, forceUpdateDate); if (!isPublicationInBasket(pubDetail.getPK())) { if (statusChanged) { // creates todos for publishers this.createTodosForPublication(pubDetail, false); } updateSilverContentVisibility(pubDetail); // la publication a été modifié par un superviseur // le créateur de la publi doit être averti String profile = KmeliaHelper.getProfile(getOrganizationController().getUserProfiles(pubDetail. getUpdaterId(), pubDetail.getPK().getInstanceId())); if ("supervisor".equals(profile)) { sendModificationAlert(updateScope, pubDetail.getPK()); } boolean visibilityPeriodUpdated = isVisibilityPeriodUpdated(pubDetail, old); if (statusChanged || visibilityPeriodUpdated) { if (KmeliaHelper.isIndexable(pubDetail)) { indexExternalElementsOfPublication(pubDetail); } else { unIndexExternalElementsOfPublication(pubDetail.getPK()); } } } } // notification pour modification sendSubscriptionsNotification(pubDetail, true); boolean isNewsManage = getBooleanValue(getOrganizationController().getComponentParameterValue( pubDetail.getPK().getInstanceId(), "isNewsManage")); if (isNewsManage) { // mécanisme de callback CallBackManager callBackManager = CallBackManager.get(); callBackManager.invoke(CallBackManager.ACTION_HEADER_PUBLICATION_UPDATE, Integer.parseInt(pubDetail.getId()), pubDetail.getInstanceId(), pubDetail); } } catch (Exception e) { throw new KmeliaRuntimeException("KmeliaBmEJB.updatePublication()", ERROR, "kmelia.EX_IMPOSSIBLE_DE_MODIFIER_LA_PUBLICATION", e); } SilverTrace.info("kmelia", "KmeliaBmEJB.updatePublication()", "root.MSG_GEN_EXIT_METHOD"); } private boolean isVisibilityPeriodUpdated(PublicationDetail pubDetail, PublicationDetail old) { boolean beginVisibilityPeriodUpdated = ((pubDetail.getBeginDate() != null && old.getBeginDate() == null) || (pubDetail. getBeginDate() == null && old.getBeginDate() != null) || (pubDetail.getBeginDate() != null && old.getBeginDate() != null && !pubDetail.getBeginDate().equals(old. getBeginDate()))); boolean endVisibilityPeriodUpdated = ((pubDetail.getEndDate() != null && old.getEndDate() == null) || (pubDetail.getEndDate() == null && old.getEndDate() != null) || (pubDetail.getEndDate() != null && old. getEndDate() != null && !pubDetail.getEndDate().equals(old.getEndDate()))); return beginVisibilityPeriodUpdated || endVisibilityPeriodUpdated; } public void movePublicationInSameApplication(PublicationDetail pub, NodePK to, String userId) throws RemoteException { // update parent getPublicationBm().removeAllFather(pub.getPK()); getPublicationBm().addFather(pub.getPK(), to); processPublicationAfterMove(pub, to, userId); } public void movePublicationInAnotherApplication(PublicationDetail pub, NodePK to, String userId) throws RemoteException { getPublicationBm().movePublication(pub.getPK(), to, false); // Change instanceId and unindex header+content processPublicationAfterMove(pub, to, userId); } private void processPublicationAfterMove(PublicationDetail pub, NodePK to, String userId) throws RemoteException { // update last modifier pub.setUpdaterId(userId); // status must be checked according to topic rights and last modifier (current user) boolean statusChanged = changePublicationStatusOnMove(pub, to); // update publication getPublicationBm().setDetail(pub, statusChanged); // check visibility on taxonomy updateSilverContentVisibility(pub); if (statusChanged) { // creates todos for publishers createTodosForPublication(pub, false); // index or unindex external elements if (KmeliaHelper.isIndexable(pub)) { indexExternalElementsOfPublication(pub); } else { unIndexExternalElementsOfPublication(pub.getPK()); } } // send notifications like a creation sendSubscriptionsNotification(pub, false); } /******************************************************************************************/ /* KMELIA - Copier/coller des documents versionnés */ /******************************************************************************************/ public void pasteDocuments(PublicationPK pubPKFrom, String pubId) throws Exception { SilverTrace.info("kmelia", "KmeliaBmEJB.pasteDocuments()", "root.MSG_GEN_ENTER_METHOD", "pubPKFrom = " + pubPKFrom.toString() + ", pubId = " + pubId); // paste versioning documents attached to publication List<Document> documents = getVersioningBm().getDocuments(new ForeignPK(pubPKFrom)); SilverTrace.info("kmelia", "KmeliaBmEJB.pasteDocuments()", "root.MSG_GEN_PARAM_VALUE", documents.size() + " to paste"); VersioningUtil versioningUtil = new VersioningUtil(); String pathFrom = null; // where the original files are String pathTo = null; // where the copied files will be ForeignPK pubPK = new ForeignPK(pubId, pubPKFrom.getInstanceId()); // change the list of workers List<Worker> workers = new ArrayList<Worker>(); if (!documents.isEmpty()) { List<String> workingProfiles = new ArrayList<String>(); workingProfiles.add(SilverpeasRole.writer.toString()); workingProfiles.add(SilverpeasRole.publisher.toString()); workingProfiles.add(SilverpeasRole.admin.toString()); String[] userIds = getOrganizationController().getUsersIdsByRoleNames( pubPKFrom.getInstanceId(), workingProfiles); for (int u = 0; u < userIds.length; u++) { String userId = userIds[u]; Worker worker = new Worker(Integer.parseInt(userId), -1, u, false, true, pubPKFrom.getInstanceId(), "U", false, true, 0); workers.add(worker); } } // paste each document for (Document document : documents) { SilverTrace.info("kmelia", "KmeliaBmEJB.pasteDocuments()", "root.MSG_GEN_PARAM_VALUE", "document name = " + document.getName()); // retrieve all versions of the document List<DocumentVersion> versions = getVersioningBm().getDocumentVersions(document.getPk()); // retrieve the initial version of the document DocumentVersion version = versions.get(0); if (pathFrom == null) { pathFrom = versioningUtil.createPath(document.getPk().getSpaceId(), document.getPk().getInstanceId(), null); } // change some data to paste document.setPk(new DocumentPK(-1, pubPKFrom)); document.setForeignKey(pubPK); document.setStatus(Document.STATUS_CHECKINED); document.setLastCheckOutDate(new Date()); document.setWorkList((ArrayList<Worker>) workers); if (pathTo == null) { pathTo = versioningUtil.createPath("useless", pubPKFrom.getInstanceId(), null); } String newVersionFile = null; if (version != null) { // paste file on fileserver newVersionFile = pasteVersionFile(version, pathFrom, pathTo); version.setPhysicalName(newVersionFile); } // create the document with its first version DocumentPK documentPK = getVersioningBm().createDocument(document, version); document.setPk(documentPK); for (DocumentVersion currentVersion : versions) { currentVersion.setDocumentPK(documentPK); SilverTrace.info("kmelia", "KmeliaBmEJB.pasteDocuments()", "root.MSG_GEN_PARAM_VALUE", "paste version = " + currentVersion.getLogicalName()); // paste file on fileserver newVersionFile = pasteVersionFile(currentVersion, pathFrom, pathTo); currentVersion.setPhysicalName(newVersionFile); // paste data getVersioningBm().addVersion(currentVersion); } } } private String pasteVersionFile(DocumentVersion version, String from, String to) { String fileNameFrom = version.getPhysicalName(); SilverTrace.info("kmelia", "KmeliaBmEJB.pasteVersionFile()", "root.MSG_GEN_ENTER_METHOD", "version = " + fileNameFrom); if (!"dummy".equals(fileNameFrom)) { // we have to rename pasted file (in case the copy/paste append in // the same instance) String type = FilenameUtils.getExtension(fileNameFrom); String fileNameTo = String.valueOf(System.currentTimeMillis()) + '.' + type; try { // paste file associated to the first version FileRepositoryManager.copyFile(from + fileNameFrom, to + fileNameTo); } catch (Exception e) { throw new KmeliaRuntimeException("KmeliaBmEJB.pasteVersionFile()", ERROR, "root.EX_FILE_NOT_FOUND", e); } return fileNameTo; } return fileNameFrom; } private void updatePublication(PublicationPK pubPK, int updateScope) { PublicationDetail pubDetail = getPublicationDetail(pubPK); updatePublication(pubDetail, updateScope, false); } @Override public void externalElementsOfPublicationHaveChanged(PublicationPK pubPK, String userId, int action) { PublicationDetail pubDetail = getPublicationDetail(pubPK); if (isDefined(userId)) { pubDetail.setUpdaterId(userId); } // check if related publication is managed by kmelia // test due to really hazardous abusive notifications if (pubDetail.getPK().getInstanceId().startsWith("kmelia") || pubDetail.getPK().getInstanceId().startsWith("toolbox") || pubDetail.getPK().getInstanceId().startsWith("kmax")) { // update publication header to store last modifier and update date if (!isDefined(userId)) { updatePublication(pubDetail, KmeliaHelper.PUBLICATION_CONTENT, false); } else { // check if user have sufficient rights to update a publication String profile = getProfileOnPublication(userId, pubDetail.getPK()); if ("supervisor".equals(profile) || SilverpeasRole.publisher.isInRole(profile) || SilverpeasRole.admin.isInRole(profile) || SilverpeasRole.writer.isInRole(profile)) { updatePublication(pubDetail, KmeliaHelper.PUBLICATION_CONTENT, false); } else { SilverTrace.warn("kmelia", "KmeliaBmEJB.externalElementsOfPublicationHaveChanged", "kmelia.PROBLEM_DETECTED", "user " + userId + " is not allowed to update publication " + pubDetail.getPK().toString()); } } // index all attached files to taking into account visibility period indexExternalElementsOfPublication(pubDetail); } } /** * Delete a publication If this publication is in the basket or in the DZ, it's deleted from the * database Else it only send to the basket * @param pubPK the id of the publication to delete * @see com.stratelia.webactiv.kmelia.model.TopicDetail */ @Override public void deletePublication(PublicationPK pubPK) { // if the publication is in the basket or in the DZ // this publication is deleted from the database SilverTrace.info("kmelia", "KmeliaBmEJB.deletePublication()", "root.MSG_GEN_ENTER_METHOD"); try { // delete all reading controls associated to this publication deleteAllReadingControlsByPublication(pubPK); // delete all links getPublicationBm().removeAllFather(pubPK); // delete the publication getPublicationBm().removePublication(pubPK); // delete reference to contentManager deleteSilverContent(pubPK); removeExternalElementsOfPublications(pubPK); } catch (Exception e) { throw new KmeliaRuntimeException("KmeliaBmEJB.deletePublication()", ERROR, "kmelia.EX_IMPOSSIBLE_DE_SUPPRIMER_LA_PUBLICATION", e); } SilverTrace.info("kmelia", "KmeliaBmEJB.deletePublication()", "root.MSG_GEN_EXIT_METHOD"); } /** * Send the publication in the basket topic * @param pubPK the id of the publication * @param kmaxMode * @see com.stratelia.webactiv.kmelia.model.TopicDetail * @since 1.0 */ @Override public void sendPublicationToBasket(PublicationPK pubPK, boolean kmaxMode) { SilverTrace.info("kmelia", "KmeliaBmEJB.sendPublicationToBasket()", "root.MSG_GEN_ENTER_METHOD"); try { // remove coordinates for Kmax if (kmaxMode) { CoordinatePK coordinatePK = new CoordinatePK("unknown", pubPK.getSpaceId(), pubPK. getComponentName()); PublicationBm pubBm = getPublicationBm(); Collection<NodePK> fatherPKs = pubBm.getAllFatherPK(pubPK); // delete publication coordinates Iterator<NodePK> it = fatherPKs.iterator(); List<String> coordinates = new ArrayList<String>(); SilverTrace.info("kmelia", "KmeliaBmEJB.sendPublicationToBasket()", "root.MSG_GEN_PARAM_VALUE", "fatherPKs" + fatherPKs); while (it.hasNext()) { String coordinateId = (it.next()).getId(); coordinates.add(coordinateId); } if (coordinates.size() > 0) { getCoordinatesBm().deleteCoordinates(coordinatePK, (ArrayList<String>) coordinates); } } // remove all links between this publication and topics getPublicationBm().removeAllFather(pubPK); // add link between this publication and the basket topic getPublicationBm().addFather(pubPK, new NodePK("1", pubPK)); getPublicationBm().deleteIndex(pubPK); // remove all the todos attached to the publication removeAllTodosForPublication(pubPK); // publication is no more accessible updateSilverContentVisibility(pubPK, false); unIndexExternalElementsOfPublication(pubPK); boolean isNewsManage = getBooleanValue(getOrganizationController().getComponentParameterValue( pubPK.getInstanceId(), "isNewsManage")); if (isNewsManage) { // mécanisme de callback CallBackManager callBackManager = CallBackManager.get(); callBackManager.invoke(CallBackManager.ACTION_PUBLICATION_REMOVE, Integer.parseInt(pubPK.getId()), pubPK.getInstanceId(), ""); } } catch (Exception e) { throw new KmeliaRuntimeException("KmeliaBmEJB.sendPublicationToBasket()", ERROR, "kmelia.EX_IMPOSSIBLE_DENVOYER_LA_PUBLICATION_A_LA_CORBEILLE", e); } SilverTrace.info("kmelia", "KmeliaBmEJB.sendPublicationToBasket()", "root.MSG_GEN_EXIT_METHOD"); } @Override public void sendPublicationToBasket(PublicationPK pubPK) { sendPublicationToBasket(pubPK, false); } /** * Add a publication to a topic and send email alerts to topic subscribers * @param pubPK the id of the publication * @param fatherPK the id of the topic * @param isACreation */ @Override public void addPublicationToTopic(PublicationPK pubPK, NodePK fatherPK, boolean isACreation) { addPublicationToTopicWithoutNotifications(pubPK, fatherPK, isACreation); SilverTrace.info("kmelia", "KmeliaBmEJB.addPublicationToTopic()", "root.MSG_GEN_ENTER_METHOD"); PublicationDetail pubDetail = getPublicationDetail(pubPK); sendSubscriptionsNotification(pubDetail, false); SilverTrace.info("kmelia", "KmeliaBmEJB.addPublicationToTopic()", "root.MSG_GEN_EXIT_METHOD"); } @Override public void addPublicationToTopicWithoutNotifications(PublicationPK pubPK, NodePK fatherPK, boolean isACreation) { SilverTrace.info("kmelia", "KmeliaBmEJB.addPublicationToTopic()", "root.MSG_GEN_ENTER_METHOD"); PublicationDetail pubDetail = getPublicationDetail(pubPK); if (!isACreation) { try { Collection<NodePK> fathers = getPublicationBm().getAllFatherPK(pubPK); if (isPublicationInBasket(pubPK, fathers)) { getPublicationBm().removeFather(pubPK, new NodePK("1", fatherPK)); if (pubDetail.getStatus().equalsIgnoreCase(PublicationDetail.VALID)) { // index publication getPublicationBm().createIndex(pubPK); // index external elements indexExternalElementsOfPublication(pubDetail); // publication is accessible again updateSilverContentVisibility(pubDetail); } else if (pubDetail.getStatus().equalsIgnoreCase( PublicationDetail.TO_VALIDATE)) { // create validation todos for publishers createTodosForPublication(pubDetail, true); } } else if (fathers.isEmpty()) { // The publi have got no father // change the end date to make this publi visible pubDetail.setEndDate(null); getPublicationBm().setDetail(pubDetail); // publication is accessible again updateSilverContentVisibility(pubDetail); } } catch (Exception e) { throw new KmeliaRuntimeException("KmeliaBmEJB.addPublicationToTopic()", ERROR, "kmelia.EX_IMPOSSIBLE_DE_PLACER_LA_PUBLICATION_DANS_LE_THEME", e); } } try { getPublicationBm().addFather(pubPK, fatherPK); } catch (Exception e) { throw new KmeliaRuntimeException("KmeliaBmEJB.addPublicationToTopic()", ERROR, "kmelia.EX_IMPOSSIBLE_DE_PLACER_LA_PUBLICATION_DANS_LE_THEME", e); } } private boolean isPublicationInBasket(PublicationPK pubPK) throws RemoteException { return isPublicationInBasket(pubPK, null); } private boolean isPublicationInBasket(PublicationPK pubPK, Collection<NodePK> fathers) throws RemoteException { if (fathers == null) { fathers = getPublicationBm().getAllFatherPK(pubPK); } if (fathers.size() == 1) { Iterator<NodePK> iterator = fathers.iterator(); if (iterator.hasNext()) { NodePK pk = iterator.next(); if (pk.isTrash()) { return true; } } } return false; } private NodePK sendSubscriptionsNotification(PublicationDetail pubDetail, boolean update) { NodePK oneFather = null; // We alert subscribers only if publication is Valid if (!pubDetail.haveGotClone() && PublicationDetail.VALID.equals(pubDetail.getStatus())) { // topic subscriptions Collection<NodePK> fathers = getPublicationFathers(pubDetail.getPK()); if (fathers != null) { for (NodePK father : fathers) { oneFather = father; sendSubscriptionsNotification(oneFather, pubDetail, update); } } // PDC subscriptions try { int silverObjectId = getSilverObjectId(pubDetail.getPK()); List<ClassifyPosition> positions = getPdcBm().getPositions(silverObjectId, pubDetail.getPK().getInstanceId()); PdcSubscriptionUtil pdc = new PdcSubscriptionUtil(); if (positions != null) { for (ClassifyPosition position : positions) { pdc.checkSubscriptions(position.getValues(), pubDetail.getPK().getInstanceId(), silverObjectId); } } } catch (RemoteException e) { SilverTrace.error("kmelia", "KmeliaBmEJB.sendSubscriptionsNotification", "kmelia.CANT_SEND_PDC_SUBSCRIPTIONS", e); } } return oneFather; } private void sendSubscriptionsNotification(NodePK fatherPK, PublicationDetail pubDetail, boolean update) { // send email alerts try { // Computing the action final NotifAction action; if (update) { action = NotifAction.UPDATE; } else { action = NotifAction.CREATE; } // Building and sending the notification UserNotificationHelper.buildAndSend(new KmeliaSubscriptionPublicationUserNotification(fatherPK, pubDetail, action)); } catch (Exception e) { SilverTrace.warn("kmelia", "KmeliaBmEJB.sendSubscriptionsNotification()", "kmelia.EX_IMPOSSIBLE_DALERTER_LES_UTILISATEURS", "fatherId = " + fatherPK.getId() + ", pubId = " + pubDetail.getPK().getId(), e); } } /** * Delete a path between publication and topic * @param pubPK * @param fatherPK */ @Override public void deletePublicationFromTopic(PublicationPK pubPK, NodePK fatherPK) { SilverTrace.info("kmelia", "KmeliaBmEJB.deletePublicationFromTopic()", "root.MSG_GEN_ENTER_METHOD"); try { Collection<NodePK> pubFathers = getPublicationBm().getAllFatherPK(pubPK); if (pubFathers.size() >= 2) { getPublicationBm().removeFather(pubPK, fatherPK); } else { // la publication n'a qu'un seul emplacement // elle est donc placée dans la corbeille du créateur sendPublicationToBasket(pubPK); } } catch (Exception e) { throw new KmeliaRuntimeException( "KmeliaBmEJB.deletePublicationFromTopic()", ERROR, "kmelia.EX_IMPOSSIBLE_DE_SUPPRIMER_LA_PUBLICATION_DE_CE_THEME", e); } SilverTrace.info("kmelia", "KmeliaBmEJB.deletePublicationFromTopic()", "root.MSG_GEN_EXIT_METHOD"); } @Override public void deletePublicationFromAllTopics(PublicationPK pubPK) { SilverTrace.info("kmelia", "KmeliaBmEJB.deletePublicationFromAllTopics()", "root.MSG_GEN_ENTER_METHOD"); try { getPublicationBm().removeAllFather(pubPK); // la publication n'a qu'un seul emplacement // elle est donc placée dans la corbeille du créateur sendPublicationToBasket(pubPK); } catch (Exception e) { throw new KmeliaRuntimeException( "KmeliaBmEJB.deletePublicationFromAllTopics()", ERROR, "kmelia.EX_IMPOSSIBLE_DE_SUPPRIMER_LA_PUBLICATION_DE_CE_THEME", e); } SilverTrace.info("kmelia", "KmeliaBmEJB.deletePublicationFromAllTopics()", "root.MSG_GEN_EXIT_METHOD"); } /** * get all available models * @return a Collection of ModelDetail * @see com.stratelia.webactiv.util.publication.info.model.ModelDetail * @since 1.0 */ @Override public Collection<ModelDetail> getAllModels() { SilverTrace.info("kmelia", "KmeliaBmEJB.getAllModels()", "root.MSG_GEN_ENTER_METHOD"); try { SilverTrace.info("kmelia", "KmeliaBmEJB.getAllModels()", "root.MSG_GEN_EXIT_METHOD"); return getPublicationBm().getAllModelsDetail(); } catch (Exception e) { throw new KmeliaRuntimeException("KmeliaBmEJB.getAllModels()", ERROR, "kmelia.EX_IMPOSSIBLE_DOBTENIR_LES_MODELES", e); } } /** * Return the detail of a model * @param modelId the id of the model * @return a ModelDetail * @since 1.0 */ @Override public ModelDetail getModelDetail(String modelId) { SilverTrace.info("kmelia", "KmeliaBmEJB.getModelDetail()", "root.MSG_GEN_ENTER_METHOD"); try { ModelPK modelPK = new ModelPK(modelId); SilverTrace.info("kmelia", "KmeliaBmEJB.getModelDetail()", "root.MSG_GEN_EXIT_METHOD"); return getPublicationBm().getModelDetail(modelPK); } catch (Exception e) { throw new KmeliaRuntimeException("KmeliaBmEJB.getModelDetail()", ERROR, "kmelia.EX_IMPOSSIBLE_DOBTENIR_LE_DETAIL_DU_MODELE", e); } } /** * Create info attached to a publication * @param pubPK the id of the publication * @param modelId the id of the selected model * @param infos an InfoDetail containing info * @since 1.0 */ @Override public void createInfoDetail(PublicationPK pubPK, String modelId, InfoDetail infos) { SilverTrace.info("kmelia", "KmeliaBmEJB.createInfoDetail()", "root.MSG_GEN_ENTER_METHOD"); try { ModelPK modelPK = new ModelPK(modelId, pubPK); checkIndex(pubPK, infos); getPublicationBm().createInfoDetail(pubPK, modelPK, infos); } catch (Exception e) { throw new KmeliaRuntimeException("KmeliaBmEJB.createInfoDetail()", ERROR, "kmelia.EX_IMPOSSIBLE_DENREGISTRER_LE_CONTENU_DU_MODELE", e); } updatePublication(pubPK, KmeliaHelper.PUBLICATION_CONTENT); SilverTrace.info("kmelia", "KmeliaBmEJB.createInfoDetail()", "root.MSG_GEN_EXIT_METHOD"); } /** * Create model info attached to a publication * @param pubPK the id of the publication * @param modelId the id of the selected model * @param infos an InfoDetail containing info * @since 1.0 */ @Override public void createInfoModelDetail(PublicationPK pubPK, String modelId, InfoDetail infos) { SilverTrace.info("kmelia", "KmeliaBmEJB.createInfoModelDetail()", "root.MSG_GEN_ENTER_METHOD"); try { ModelPK modelPK = new ModelPK(modelId, pubPK); checkIndex(pubPK, infos); getPublicationBm().createInfoModelDetail(pubPK, modelPK, infos); } catch (Exception e) { throw new KmeliaRuntimeException("KmeliaBmEJB.createInfoModelDetail()", ERROR, "kmelia.EX_IMPOSSIBLE_DENREGISTRER_LE_CONTENU_DU_MODELE", e); } updatePublication(pubPK, KmeliaHelper.PUBLICATION_CONTENT); SilverTrace.info("kmelia", "KmeliaBmEJB.createInfoModelDetail()", "root.MSG_GEN_EXIT_METHOD"); } /** * get info attached to a publication * @param pubPK the id of the publication * @return an InfoDetail * @since 1.0 */ @Override public InfoDetail getInfoDetail(PublicationPK pubPK) { SilverTrace.info("kmelia", "KmeliaBmEJB.getInfoDetail()", "root.MSG_GEN_ENTER_METHOD"); try { return getPublicationBm().getInfoDetail(pubPK); } catch (Exception e) { throw new KmeliaRuntimeException("KmeliaBmEJB.getInfoDetail()", ERROR, "kmelia.EX_IMPOSSIBLE_DOBTENIR_LE_CONTENU_DU_MODELE", e); } } /** * Update info attached to a publication * @param pubPK the id of the publication * @param infos an InfoDetail containing info to updated * @since 1.0 */ @Override public void updateInfoDetail(PublicationPK pubPK, InfoDetail infos) { SilverTrace.info("kmelia", "KmeliaBmEJB.updateInfoDetail()", "root.MSG_GEN_ENTER_METHOD"); try { checkIndex(pubPK, infos); getPublicationBm().updateInfoDetail(pubPK, infos); } catch (Exception e) { throw new KmeliaRuntimeException("KmeliaBmEJB.updateInfoDetail()", ERROR, "kmelia.EX_IMPOSSIBLE_DE_MODIFIER_LE_CONTENU_DU_MODELE", e); } updatePublication(pubPK, KmeliaHelper.PUBLICATION_CONTENT); SilverTrace.info("kmelia", "KmeliaBmEJB.updateInfoDetail()", "root.MSG_GEN_EXIT_METHOD"); } /** * Updates the publication links * @param pubPK publication identifier which you want to update links * @param links list of publication to link with current. */ @Override public void addInfoLinks(PublicationPK pubPK, List<ForeignPK> links) { SilverTrace.info("kmelia", "KmeliaBmEJB.addInfoLinks()", "root.MSG_GEN_ENTER_METHOD", "pubId = " + pubPK.getId() + ", pubIds = " + links.toString()); try { getPublicationBm().addLinks(pubPK, links); } catch (Exception e) { throw new KmeliaRuntimeException("KmeliaBmEJB.addInfoLinks()", ERROR, "kmelia.EX_IMPOSSIBLE_DE_MODIFIER_LE_CONTENU_DU_MODELE", e); } } @Override public void deleteInfoLinks(PublicationPK pubPK, List<ForeignPK> links) { SilverTrace.info("kmelia", "KmeliaBmEJB.deleteInfoLinks()", "root.MSG_GEN_ENTER_METHOD", "pubId = " + pubPK.getId() + ", pubIds = " + links.toString()); try { getPublicationBm().deleteInfoLinks(pubPK, links); } catch (Exception e) { throw new KmeliaRuntimeException("KmeliaBmEJB.deleteInfoLinks()", ERROR, "kmelia.EX_IMPOSSIBLE_DE_MODIFIER_LE_CONTENU_DU_MODELE", e); } } @Override public CompletePublication getCompletePublication(PublicationPK pubPK) { SilverTrace.info("kmelia", "KmeliaBmEJB.getCompletePublication()", "root.MSG_GEN_ENTER_METHOD"); CompletePublication completePublication = null; try { completePublication = getPublicationBm().getCompletePublication(pubPK); } catch (Exception e) { throw new KmeliaRuntimeException("KmeliaBmEJB.getCompletePublication()", ERROR, "kmelia.EX_IMPOSSIBLE_DOBTENIR_LA_PUBLICATION", e); } SilverTrace.info("kmelia", "KmeliaBmEJB.getCompletePublication()", "root.MSG_GEN_EXIT_METHOD"); return completePublication; } @Override public KmeliaPublication getPublication(PublicationPK pubPK) { SilverTrace.info("kmelia", "KmeliaBmEJB.getPublication()", "root.MSG_GEN_ENTER_METHOD", "pubPK = " + pubPK.toString()); return aKmeliaPublicationWithPk(pubPK); } @Override public TopicDetail getPublicationFather(PublicationPK pubPK, boolean isTreeStructureUsed, String userId, boolean isRightsOnTopicsUsed) { SilverTrace.info("kmelia", "KmeliaBmEJB.getPublicationFather()", "root.MSG_GEN_ENTER_METHOD"); // fetch one of the publication fathers NodePK fatherPK = getPublicationFatherPK(pubPK, isTreeStructureUsed, userId, isRightsOnTopicsUsed); String profile = KmeliaHelper.getProfile(getOrganizationController().getUserProfiles(userId, pubPK.getInstanceId())); TopicDetail fatherDetail = goTo(fatherPK, userId, isTreeStructureUsed, profile, isRightsOnTopicsUsed); SilverTrace.info("kmelia", "KmeliaBmEJB.getPublicationFather()", "root.MSG_GEN_EXIT_METHOD"); return fatherDetail; } public NodePK getPublicationFatherPK(PublicationPK pubPK, boolean isTreeStructureUsed, String userId, boolean isRightsOnTopicsUsed) { SilverTrace.info("kmelia", "KmeliaBmEJB.getPublicationFatherId()", "root.MSG_GEN_ENTER_METHOD"); // fetch one of the publication fathers Collection<NodePK> fathers = getPublicationFathers(pubPK); NodePK fatherPK = new NodePK("0", pubPK); // By default --> Root if (fathers != null) { Iterator<NodePK> it = fathers.iterator(); if (!isRightsOnTopicsUsed) { if (it.hasNext()) { fatherPK = it.next(); } } else { NodeDetail allowedFather = null; while (allowedFather == null && it.hasNext()) { fatherPK = it.next(); NodeDetail father = getNodeHeader(fatherPK); if (!father.haveRights() || getOrganizationController().isObjectAvailable( father.getRightsDependsOn(), ObjectType.NODE, fatherPK.getInstanceId(), userId)) { allowedFather = father; } } if (allowedFather != null) { fatherPK = allowedFather.getNodePK(); } } } return fatherPK; } @Override public Collection<NodePK> getPublicationFathers(PublicationPK pubPK) { SilverTrace.info("kmelia", "KmeliaBmEJB.getPublicationFathers()", "root.MSG_GEN_ENTER_METHOD", "pubPK = " + pubPK.toString()); try { Collection<NodePK> fathers = getPublicationBm().getAllFatherPK(pubPK); if (fathers == null || fathers.isEmpty()) { SilverTrace.info("kmelia", "KmeliaBmEJB.getPublicationFathers()", "root.MSG_GEN_PARAM_VALUE", "Following publication have got no fathers : pubPK = " + pubPK.toString()); // This publication have got no father ! // Check if it's a clone (a clone have got no father ever) boolean alwaysVisibleModeActivated = "yes".equalsIgnoreCase(getOrganizationController().getComponentParameterValue( pubPK.getInstanceId(), "publicationAlwaysVisible")); if (alwaysVisibleModeActivated) { SilverTrace.info("kmelia", "KmeliaBmEJB.getPublicationFathers()", "root.MSG_GEN_PARAM_VALUE", "Getting the publication"); PublicationDetail publi = getPublicationBm().getDetail(pubPK); if (publi != null) { boolean isClone = isDefined(publi.getCloneId()) && !isDefined(publi.getCloneStatus()); SilverTrace.info("kmelia", "KmeliaBmEJB.getPublicationFathers()", "root.MSG_GEN_PARAM_VALUE", "This publication is clone ? " + isClone); if (isClone) { // This publication is a clone // Get fathers from main publication fathers = getPublicationBm().getAllFatherPK(publi.getClonePK()); SilverTrace.info("kmelia", "KmeliaBmEJB.getPublicationFathers()", "root.MSG_GEN_PARAM_VALUE", "Main publication's fathers fetched. # of fathers = " + fathers.size()); } } } } return fathers; } catch (Exception e) { throw new KmeliaRuntimeException("KmeliaBmEJB.getPublicationFathers()", ERROR, "kmelia.EX_IMPOSSIBLE_DOBTENIR_UN_PERE_DE_LA_PUBLICATION", e); } } /** * gets a list of PublicationDetail corresponding to the links parameter * @param links list of publication (componentID + publicationId) * @return a list of PublicationDetail */ @Override public Collection<PublicationDetail> getPublicationDetails(List<ForeignPK> links) { SilverTrace.info("kmelia", "KmeliaBmEJB.getPublicationDetails()", "root.MSG_GEN_ENTER_METHOD"); Collection<PublicationDetail> publications = null; List<PublicationPK> publicationPKs = new ArrayList<PublicationPK>(); for (ForeignPK link : links) { PublicationPK pubPK = new PublicationPK(link.getId(), link.getInstanceId()); publicationPKs.add(pubPK); } try { publications = getPublicationBm().getPublications(publicationPKs); } catch (Exception e) { throw new KmeliaRuntimeException("KmeliaBmEJB.getPublicationDetails()", ERROR, "kmelia.EX_IMPOSSIBLE_DOBTENIR_LES_PUBLICATIONS", e); } SilverTrace.info("kmelia", "KmeliaBmEJB.getPublicationDetails()", "root.MSG_GEN_EXIT_METHOD"); return publications; } /** * gets a list of authorized publications * @param links list of publication defined by his id and component id * @param userId identifier User. allow to check if the publication is accessible for current user * @param isRightsOnTopicsUsed indicates if the right must be checked * @return a collection of Kmelia publication * @since 1.0 */ @Override public Collection<KmeliaPublication> getPublications(List<ForeignPK> links, String userId, boolean isRightsOnTopicsUsed) { SilverTrace.info("kmelia", "KmeliaBmEJB.getPublications()", "root.MSG_GEN_ENTER_METHOD"); // initialization of the publications list List<ForeignPK> allowedPublicationIds = new ArrayList<ForeignPK>(links); if (isRightsOnTopicsUsed) { KmeliaSecurity security = new KmeliaSecurity(); allowedPublicationIds.clear(); // check if the publication is authorized for current user for (ForeignPK link : links) { if (security.isObjectAvailable(link.getInstanceId(), userId, link.getId(), KmeliaSecurity.PUBLICATION_TYPE)) { allowedPublicationIds.add(link); } } } Collection<PublicationDetail> publications = getPublicationDetails(allowedPublicationIds); return pubDetails2userPubs(publications); } /** * Gets the publications linked with the specified one and for which the specified user is * authorized to access. * @param publication the publication from which linked publications are get. * @param userId the unique identifier of a user. It allows to check if a linked publication is * accessible for the specified user. * @return a list of Kmelia publications. * @throws RemoteException if an error occurs while communicating with the remote business service. */ @Override public List<KmeliaPublication> getLinkedPublications(KmeliaPublication publication, String userId) throws RemoteException { KmeliaSecurity security = new KmeliaSecurity(); List<ForeignPK> allLinkIds = publication.getCompleteDetail().getLinkList(); List<KmeliaPublication> authorizedLinks = new ArrayList<KmeliaPublication>(allLinkIds.size()); for (ForeignPK linkId : allLinkIds) { if (security.isAccessAuthorized(linkId.getInstanceId(), userId, linkId.getId())) { PublicationPK pubPk = new PublicationPK(linkId.getId(), linkId.getInstanceId()); authorizedLinks.add(KmeliaPublication.aKmeliaPublicationWithPk(pubPk)); } } return authorizedLinks; } /** * Gets all the publications linked with the specified one. * @param publication the publication from which linked publications are get. * @return a list of Kmelia publications. * @throws RemoteException if an error occurs while communicating with the remote business service. */ @Override public List<KmeliaPublication> getLinkedPublications(KmeliaPublication publication) throws RemoteException { List<ForeignPK> allLinkIds = publication.getCompleteDetail().getLinkList(); List<KmeliaPublication> linkedPublications = new ArrayList<KmeliaPublication>(allLinkIds.size()); for (ForeignPK linkId : allLinkIds) { PublicationPK pubPk = new PublicationPK(linkId.getId(), linkId.getInstanceId()); linkedPublications.add(KmeliaPublication.aKmeliaPublicationWithPk(pubPk)); } return linkedPublications; } @Override public List<KmeliaPublication> getPublicationsToValidate(String componentId) { SilverTrace.info("kmelia", "KmeliaBmEJB.getPublicationsToValidate()", "root.MSG_GEN_ENTER_METHOD"); Collection<PublicationDetail> publications = new ArrayList<PublicationDetail>(); PublicationPK pubPK = new PublicationPK("useless", componentId); try { Collection<PublicationDetail> temp = getPublicationBm().getPublicationsByStatus(PublicationDetail.TO_VALIDATE, pubPK); // retrieve original publications according to clones for (PublicationDetail publi : temp) { boolean isClone = PublicationDetail.TO_VALIDATE.equals(publi.getStatus()) && !"-1".equals(publi.getCloneId()); if (isClone) { // publication is a clone, get original one publications.add(getPublicationDetail(new PublicationPK(publi.getCloneId(), publi.getPK()))); } else { // publication is not a clone, return it publications.add(publi); } } } catch (Exception e) { throw new KmeliaRuntimeException( "KmeliaBmEJB.getPublicationsToValidate()", ERROR, "kmelia.EX_IMPOSSIBLE_DOBTENIR_LES_PUBLICATIONS_A_VALIDER", e); } SilverTrace.info("kmelia", "KmeliaBmEJB.getPublicationsToValidate()", "root.MSG_GEN_EXIT_METHOD"); return pubDetails2userPubs(publications); } private void sendValidationNotification(final NodePK fatherPK, final PublicationDetail pubDetail, final String refusalMotive, final String userIdWhoRefuse) { try { UserNotificationHelper.buildAndSend(new KmeliaValidationPublicationUserNotification(fatherPK, pubDetail, refusalMotive, userIdWhoRefuse)); } catch (Exception e) { SilverTrace.warn("kmelia", "KmeliaBmEJB.sendValidationNotification()", "kmelia.EX_IMPOSSIBLE_DALERTER_LES_UTILISATEURS", "fatherId = " + fatherPK.getId() + ", pubPK = " + pubDetail.getPK(), e); } } private void sendAlertToSupervisors(final NodePK fatherPK, final PublicationDetail pubDetail) { if (pubDetail.isValid()) { try { UserNotificationHelper.buildAndSend(new KmeliaSupervisorPublicationUserNotification(fatherPK, pubDetail)); } catch (Exception e) { SilverTrace.warn("kmelia", "KmeliaBmEJB.alertSupervisors()", "kmelia.EX_IMPOSSIBLE_DALERTER_LES_UTILISATEURS", "fatherId = " + fatherPK.getId() + ", pubPK = " + pubDetail.getPK(), e); } } } private int getValidationType(String instanceId) { String sParam = getOrganizationController().getComponentParameterValue(instanceId, "targetValidation"); if (isDefined(sParam)) { return Integer.parseInt(sParam); } else { return KmeliaHelper.VALIDATION_CLASSIC; } } @Override public List<String> getAllValidators(PublicationPK pubPK, int validationType) throws RemoteException { SilverTrace.debug("kmelia", "KmeliaBmEJB.getAllValidators", "root.MSG_GEN_ENTER_METHOD", "pubId = " + pubPK.getId() + ", validationType = " + validationType); if (validationType == -1) { validationType = getValidationType(pubPK.getInstanceId()); } SilverTrace.debug("kmelia", "KmeliaBmEJB.getAllValidators", "root.MSG_GEN_PARAM_VALUE", "validationType = " + validationType); // get all users who have to validate List<String> allValidators = new ArrayList<String>(); if (validationType == KmeliaHelper.VALIDATION_TARGET_N || validationType == KmeliaHelper.VALIDATION_TARGET_1) { PublicationDetail publi = getPublicationBm().getDetail(pubPK); if (isDefined(publi.getTargetValidatorId())) { StringTokenizer tokenizer = new StringTokenizer(publi.getTargetValidatorId(), ","); while (tokenizer.hasMoreTokens()) { allValidators.add(tokenizer.nextToken()); } } } if (allValidators.isEmpty()) { // It's not a targeted validation or it is but no validators has // been selected ! List<String> roles = new ArrayList<String>(); roles.add("admin"); roles.add("publisher"); if (KmeliaHelper.isKmax(pubPK.getInstanceId())) { allValidators.addAll(Arrays.asList(getOrganizationController().getUsersIdsByRoleNames( pubPK.getInstanceId(), roles))); } else { // get admin and publishers of all nodes where publication is List<NodePK> nodePKs = (List<NodePK>) getPublicationFathers(pubPK); NodePK nodePK = null; NodeDetail node = null; boolean oneNodeIsPublic = false; for (int n = 0; !oneNodeIsPublic && nodePKs != null && n < nodePKs.size(); n++) { nodePK = nodePKs.get(n); node = getNodeHeader(nodePK); if (node != null) { SilverTrace.debug("kmelia", "KmeliaBmEJB.getAllValidators", "root.MSG_GEN_PARAM_VALUE", "nodePK = " + nodePK.toString()); if (!node.haveRights()) { allValidators.addAll(Arrays.asList(getOrganizationController().getUsersIdsByRoleNames( pubPK.getInstanceId(), roles))); oneNodeIsPublic = true; } else { allValidators.addAll(Arrays.asList(getOrganizationController().getUsersIdsByRoleNames( pubPK.getInstanceId(), Integer.toString(node.getRightsDependsOn()), ObjectType.NODE, roles))); } } } } } SilverTrace.debug("kmelia", "KmeliaBmEJB.getAllValidators", "root.MSG_GEN_EXIT_METHOD", "pubId = " + pubPK.getId() + ", allValidators = " + allValidators.toString()); return allValidators; } private boolean isValidationComplete(PublicationPK pubPK, List<String> allValidators, int validationType) throws RemoteException { List<ValidationStep> steps = getPublicationBm().getValidationSteps(pubPK); // get users who have already validate List<String> stepUserIds = new ArrayList<String>(); for (ValidationStep step : steps) { stepUserIds.add(step.getUserId()); } // check if all users have validate boolean validationOK = true; String validatorId = null; for (int i = 0; validationOK && i < allValidators.size(); i++) { validatorId = allValidators.get(i); validationOK = stepUserIds.contains(validatorId); } return validationOK; } @Override public boolean validatePublication(PublicationPK pubPK, String userId, int validationType, boolean force) { SilverTrace.info("kmelia", "KmeliaBmEJB.validatePublication()", "root.MSG_GEN_ENTER_METHOD"); boolean validationComplete = false; try { if (force) { validationComplete = true; } else { switch (validationType) { case KmeliaHelper.VALIDATION_CLASSIC: case KmeliaHelper.VALIDATION_TARGET_1: validationComplete = true; break; case KmeliaHelper.VALIDATION_COLLEGIATE: case KmeliaHelper.VALIDATION_TARGET_N: // get all users who have to validate List<String> allValidators = getAllValidators(pubPK, validationType); if (allValidators.size() == 1) { // special case : only once user is concerned by validation validationComplete = true; } else if (allValidators.size() > 1) { // remove todo for this user. His job is done ! removeTodoForPublication(pubPK, userId); // save his decision ValidationStep validation = new ValidationStep(pubPK, userId, PublicationDetail.VALID); getPublicationBm().addValidationStep(validation); // check if all validators have give their decision validationComplete = isValidationComplete(pubPK, allValidators, validationType); } } } if (validationComplete) { /* remove all todos attached to that publication */ removeAllTodosForPublication(pubPK); CompletePublication currentPub = getPublicationBm().getCompletePublication(pubPK); PublicationDetail currentPubDetail = currentPub.getPublicationDetail(); if (currentPubDetail.haveGotClone()) { currentPubDetail = mergeClone(currentPub, userId); } else if (currentPubDetail.isValidationRequired()) { currentPubDetail.setValidatorId(userId); currentPubDetail.setValidateDate(new Date()); currentPubDetail.setStatus(PublicationDetail.VALID); } KmeliaHelper.checkIndex(currentPubDetail); getPublicationBm().setDetail(currentPubDetail); updateSilverContentVisibility(currentPubDetail); // index all publication's elements indexExternalElementsOfPublication(currentPubDetail); // the publication has been validated // we must alert all subscribers of the different topics NodePK oneFather = sendSubscriptionsNotification(currentPubDetail, false); // we have to alert publication's creator sendValidationNotification(oneFather, currentPubDetail, null, userId); // alert supervisors sendAlertToSupervisors(oneFather, currentPubDetail); } } catch (Exception e) { throw new KmeliaRuntimeException("KmeliaBmEJB.validatePublication()", ERROR, "kmelia.EX_IMPOSSIBLE_DE_VALIDER_LA_PUBLICATION", e); } SilverTrace.info("kmelia", "KmeliaBmEJB.validatePublication()", "root.MSG_GEN_EXIT_METHOD", "validationComplete = " + validationComplete); return validationComplete; } private PublicationDetail getClone(PublicationDetail refPub) { PublicationDetail clone = new PublicationDetail(); if (refPub.getAuthor() != null) { clone.setAuthor(refPub.getAuthor()); } if (refPub.getBeginDate() != null) { clone.setBeginDate(new Date(refPub.getBeginDate().getTime())); } if (refPub.getBeginHour() != null) { clone.setBeginHour(refPub.getBeginHour()); } if (refPub.getContent() != null) { clone.setContent(refPub.getContent()); } clone.setCreationDate(new Date(refPub.getCreationDate().getTime())); clone.setCreatorId(refPub.getCreatorId()); if (refPub.getDescription() != null) { clone.setDescription(refPub.getDescription()); } if (refPub.getEndDate() != null) { clone.setEndDate(new Date(refPub.getEndDate().getTime())); } if (refPub.getEndHour() != null) { clone.setEndHour(refPub.getEndHour()); } clone.setImportance(refPub.getImportance()); if (refPub.getInfoId() != null) { clone.setInfoId(refPub.getInfoId()); } if (refPub.getKeywords() != null) { clone.setKeywords(refPub.getKeywords()); } if (refPub.getName() != null) { clone.setName(refPub.getName()); } clone.setPk(new PublicationPK(refPub.getPK().getId(), refPub.getPK().getInstanceId())); if (refPub.getStatus() != null) { clone.setStatus(refPub.getStatus()); } if (refPub.getTargetValidatorId() != null) { clone.setTargetValidatorId(refPub.getTargetValidatorId()); } if (refPub.getCloneId() != null) { clone.setCloneId(refPub.getCloneId()); } if (refPub.getUpdateDate() != null) { clone.setUpdateDate(new Date(refPub.getUpdateDate().getTime())); } if (refPub.getUpdaterId() != null) { clone.setUpdaterId(refPub.getUpdaterId()); } if (refPub.getValidateDate() != null) { clone.setValidateDate(new Date(refPub.getValidateDate().getTime())); } if (refPub.getValidatorId() != null) { clone.setValidatorId(refPub.getValidatorId()); } if (refPub.getVersion() != null) { clone.setVersion(refPub.getVersion()); } return clone; } private PublicationDetail mergeClone(CompletePublication currentPub, String userId) throws RemoteException, FormException, PublicationTemplateException, AttachmentException { PublicationDetail currentPubDetail = currentPub.getPublicationDetail(); String memInfoId = currentPubDetail.getInfoId(); PublicationPK pubPK = currentPubDetail.getPK(); // merge du clone sur la publi de référence String cloneId = currentPubDetail.getCloneId(); if (!"-1".equals(cloneId)) { PublicationPK tempPK = new PublicationPK(cloneId, pubPK); CompletePublication tempPubli = getPublicationBm().getCompletePublication(tempPK); PublicationDetail tempPubliDetail = tempPubli.getPublicationDetail(); // le clone devient la publi de référence currentPubDetail = getClone(tempPubliDetail); currentPubDetail.setPk(pubPK); if (userId != null) { currentPubDetail.setValidatorId(userId); currentPubDetail.setValidateDate(new Date()); } currentPubDetail.setStatus(PublicationDetail.VALID); currentPubDetail.setCloneId("-1"); currentPubDetail.setCloneStatus(null); // merge du contenu DBModel if (tempPubli.getModelDetail() != null) { if (currentPub.getModelDetail() != null) { currentPubDetail.setInfoId(memInfoId); // il existait déjà un contenu getPublicationBm().updateInfoDetail(pubPK, tempPubli.getInfoDetail()); } else { // il n'y avait pas encore de contenu ModelPK modelPK = new ModelPK(tempPubli.getModelDetail().getId(), "useless", tempPK.getInstanceId()); getPublicationBm().createInfoModelDetail(pubPK, modelPK, tempPubli.getInfoDetail()); // recupere nouvel infoId PublicationDetail modifiedPubli = getPublicationDetail(pubPK); currentPubDetail.setInfoId(modifiedPubli.getInfoId()); } } else { // merge du contenu XMLModel String infoId = tempPubli.getPublicationDetail().getInfoId(); if (infoId != null && !"0".equals(infoId) && !isInteger(infoId)) { // register xmlForm to publication String xmlFormShortName = infoId; // get xmlContent to paste PublicationTemplateManager publicationTemplateManager = PublicationTemplateManager.getInstance(); PublicationTemplate pubTemplate = publicationTemplateManager.getPublicationTemplate( tempPK.getInstanceId() + ":" + xmlFormShortName); RecordSet set = pubTemplate.getRecordSet(); // DataRecord data = set.getRecord(fromId); if (memInfoId != null && !"0".equals(memInfoId)) { // il existait déjà un contenu set.merge(cloneId, pubPK.getInstanceId(), pubPK.getId(), pubPK.getInstanceId()); } else { // il n'y avait pas encore de contenu publicationTemplateManager.addDynamicPublicationTemplate(tempPK.getInstanceId() + ":" + xmlFormShortName, xmlFormShortName + ".xml"); set.clone(cloneId, pubPK.getInstanceId(), pubPK.getId(), pubPK.getInstanceId()); } } } // merge du contenu Wysiwyg boolean cloneWysiwyg = WysiwygController.haveGotWysiwyg("useless", tempPK.getInstanceId(), cloneId); if (cloneWysiwyg) { WysiwygController.copy("useless", tempPK.getInstanceId(), cloneId, "useless", pubPK.getInstanceId(), pubPK.getId(), tempPubli.getPublicationDetail(). getUpdaterId()); } // merge des fichiers joints AttachmentPK pkFrom = new AttachmentPK(pubPK.getId(), pubPK.getInstanceId()); AttachmentPK pkTo = new AttachmentPK(cloneId, tempPK.getInstanceId()); AttachmentController.mergeAttachments(pkFrom, pkTo); // merge des fichiers versionnés // delete xml content removeXMLContentOfPublication(tempPK); // suppression du clone deletePublication(tempPK); } return currentPubDetail; } @Override public void unvalidatePublication(PublicationPK pubPK, String userId, String refusalMotive, int validationType) { SilverTrace.info("kmelia", "KmeliaBmEJB.unvalidatePublication()", "root.MSG_GEN_ENTER_METHOD"); try { switch (validationType) { case KmeliaHelper.VALIDATION_CLASSIC: case KmeliaHelper.VALIDATION_TARGET_1: // do nothing break; case KmeliaHelper.VALIDATION_COLLEGIATE: case KmeliaHelper.VALIDATION_TARGET_N: // reset other decisions getPublicationBm().removeValidationSteps(pubPK); } PublicationDetail currentPubDetail = getPublicationBm().getDetail(pubPK); if (currentPubDetail.haveGotClone()) { String cloneId = currentPubDetail.getCloneId(); PublicationPK tempPK = new PublicationPK(cloneId, pubPK); PublicationDetail clone = getPublicationBm().getDetail(tempPK); // change clone's status clone.setStatus("UnValidate"); clone.setIndexOperation(IndexManager.NONE); getPublicationBm().setDetail(clone); // Modification de la publication de reference currentPubDetail.setCloneStatus(PublicationDetail.REFUSED); currentPubDetail.setUpdateDateMustBeSet(false); getPublicationBm().setDetail(currentPubDetail); // we have to alert publication's last updater List<NodePK> fathers = (List<NodePK>) getPublicationFathers(pubPK); NodePK oneFather = null; if (fathers != null && fathers.size() > 0) { oneFather = fathers.get(0); } sendValidationNotification(oneFather, clone, refusalMotive, userId); } else { // send unvalidate publication to basket // sendPublicationToBasket(pubPK); // change publication's status currentPubDetail.setStatus("UnValidate"); KmeliaHelper.checkIndex(currentPubDetail); getPublicationBm().setDetail(currentPubDetail); // change visibility over PDC updateSilverContentVisibility(currentPubDetail); // we have to alert publication's creator List<NodePK> fathers = (List<NodePK>) getPublicationFathers(pubPK); NodePK oneFather = null; if (fathers != null && fathers.size() > 0) { oneFather = fathers.get(0); } sendValidationNotification(oneFather, currentPubDetail, refusalMotive, userId); } } catch (Exception e) { throw new KmeliaRuntimeException("KmeliaBmEJB.unvalidatePublication()", ERROR, "kmelia.EX_IMPOSSIBLE_DE_REFUSER_LA_PUBLICATION", e); } SilverTrace.info("kmelia", "KmeliaBmEJB.unvalidatePublication()", "root.MSG_GEN_EXIT_METHOD"); } @Override public void suspendPublication(PublicationPK pubPK, String defermentMotive, String userId) { SilverTrace.info("kmelia", "KmeliaBmEJB.suspendPublication()", "root.MSG_GEN_ENTER_METHOD"); try { PublicationDetail currentPubDetail = getPublicationBm().getDetail(pubPK); // change publication's status currentPubDetail.setStatus(PublicationDetail.TO_VALIDATE); KmeliaHelper.checkIndex(currentPubDetail); getPublicationBm().setDetail(currentPubDetail); // change visibility over PDC updateSilverContentVisibility(currentPubDetail); unIndexExternalElementsOfPublication(currentPubDetail.getPK()); // we have to alert publication's creator sendDefermentNotification(currentPubDetail, defermentMotive, userId); } catch (Exception e) { throw new KmeliaRuntimeException("KmeliaBmEJB.unvalidatePublication()", ERROR, "kmelia.EX_IMPOSSIBLE_DE_REFUSER_LA_PUBLICATION", e); } SilverTrace.info("kmelia", "KmeliaBmEJB.suspendPublication()", "root.MSG_GEN_EXIT_METHOD"); } private void sendDefermentNotification(final PublicationDetail pubDetail, final String defermentMotive, final String senderId) { try { UserNotificationHelper.buildAndSend(new KmeliaDefermentPublicationUserNotification(pubDetail, defermentMotive)); } catch (Exception e) { SilverTrace.warn("kmelia", "KmeliaBmEJB.sendDefermentNotification()", "kmelia.EX_IMPOSSIBLE_DALERTER_LES_UTILISATEURS", "pubPK = " + pubDetail.getPK(), e); } } /** * Change publication status from draft to valid (for publisher) or toValidate (for redactor). * @param pubPK * @param topicPK * @param userProfile */ @Override public void draftOutPublication(PublicationPK pubPK, NodePK topicPK, String userProfile) { PublicationDetail pubDetail = draftOutPublicationWithoutNotifications(pubPK, topicPK, userProfile); indexExternalElementsOfPublication(pubDetail); sendTodosAndNotificationsOnDraftOut(pubDetail, topicPK, userProfile); } /** * This method is here to manage correctly transactional scope of EJB (conflicted by EJB and UserPreferences service) */ @Override public PublicationDetail draftOutPublicationWithoutNotifications(PublicationPK pubPK, NodePK topicPK, String userProfile) { return draftOutPublication(pubPK, topicPK, userProfile, false, true); } @Override public PublicationDetail draftOutPublication(PublicationPK pubPK, NodePK topicPK, String userProfile, boolean forceUpdateDate) { return draftOutPublication(pubPK, topicPK, userProfile, forceUpdateDate, false); } private PublicationDetail draftOutPublication(PublicationPK pubPK, NodePK topicPK, String userProfile, boolean forceUpdateDate, boolean inTransaction) { SilverTrace.info("kmelia", "KmeliaBmEJB.draftOutPublication()", "root.MSG_GEN_ENTER_METHOD", "pubId = " + pubPK.getId()); try { CompletePublication currentPub = getPublicationBm().getCompletePublication(pubPK); PublicationDetail pubDetail = currentPub.getPublicationDetail(); SilverTrace.info("kmelia", "KmeliaBmEJB.draftOutPublication()", "root.MSG_GEN_PARAM_VALUE", "actual status = " + pubDetail.getStatus()); if (userProfile.equals("publisher") || userProfile.equals("admin")) { if (pubDetail.haveGotClone()) { pubDetail = mergeClone(currentPub, null); } pubDetail.setStatus(PublicationDetail.VALID); } else { if (pubDetail.haveGotClone()) { // changement du statut du clone PublicationDetail clone = getPublicationBm().getDetail(pubDetail.getClonePK()); clone.setStatus(PublicationDetail.TO_VALIDATE); clone.setIndexOperation(IndexManager.NONE); clone.setUpdateDateMustBeSet(false); getPublicationBm().setDetail(clone); pubDetail.setCloneStatus(PublicationDetail.TO_VALIDATE); } else { pubDetail.setStatus(PublicationDetail.TO_VALIDATE); } } KmeliaHelper.checkIndex(pubDetail); getPublicationBm().setDetail(pubDetail, forceUpdateDate); if (!KmeliaHelper.isKmax(pubDetail.getInstanceId())) { // update visibility attribute on PDC updateSilverContentVisibility(pubDetail); } SilverTrace.info("kmelia", "KmeliaBmEJB.draftOutPublication()", "root.MSG_GEN_PARAM_VALUE", "new status = " + pubDetail.getStatus()); if (!inTransaction) { // index all publication's elements indexExternalElementsOfPublication(pubDetail); sendTodosAndNotificationsOnDraftOut(pubDetail, topicPK, userProfile); } return pubDetail; } catch (Exception e) { throw new KmeliaRuntimeException("KmeliaBmEJB.draftOutPublication()", ERROR, "kmelia.EX_IMPOSSIBLE_DE_MODIFIER_LA_PUBLICATION", e); } } private void sendTodosAndNotificationsOnDraftOut(PublicationDetail pubDetail, NodePK topicPK, String userProfile) { if (SilverpeasRole.writer.isInRole(userProfile)) { try { createTodosForPublication(pubDetail, true); } catch (RemoteException e) { throw new KmeliaRuntimeException("KmeliaBmEJB.sendTodosAndNotificationsOnDraftOut()", ERROR, "kmelia.CANT_CREATE_TODOS", e); } } // Subscriptions and supervisors are supported by kmelia and filebox only if (!KmeliaHelper.isKmax(pubDetail.getInstanceId())) { // alert subscribers sendSubscriptionsNotification(pubDetail, false); // alert supervisors if (topicPK != null) { sendAlertToSupervisors(topicPK, pubDetail); } } } /** * Change publication status from any state to draft. * @param pubPK */ @Override public void draftInPublication(PublicationPK pubPK) { draftInPublication(pubPK, null); } @Override public void draftInPublication(PublicationPK pubPK, String userId) { SilverTrace.info("kmelia", "KmeliaBmEJB.draftInPublication()", "root.MSG_GEN_ENTER_METHOD", "pubPK = " + pubPK.toString()); try { PublicationDetail pubDetail = getPublicationBm().getDetail(pubPK); SilverTrace.info("kmelia", "KmeliaBmEJB.draftInPublication()", "root.MSG_GEN_PARAM_VALUE", "actual status = " + pubDetail.getStatus()); pubDetail.setStatus(PublicationDetail.DRAFT); pubDetail.setUpdaterId(userId); KmeliaHelper.checkIndex(pubDetail); getPublicationBm().setDetail(pubDetail); updateSilverContentVisibility(pubDetail); unIndexExternalElementsOfPublication(pubDetail.getPK()); removeAllTodosForPublication(pubPK); boolean isNewsManage = getBooleanValue(getOrganizationController().getComponentParameterValue( pubDetail.getPK().getInstanceId(), "isNewsManage")); if (isNewsManage) { // mécanisme de callback CallBackManager callBackManager = CallBackManager.get(); callBackManager.invoke(CallBackManager.ACTION_PUBLICATION_REMOVE, Integer.parseInt(pubDetail.getId()), pubDetail.getInstanceId(), pubDetail); } SilverTrace.info("kmelia", "KmeliaBmEJB.draftInPublication()", "root.MSG_GEN_PARAM_VALUE", "new status = " + pubDetail.getStatus()); } catch (Exception e) { throw new KmeliaRuntimeException("KmeliaBmEJB.draftInPublication()", ERROR, "kmelia.EX_IMPOSSIBLE_DE_MODIFIER_LA_PUBLICATION", e); } } @Override public NotificationMetaData getAlertNotificationMetaData(PublicationPK pubPK, NodePK topicPK, String senderName) { SilverTrace.info("kmelia", "KmeliaBmEJB.getAlertNotificationMetaData()", "root.MSG_GEN_ENTER_METHOD"); final PublicationDetail pubDetail = getPublicationDetail(pubPK); final NotificationMetaData notifMetaData = UserNotificationHelper.build(new KmeliaSubscriptionPublicationUserNotification(topicPK, pubDetail, NotifAction.REPORT, senderName)); SilverTrace.info("kmelia", "KmeliaBmEJB.getAlertNotificationMetaData()", "root.MSG_GEN_EXIT_METHOD"); return notifMetaData; } /** * @param pubPK * @param attachmentPk * @param topicPK * @param senderName * @return */ @Override public NotificationMetaData getAlertNotificationMetaData(PublicationPK pubPK, AttachmentPK attachmentPk, NodePK topicPK, String senderName) { SilverTrace.info("kmelia", "KmeliaBmEJB.getAlertNotificationMetaData(attachment)", "root.MSG_GEN_ENTER_METHOD"); final PublicationDetail pubDetail = getPublicationDetail(pubPK); final AttachmentDetail attachmentDetail = AttachmentController.searchAttachmentByPK(attachmentPk); final NotificationMetaData notifMetaData = UserNotificationHelper.build(new KmeliaAttachmentSubscriptionPublicationUserNotification(topicPK, pubDetail, attachmentDetail, senderName)); SilverTrace.info("kmelia", "KmeliaBmEJB.getAlertNotificationMetaData(attachment)", "root.MSG_GEN_EXIT_METHOD"); return notifMetaData; } /** * @param pubPK * @param documentPk * @param topicPK * @param senderName * @return * @throws RemoteException */ @Override public NotificationMetaData getAlertNotificationMetaData(PublicationPK pubPK, DocumentPK documentPk, NodePK topicPK, String senderName) throws RemoteException { SilverTrace.info("kmelia", "KmeliaBmEJB.getAlertNotificationMetaData(document)", "root.MSG_GEN_ENTER_METHOD"); final PublicationDetail pubDetail = getPublicationDetail(pubPK); final VersioningUtil versioningUtil = new VersioningUtil(); final Document document = versioningUtil.getDocument(documentPk); final DocumentVersion documentVersion = versioningUtil.getLastPublicVersion(documentPk); final NotificationMetaData notifMetaData = UserNotificationHelper.build(new KmeliaDocumentSubscriptionPublicationUserNotification(topicPK, pubDetail, document, documentVersion, senderName)); SilverTrace.info("kmelia", "KmeliaBmEJB.getAlertNotificationMetaData(document)", "root.MSG_GEN_EXIT_METHOD"); return notifMetaData; } /**************************************************************************************/ /* Controle de lecture */ /**************************************************************************************/ /** * delete reading controls to a publication * @param pubPK the id of a publication * @since 1.0 */ @Override public void deleteAllReadingControlsByPublication(PublicationPK pubPK) { SilverTrace.info("kmelia", "KmeliaBmEJB.deleteAllReadingControlsByPublication()", "root.MSG_GEN_ENTER_METHOD"); try { getStatisticBm().deleteHistoryByAction(new ForeignPK(pubPK.getId(), pubPK.getInstanceId()), 1, "Publication"); } catch (Exception e) { throw new KmeliaRuntimeException("KmeliaBmEJB.deleteAllReadingControlsByPublication()", ERROR, "kmelia.EX_IMPOSSIBLE_DE_SUPPRIMER_LES_CONTROLES_DE_LECTURE", e); } SilverTrace.info("kmelia", "KmeliaBmEJB.deleteAllReadingControlsByPublication()", "root.MSG_GEN_EXIT_METHOD"); } @Override public void indexKmelia(String componentId) { indexTopics(new NodePK("useless", componentId)); indexPublications(new PublicationPK("useless", componentId)); } private void indexPublications(PublicationPK pubPK) { Collection<PublicationDetail> pubs = null; try { pubs = getPublicationBm().getAllPublications(pubPK); } catch (Exception e) { throw new KmeliaRuntimeException("KmeliaBmEJB.indexPublications()", ERROR, "kmelia.EX_IMPOSSIBLE_DINDEXER_LES_PUBLICATIONS", e); } if (pubs != null) { for (PublicationDetail pub : pubs) { try { pubPK = pub.getPK(); List<NodePK> pubFathers = null; // index only valid publications if (pub.getStatus() != null && pub.isValid()) { pubFathers = (List<NodePK>) getPublicationBm().getAllFatherPK(pubPK); // index only valid publications which are not only in // dz or basket if (pubFathers.size() >= 2) { indexPublication(pub); } else if (pubFathers.size() == 1) { NodePK nodePK = pubFathers.get(0); // index the valid publication if it is not in the // basket if (!nodePK.isTrash()) { indexPublication(pub); } } else { // don't index publications in the dz } } } catch (Exception e) { throw new KmeliaRuntimeException("KmeliaBmEJB.indexPublications()", ERROR, "kmelia.EX_IMPOSSIBLE_DINDEXER_LA_PUBLICATION", "pubPK = " + pubPK.toString(), e); } } } } private void indexPublication(PublicationDetail pub) throws RemoteException { // index publication itself getPublicationBm().createIndex(pub.getPK()); // index external elements indexExternalElementsOfPublication(pub); } private void indexTopics(NodePK nodePK) { try { Collection<NodeDetail> nodes = getNodeBm().getAllNodes(nodePK); if (nodes != null) { for (NodeDetail node : nodes) { if (!node.getNodePK().isRoot() && !node.getNodePK().isTrash() && !node.getNodePK().getId().equals("2")) { getNodeBm().createIndex(node); } } } } catch (Exception e) { throw new KmeliaRuntimeException("KmeliaBmEJB.indexTopics()", ERROR, "kmelia.EX_IMPOSSIBLE_DINDEXER_LES_THEMES", e); } } /**************************************************************************************/ /* Gestion des todos */ /**************************************************************************************/ /* * Creates todos for all publishers of this kmelia instance * @param pubDetail publication to be validated * @param creation true if it's the creation of the publi */ private void createTodosForPublication(PublicationDetail pubDetail, boolean creation) throws RemoteException { if (!creation) { /* remove all todos attached to that publication */ removeAllTodosForPublication(pubDetail.getPK()); } if (pubDetail.isValidationRequired() || PublicationDetail.TO_VALIDATE.equalsIgnoreCase(pubDetail.getCloneStatus())) { int validationType = getValidationType(pubDetail.getPK().getInstanceId()); if (validationType == KmeliaHelper.VALIDATION_TARGET_N || validationType == KmeliaHelper.VALIDATION_COLLEGIATE) { // removing potential older validation decision getPublicationBm().removeValidationSteps(pubDetail.getPK()); } List<String> validators = getAllValidators(pubDetail.getPK(), validationType); String[] users = validators.toArray(new String[validators.size()]); // For each publisher create a todo addTodo(pubDetail, users); // Send a notification to alert admins and publishers sendValidationAlert(pubDetail, users); } } private String addTodo(PublicationDetail pubDetail, String[] users) { ResourceLocator message = new ResourceLocator( "com.stratelia.webactiv.kmelia.multilang.kmeliaBundle", "fr"); TodoDetail todo = new TodoDetail(); todo.setId(pubDetail.getPK().getId()); todo.setSpaceId(pubDetail.getPK().getSpace()); todo.setComponentId(pubDetail.getPK().getComponentName()); todo.setName(message.getString("ToValidateShort") + " : " + pubDetail.getName()); List<Attendee> attendees = new ArrayList<Attendee>(); for (String user : users) { if (user != null) { attendees.add(new Attendee(user)); } } todo.setAttendees(new ArrayList<Attendee>(attendees)); if (isDefined(pubDetail.getUpdaterId())) { todo.setDelegatorId(pubDetail.getUpdaterId()); } else { todo.setDelegatorId(pubDetail.getCreatorId()); } todo.setExternalId(pubDetail.getPK().getId()); TodoBackboneAccess todoBBA = new TodoBackboneAccess(); return todoBBA.addEntry(todo); } /* * Remove todos for all pubishers of this kmelia instance * @param pubDetail corresponding publication */ private void removeAllTodosForPublication(PublicationPK pubPK) { SilverTrace.info("kmelia", "KmeliaBmEJB.removeAllTodosForPublication()", "root.MSG_GEN_ENTER_METHOD", "Enter pubPK =" + pubPK.toString()); TodoBackboneAccess todoBBA = new TodoBackboneAccess(); todoBBA.removeEntriesFromExternal("useless", pubPK.getInstanceId(), pubPK.getId()); } private void removeTodoForPublication(PublicationPK pubPK, String userId) { SilverTrace.info("kmelia", "KmeliaBmEJB.removeTodoForPublication()", "root.MSG_GEN_ENTER_METHOD", "Enter pubPK =" + pubPK.toString()); TodoBackboneAccess todoBBA = new TodoBackboneAccess(); todoBBA.removeAttendeeToEntryFromExternal(pubPK.getInstanceId(), pubPK.getId(), userId); } private void sendValidationAlert(final PublicationDetail pubDetail, final String[] users) { UserNotificationHelper.buildAndSend(new KmeliaPendingValidationPublicationUserNotification(pubDetail, users)); } private void sendModificationAlert(final int modificationScope, final PublicationDetail pubDetail) { UserNotificationHelper.buildAndSend(new KmeliaModificationPublicationUserNotification(pubDetail, modificationScope)); } @Override public void sendModificationAlert(int modificationScope, PublicationPK pubPK) { sendModificationAlert(modificationScope, getPublicationDetail(pubPK)); } @Override public int getSilverObjectId(PublicationPK pubPK) { SilverTrace.info("kmelia", "KmeliaBmEJB.getSilverObjectId()", "root.MSG_GEN_ENTER_METHOD", "pubId = " + pubPK.getId()); int silverObjectId = -1; PublicationDetail pubDetail = null; try { silverObjectId = getKmeliaContentManager().getSilverObjectId( pubPK.getId(), pubPK.getInstanceId()); if (silverObjectId == -1) { pubDetail = getPublicationDetail(pubPK); silverObjectId = createSilverContent(pubDetail, pubDetail.getCreatorId()); } } catch (Exception e) { throw new KmeliaRuntimeException("KmeliaBmEJB.getSilverObjectId()", ERROR, "kmelia.EX_IMPOSSIBLE_DOBTENIR_LE_SILVEROBJECTID", e); } return silverObjectId; } private int createSilverContent(PublicationDetail pubDetail, String creatorId) { SilverTrace.info("kmelia", "KmeliaBmEJB.createSilverContent()", "root.MSG_GEN_ENTER_METHOD", "pubId = " + pubDetail.getPK().getId()); Connection con = null; try { con = getConnection(); return getKmeliaContentManager().createSilverContent(con, pubDetail, creatorId); } catch (Exception e) { throw new KmeliaRuntimeException("KmeliaBmEJB.createSilverContent()", ERROR, "kmelia.EX_IMPOSSIBLE_DOBTENIR_LE_SILVEROBJECTID", e); } finally { freeConnection(con); } } @Override public void deleteSilverContent(PublicationPK pubPK) { SilverTrace.info("kmelia", "KmeliaBmEJB.deleteSilverContent()", "root.MSG_GEN_ENTER_METHOD", "pubId = " + pubPK.getId()); Connection con = getConnection(); try { getKmeliaContentManager().deleteSilverContent(con, pubPK); } catch (Exception e) { throw new KmeliaRuntimeException("KmeliaBmEJB.deleteSilverContent()", ERROR, "kmelia.EX_IMPOSSIBLE_DOBTENIR_LE_SILVEROBJECTID", e); } finally { freeConnection(con); } } private void updateSilverContentVisibility(PublicationDetail pubDetail) { try { getKmeliaContentManager().updateSilverContentVisibility(pubDetail); } catch (Exception e) { throw new KmeliaRuntimeException("KmeliaBmEJB.updateSilverContentVisibility()", ERROR, "kmelia.EX_IMPOSSIBLE_DOBTENIR_LE_SILVEROBJECTID", e); } } private void updateSilverContentVisibility(PublicationPK pubPK, boolean isVisible) { PublicationDetail pubDetail = getPublicationDetail(pubPK); try { getKmeliaContentManager().updateSilverContentVisibility(pubDetail, isVisible); } catch (Exception e) { throw new KmeliaRuntimeException("KmeliaBmEJB.updateSilverContentVisibility()", ERROR, "kmelia.EX_IMPOSSIBLE_DOBTENIR_LE_SILVEROBJECTID", e); } } private KmeliaContentManager getKmeliaContentManager() { return new KmeliaContentManager(); } @Override public Collection<AttachmentDetail> getAttachments(PublicationPK pubPK) { SilverTrace.info("kmelia", "KmeliaBmEJB.getAttachments()", "root.MSG_GEN_ENTER_METHOD", "pubId = " + pubPK.getId()); String ctx = "Images"; AttachmentPK foreignKey = new AttachmentPK(pubPK.getId(), pubPK); SilverTrace.info("kmelia", "KmeliaBmEJB.getAttachments()", "root.MSG_GEN_PARAM_VALUE", "foreignKey = " + foreignKey.toString()); Connection con = null; try { con = getConnection(); Collection<AttachmentDetail> attachmentList = AttachmentController. searchAttachmentByPKAndContext(foreignKey, ctx, con); SilverTrace.info("kmelia", "KmeliaBmEJB.getAttachments()", "root.MSG_GEN_PARAM_VALUE", "attachmentList.size() = " + attachmentList.size()); return attachmentList; } catch (Exception e) { throw new KmeliaRuntimeException("KmeliaBmEJB.getAttachments()", ERROR, "kmelia.EX_IMPOSSIBLE_DOBTENIR_LES_FICHIERSJOINTS", e); } } @Override public String getWysiwyg(PublicationPK pubPK) { String wysiwygContent = null; try { wysiwygContent = WysiwygController.loadFileAndAttachment(pubPK.getSpaceId(), pubPK. getInstanceId(), pubPK.getId()); } catch (Exception e) { throw new KmeliaRuntimeException("KmeliaBmEJB.getAttachments()", ERROR, "kmelia.EX_IMPOSSIBLE_DOBTENIR_LE_WYSIWYG", e); } return wysiwygContent; } private void checkIndex(PublicationPK pubPK, InfoDetail infos) { infos.setIndexOperation(IndexManager.NONE); } private void indexExternalElementsOfPublication(PublicationDetail pubDetail) { if (KmeliaHelper.isIndexable(pubDetail)) { // index attachments AttachmentController.attachmentIndexer(pubDetail.getPK(), pubDetail.getBeginDate(), pubDetail.getEndDate()); try { // index versioning VersioningUtil versioning = new VersioningUtil(); versioning.indexDocumentsByForeignKey(new ForeignPK(pubDetail.getPK()), pubDetail.getBeginDate(), pubDetail.getEndDate()); } catch (Exception e) { SilverTrace.error("kmelia", "KmeliaBmEJB.indexExternalElementsOfPublication", "Indexing versioning documents failed", "pubPK = " + pubDetail.getPK().toString(), e); } try { // index comments getCommentService().indexAllCommentsOnPublication(pubDetail.getContributionType(), pubDetail.getPK()); } catch (Exception e) { SilverTrace.error("kmelia", "KmeliaBmEJB.indexExternalElementsOfPublication", "Indexing comments failed", "pubPK = " + pubDetail.getPK().toString(), e); } } } private void unIndexExternalElementsOfPublication(PublicationPK pubPK) { // unindex attachments AttachmentController.unindexAttachmentsByForeignKey(pubPK); try { // index versioning VersioningUtil versioning = new VersioningUtil(); versioning.unindexDocumentsByForeignKey(new ForeignPK(pubPK)); } catch (Exception e) { SilverTrace.error("kmelia", "KmeliaBmEJB.indexExternalElementsOfPublication", "Indexing versioning documents failed", "pubPK = " + pubPK.toString(), e); } try { // index comments getCommentService().unindexAllCommentsOnPublication(PublicationDetail.getResourceType(), pubPK); } catch (Exception e) { SilverTrace.error("kmelia", "KmeliaBmEJB.indexExternalElementsOfPublication", "Indexing comments failed", "pubPK = " + pubPK.toString(), e); } } private void removeExternalElementsOfPublications(PublicationPK pubPK) { // remove attachments AttachmentController.deleteAttachmentByCustomerPK(pubPK); // remove versioning try { getVersioningBm().deleteDocumentsByForeignPK(new ForeignPK(pubPK)); } catch (Exception e) { throw new KmeliaRuntimeException("KmeliaBmEJB.removeExternalElementsOfPublications()", ERROR, "kmelia.EX_IMPOSSIBLE_DE_SUPPRIMER_LES_FICHIERS_VERSIONNES", e); } // remove comments try { getCommentService() .deleteAllCommentsOnPublication(PublicationDetail.getResourceType(), pubPK); } catch (Exception e) { throw new KmeliaRuntimeException("KmeliaBmEJB.removeExternalElementsOfPublications()", ERROR, "kmelia.EX_IMPOSSIBLE_DE_SUPPRIMER_LES_COMMENTAIRES", e); } // remove Wysiwyg content try { WysiwygController.deleteWysiwygAttachments("useless", pubPK.getInstanceId(), pubPK.getId()); } catch (Exception e) { throw new KmeliaRuntimeException("KmeliaBmEJB.removeExternalElementsOfPublications", ERROR, "root.EX_DELETE_ATTACHMENT_FAILED", e); } // remove Thumbnail content try { ThumbnailDetail thumbToDelete = new ThumbnailDetail(pubPK.getInstanceId(), Integer.parseInt(pubPK.getId()), ThumbnailDetail.THUMBNAIL_OBJECTTYPE_PUBLICATION_VIGNETTE); ThumbnailController.deleteThumbnail(thumbToDelete); } catch (Exception e) { throw new KmeliaRuntimeException("KmeliaBmEJB.removeExternalElementsOfPublications", ERROR, "root.EX_DELETE_THUMBNAIL_FAILED", e); } } @Override public void removeContentOfPublication(PublicationPK pubPK) { // remove XML content PublicationDetail publication = getPublicationDetail(pubPK); if (!com.silverpeas.util.StringUtil.isInteger(publication.getInfoId())) { removeXMLContentOfPublication(pubPK); } // reset reference to content publication.setInfoId("0"); updatePublication(publication, KmeliaHelper.PUBLICATION_CONTENT, true); } private void removeXMLContentOfPublication(PublicationPK pubPK) { try { PublicationDetail pubDetail = getPublicationDetail(pubPK); String infoId = pubDetail.getInfoId(); if (!isInteger(infoId)) { String xmlFormShortName = infoId; PublicationTemplate pubTemplate = PublicationTemplateManager.getInstance(). getPublicationTemplate(pubDetail.getPK().getInstanceId() + ":" + xmlFormShortName); RecordSet set = pubTemplate.getRecordSet(); DataRecord data = set.getRecord(pubDetail.getPK().getId()); set.delete(data); } } catch (PublicationTemplateException e) { throw new KmeliaRuntimeException( "KmeliaBmEJB.removeXMLContentOfPublication()", ERROR, "kmelia.EX_IMPOSSIBLE_DE_SUPPRIMER_LE_CONTENU_XML", e); } catch (FormException e) { throw new KmeliaRuntimeException( "KmeliaBmEJB.removeXMLContentOfPublication()", ERROR, "kmelia.EX_IMPOSSIBLE_DE_SUPPRIMER_LE_CONTENU_XML", e); } } private static boolean isInteger(String id) { try { Integer.parseInt(id); return true; } catch (NumberFormatException e) { return false; } } /*****************************************************************************************************************/ /** Connection management methods used for the content service **/ /*****************************************************************************************************************/ private Connection getConnection() { try { Connection con = DBUtil.makeConnection(SILVERPEAS_DATASOURCE); return con; } catch (Exception e) { throw new KmeliaRuntimeException("KmeliaBmEJB.getConnection()", ERROR, "root.EX_CONNECTION_OPEN_FAILED", e); } } private void freeConnection(Connection con) { if (con != null) { try { con.close(); } catch (Exception e) { SilverTrace.error("kmelia", "KmeliaBmEJB.freeConnection()", "root.EX_CONNECTION_CLOSE_FAILED", "", e); } } } @Override public void addModelUsed(String[] models, String instanceId, String nodeId) { Connection con = getConnection(); try { ModelDAO.deleteModel(con, instanceId, nodeId); for (String modelId : models) { ModelDAO.addModel(con, instanceId, modelId, nodeId); } } catch (Exception e) { throw new KmeliaRuntimeException("KmeliaBmEJB.addModelUsed()", ERROR, "kmelia.IMPOSSIBLE_D_AJOUTER_LES_MODELES", e); } finally { // fermer la connexion freeConnection(con); } } @Override public Collection<String> getModelUsed(String instanceId, String nodeId) { Connection con = getConnection(); try { // get templates defined for the given node Collection<String> result = com.silverpeas.formTemplate.dao.ModelDAO.getModelUsed(con, instanceId, nodeId); if (isDefined(nodeId) && result.isEmpty()) { // there is no templates defined for the given node, check the parent nodes Collection<NodeDetail> parents = getNodeBm().getPath(new NodePK(nodeId, instanceId)); Iterator<NodeDetail> iter = parents.iterator(); while (iter.hasNext() && result.isEmpty()) { NodeDetail parent = iter.next(); result = com.silverpeas.formTemplate.dao.ModelDAO.getModelUsed(con, instanceId, parent. getNodePK().getId()); } } return result; } catch (Exception e) { throw new KmeliaRuntimeException("KmeliaBmEJB.getModelUsed()", ERROR, "kmelia.IMPOSSIBLE_DE_RECUPERER_LES_MODELES", e); } finally { // fermer la connexion freeConnection(con); } } @Override public List<NodeDetail> getAxis(String componentId) { ResourceLocator nodeSettings = new ResourceLocator( "com.stratelia.webactiv.util.node.nodeSettings", ""); String sortField = nodeSettings.getString("sortField", "nodepath"); String sortOrder = nodeSettings.getString("sortOrder", "asc"); SilverTrace.info("kmax", "KmeliaBmEjb.getAxis()", "root.MSG_GEN_PARAM_VALUE", "componentId = " + componentId + " sortField=" + sortField + " sortOrder=" + sortOrder); List<NodeDetail> axis = new ArrayList<NodeDetail>(); try { List<NodeDetail> headers = getAxisHeaders(componentId); for (NodeDetail header : headers) { // Do not get hidden nodes (Basket and unclassified) if (!NodeDetail.STATUS_INVISIBLE.equals(header.getStatus())) { // get content of this axis axis.addAll(getNodeBm().getSubTree(header.getNodePK(), sortField + " " + sortOrder)); } } } catch (Exception e) { throw new KmaxRuntimeException("KmeliaBmEJB.getAxis()", ERROR, "kmax.EX_IMPOSSIBLE_DOBTENIR_LES_AXES", e); } return axis; } @Override public List<NodeDetail> getAxisHeaders(String componentId) { List<NodeDetail> axisHeaders = null; try { axisHeaders = getNodeBm().getHeadersByLevel( new NodePK("useless", componentId), 2); } catch (Exception e) { throw new KmaxRuntimeException("KmeliaBmEJB.getAxisHeaders()", ERROR, "kmax.EX_IMPOSSIBLE_DOBTENIR_LES_ENTETES_DES_AXES", e); } return axisHeaders; } @Override public NodePK addAxis(NodeDetail axis, String componentId) { NodePK axisPK = new NodePK("toDefine", componentId); NodeDetail rootDetail = new NodeDetail(new NodePK("0"), "Root", "desc", "unknown", "unknown", "/0", 1, new NodePK("-1"), null); rootDetail.setStatus(NodeDetail.STATUS_VISIBLE); axis.setNodePK(axisPK); CoordinatePK coordinatePK = new CoordinatePK("useless", axisPK); try { // axis creation axisPK = getNodeBm().createNode(axis, rootDetail); // add this new axis to existing coordinates CoordinatePoint point = new CoordinatePoint(-1, Integer.parseInt(axisPK.getId()), true); getCoordinatesBm().addPointToAllCoordinates(coordinatePK, point); } catch (Exception e) { throw new KmeliaRuntimeException("KmeliaBmEJB.addAxis()", ERROR, "kmax.EX_IMPOSSIBLE_DE_CREER_L_AXE", e); } return axisPK; } @Override public void updateAxis(NodeDetail axis, String componentId) { axis.getNodePK().setComponentName(componentId); SilverTrace.info("kmax", "KmeliaBmEjb.updateAxis()", "root.MSG_GEN_PARAM_VALUE", "componentId = " + componentId + " nodePk.getComponentId()=" + axis.getNodePK(). getInstanceId()); try { getNodeBm().setDetail(axis); } catch (Exception e) { throw new KmaxRuntimeException("KmeliaBmEJB.updateAxis()", ERROR, "kmax.EX_IMPOSSIBLE_DE_MODIFIER_L_AXE", e); } } @Override @SuppressWarnings("unchecked") public void deleteAxis(String axisId, String componentId) { NodePK pkToDelete = new NodePK(axisId, componentId); PublicationPK pubPK = new PublicationPK("useless"); CoordinatePK coordinatePK = new CoordinatePK("useless", pkToDelete); List<String> fatherIds = new ArrayList<String>(); Collection<String> coordinateIds = null; // Delete the axis try { // delete publicationFathers if (getAxisHeaders(componentId).size() == 1) { coordinateIds = getCoordinatesBm().getCoordinateIdsByNodeId(coordinatePK, axisId); Iterator<String> coordinateIdsIt = coordinateIds.iterator(); String coordinateId = ""; while (coordinateIdsIt.hasNext()) { coordinateId = coordinateIdsIt.next(); fatherIds.add(coordinateId); } if (fatherIds.size() > 0) { getPublicationBm().removeFathers(pubPK, fatherIds); } } // delete coordinate which contains subComponents of this component Collection<NodeDetail> subComponents = getNodeBm().getDescendantDetails(pkToDelete); Iterator<NodeDetail> it = subComponents.iterator(); List<NodePK> points = new ArrayList<NodePK>(); points.add(pkToDelete); while (it.hasNext()) { points.add((it.next()).getNodePK()); } removeCoordinatesByPoints(points, componentId); // delete axis getNodeBm().removeNode(pkToDelete); } catch (Exception e) { throw new KmaxRuntimeException("KmeliaBmEJB.deleteAxis()", ERROR, "kmax.EX_IMPOSSIBLE_DE_SUPPRIMER_L_AXE", e); } } private void removeCoordinatesByPoints(List<NodePK> nodePKs, String componentId) { Iterator<NodePK> it = nodePKs.iterator(); List<String> coordinatePoints = new ArrayList<String>(); String nodeId = ""; while (it.hasNext()) { nodeId = (it.next()).getId(); coordinatePoints.add(nodeId); } CoordinatePK coordinatePK = new CoordinatePK("useless", "useless", componentId); try { getCoordinatesBm().deleteCoordinatesByPoints(coordinatePK, (ArrayList<String>) coordinatePoints); } catch (Exception e) { throw new KmaxRuntimeException("KmeliaBmEJB.removeCoordinatesByPoints()", ERROR, "kmax.EX_IMPOSSIBLE_DE_SUPPRIMER_LES_COORDONNEES_PAR_UN_POINT", e); } } @Override public NodeDetail getNodeHeader(String id, String componentId) { NodePK pk = new NodePK(id, componentId); return getNodeHeader(pk); } private NodeDetail getNodeHeader(NodePK pk) { NodeDetail nodeDetail = null; try { nodeDetail = getNodeBm().getHeader(pk); } catch (Exception e) { throw new KmaxRuntimeException("KmeliaBmEJB.getNodeHeader()", ERROR, "kmax.EX_IMPOSSIBLE_DOBTENIR_LE_NOEUD", e); } return nodeDetail; } @Override public NodePK addPosition(String fatherId, NodeDetail position, String componentId, String userId) { SilverTrace.info("kmax", "KmeliaBmEjb.addPosition()", "root.MSG_GEN_PARAM_VALUE", "fatherId = " + fatherId + " And position = " + position.toString()); position.getNodePK().setComponentName(componentId); position.setCreationDate(DateUtil.today2SQLDate()); position.setCreatorId(userId); NodeDetail fatherDetail = null; NodePK componentPK = null; fatherDetail = getNodeHeader(fatherId, componentId); SilverTrace.info("kmax", "KmeliaBmEjb.addPosition()", "root.MSG_GEN_PARAM_VALUE", "fatherDetail = " + fatherDetail.toString()); try { componentPK = getNodeBm().createNode(position, fatherDetail); } catch (Exception e) { throw new KmaxRuntimeException("KmeliaBmEjb.addPosition()", ERROR, "kmax.EX_IMPOSSIBLE_DAJOUTER_UNE_COMPOSANTE_A_L_AXE", e); } return componentPK; } @Override public void updatePosition(NodeDetail position, String componentId) { position.getNodePK().setComponentName(componentId); try { getNodeBm().setDetail(position); } catch (Exception e) { throw new KmaxRuntimeException("KmeliaBmEjb.updatePosition()", ERROR, "kmax.EX_IMPOSSIBLE_DE_MODIFIER_LA_COMPOSANTE_DE_L_AXE", e); } } @Override public void deletePosition(String positionId, String componentId) { NodePK pkToDelete = new NodePK(positionId, componentId); // Delete the axis try { // delete coordinate which contains subPositions of this position Collection<NodeDetail> subComponents = getNodeBm().getDescendantDetails(pkToDelete); Iterator<NodeDetail> it = subComponents.iterator(); List<NodePK> points = new ArrayList<NodePK>(); points.add(pkToDelete); while (it.hasNext()) { points.add((it.next()).getNodePK()); } removeCoordinatesByPoints(points, componentId); // delete component getNodeBm().removeNode(pkToDelete); } catch (Exception e) { throw new KmaxRuntimeException("KmeliaBmEjb.deletePosition()", ERROR, "kmax.EX_IMPOSSIBLE_DE_SUPPRIMER_LA_COMPOSANTE_DE_L_AXE", e); } } @Override public Collection<NodeDetail> getPath(String id, String componentId) { Collection<NodeDetail> newPath = new ArrayList<NodeDetail>(); NodePK nodePK = new NodePK(id, componentId); // compute path from a to z NodeBm nodeBm = getNodeBm(); try { List<NodeDetail> pathInReverse = (List<NodeDetail>) nodeBm.getPath(nodePK); // reverse the path from root to leaf for (int i = pathInReverse.size() - 1; i >= 0; i--) { newPath.add(pathInReverse.get(i)); } } catch (Exception e) { throw new KmaxRuntimeException("KmeliaBmEjb.getPath()", ERROR, "kmax.EX_IMPOSSIBLE_DOBTENIR_LE_CHEMIN", e); } return newPath; } public Collection<Coordinate> getKmaxPathList(PublicationPK pubPK) { SilverTrace.info("kmax", "KmeliaBmEJB.getKmaxPathList()", "root.MSG_GEN_ENTER_METHOD"); Collection<Coordinate> coordinates = null; try { coordinates = getPublicationCoordinates(pubPK.getId(), pubPK.getInstanceId()); } catch (Exception e) { throw new KmeliaRuntimeException("KmeliaBmEJB.getKmaxPathList()", ERROR, "kmelia.EX_IMPOSSIBLE_DOBTENIR_LES_EMPLACEMENTS_DE_LA_PUBLICATION", e); } return coordinates; } @Override public List<KmeliaPublication> search(List<String> combination, String componentId) { Collection<PublicationDetail> publications = searchPublications(combination, componentId); if (publications == null) { return new ArrayList<KmeliaPublication>(); } return pubDetails2userPubs(publications); } @Override public List<KmeliaPublication> search(List<String> combination, int nbDays, String componentId) { Collection<PublicationDetail> publications = searchPublications(combination, componentId); SilverTrace.info("kmax", "KmeliaBmEjb.search()", "root.MSG_GEN_PARAM_VALUE", "publications = " + publications); return pubDetails2userPubs(filterPublicationsByBeginDate(publications, nbDays)); } private Collection<PublicationDetail> searchPublications(List<String> combination, String componentId) { PublicationPK pk = new PublicationPK("useless", componentId); CoordinatePK coordinatePK = new CoordinatePK("unknown", pk); Collection<PublicationDetail> publications = null; Collection<String> coordinates = null; try { // Remove node "Toutes catégories" (level == 2) from combination int nodeLevel = 0; String axisValue = ""; for (int i = 0; i < combination.size(); i++) { axisValue = combination.get(i); StringTokenizer st = new StringTokenizer(axisValue, "/"); nodeLevel = st.countTokens(); // if node is level 2, it represents "Toutes Catégories" // this axis is not used by the search if (nodeLevel == 2) { combination.remove(i); i--; } } if (combination.isEmpty()) { // all criterias is "Toutes Catégories" // get all publications classified NodePK basketPK = new NodePK("1", componentId); publications = getPublicationBm().getDetailsNotInFatherPK(basketPK); } else { if (combination != null && combination.size() > 0) { coordinates = getCoordinatesBm().getCoordinatesByFatherPaths( (ArrayList<String>) combination, coordinatePK); } if (!coordinates.isEmpty()) { publications = getPublicationBm().getDetailsByFatherIds((ArrayList<String>) coordinates, pk, false); } } } catch (Exception e) { throw new KmaxRuntimeException("KmeliaBmEJB.search()", ERROR, "kmax.EX_IMPOSSIBLE_DOBTENIR_LA_LISTE_DES_RESULTATS", e); } return publications; } @Override public Collection<KmeliaPublication> getUnbalancedPublications(String componentId) { PublicationPK pk = new PublicationPK("useless", componentId); Collection<PublicationDetail> publications = null; try { publications = getPublicationBm().getOrphanPublications(pk); } catch (Exception e) { throw new KmaxRuntimeException("KmeliaBmEJB.getUnbalancedPublications()", ERROR, "kmax.EX_IMPOSSIBLE_DOBTENIR_LA_LISTE_DES_PUBLICATIONS_NON_CLASSEES", e); } return pubDetails2userPubs(publications); } private Collection<PublicationDetail> filterPublicationsByBeginDate( Collection<PublicationDetail> publications, int nbDays) { List<PublicationDetail> pubOK = new ArrayList<PublicationDetail>(); if (publications != null) { Calendar rightNow = Calendar.getInstance(); if (nbDays == 0) { nbDays = 1; } rightNow.add(Calendar.DATE, 0 - nbDays); Date day = rightNow.getTime(); Iterator<PublicationDetail> it = publications.iterator(); PublicationDetail pub = null; Date dateToCompare = null; while (it.hasNext()) { pub = it.next(); if (pub.getBeginDate() != null) { dateToCompare = pub.getBeginDate(); } else { dateToCompare = pub.getCreationDate(); } if (dateToCompare.compareTo(day) >= 0) { pubOK.add(pub); } } } return pubOK; } @Override public void indexKmax(String componentId) { indexAxis(componentId); indexPublications(new PublicationPK("useless", componentId)); } private void indexAxis(String componentId) { NodePK nodePK = new NodePK("useless", componentId); try { Collection<NodeDetail> nodes = getNodeBm().getAllNodes(nodePK); if (nodes != null) { for (NodeDetail nodeDetail : nodes) { if ("corbeille".equalsIgnoreCase(nodeDetail.getName()) && nodeDetail.getNodePK().isTrash()) { // do not index the bin } else { getNodeBm().createIndex(nodeDetail); } } } } catch (Exception e) { throw new KmaxRuntimeException("KmeliaBmEjb.indexAxis()", ERROR, "kmax.EX_IMPOSSIBLE_DINDEXER_LES_AXES", e); } } @Override public KmeliaPublication getKmaxPublication(String pubId, String currentUserId) { SilverTrace.info("kmax", "KmeliaBmEjb.getKmaxCompletePublication()", "root.MSG_GEN_ENTER_METHOD"); PublicationPK pubPK = null; CompletePublication completePublication = null; PublicationBm pubBm = getPublicationBm(); try { pubPK = new PublicationPK(pubId); completePublication = pubBm.getCompletePublication(pubPK); } catch (Exception e) { throw new KmaxRuntimeException( "KmeliaBmEjb.getKmaxCompletePublication()", ERROR, "kmax.EX_IMPOSSIBLE_DOBTENIR_LES_INFORMATIONS_DE_LA_PUBLICATION", e); } KmeliaPublication publication = aKmeliaPublicationFromCompleteDetail(completePublication); SilverTrace.info("kmax", "KmeliaBmEjb.getKmaxCompletePublication()", "root.MSG_GEN_EXIT_METHOD"); return publication; } @Override public Collection<Coordinate> getPublicationCoordinates(String pubId, String componentId) { SilverTrace.info("kmax", "KmeliaBmEjb.getPublicationCoordinates()", "root.MSG_GEN_ENTER_METHOD"); try { return getPublicationBm().getCoordinates(pubId, componentId); } catch (Exception e) { throw new KmaxRuntimeException("KmeliaBmEjb.getPublicationCoordinates()", ERROR, "root.MSG_GEN_PARAM_VALUE", e); } } @Override public void addPublicationToCombination(String pubId, List<String> combination, String componentId) { SilverTrace.info("kmax", "KmeliaBmEJB.addPublicationToCombination()", "root.MSG_GEN_PARAM_VALUE", "combination =" + combination.toString()); PublicationPK pubPK = new PublicationPK(pubId, componentId); CoordinatePK coordinatePK = new CoordinatePK("unknown", pubPK); try { NodeBm nodeBm = getNodeBm(); Collection<Coordinate> coordinates = getPublicationCoordinates(pubId, componentId); if (!checkCombination(coordinates, combination)) { return; } NodeDetail nodeDetail = null; // enrich combination by get ancestors Iterator<String> it = combination.iterator(); List<CoordinatePoint> allnodes = new ArrayList<CoordinatePoint>(); int i = 1; while (it.hasNext()) { String nodeId = it.next(); NodePK nodePK = new NodePK(nodeId, componentId); SilverTrace.info("kmax", "KmeliaBmEjb.addPublicationToCombination()", "root.MSG_GEN_PARAM_VALUE", "avant nodeBm.getPath() ! i = " + i); Collection<NodeDetail> path = nodeBm.getPath(nodePK); SilverTrace.info("kmax", "KmeliaBmEjb.addPublicationToCombination()", "root.MSG_GEN_PARAM_VALUE", "path for nodeId " + nodeId + " = " + path.toString()); for (NodeDetail aPath : path) { nodeDetail = aPath; String anscestorId = nodeDetail.getNodePK().getId(); int nodeLevel = nodeDetail.getLevel(); if (!nodeDetail.getNodePK().isRoot()) { CoordinatePoint point; if (anscestorId.equals(nodeId)) { point = new CoordinatePoint(-1, Integer.parseInt(anscestorId), true, nodeLevel, i); } else { point = new CoordinatePoint(-1, Integer.parseInt(anscestorId), false, nodeLevel, i); } allnodes.add(point); } } i++; } int coordinateId = getCoordinatesBm().addCoordinate(coordinatePK, allnodes); getPublicationBm().addFather(pubPK, new NodePK(String.valueOf(coordinateId), pubPK)); } catch (Exception e) { throw new KmaxRuntimeException("KmeliaBmEjb.addPublicationToCombination()", ERROR, "kmax.EX_IMPOSSIBLE_DAJOUTER_LA_PUBLICATION_A_CETTE_COMBINAISON", e); } } protected boolean checkCombination(Collection<Coordinate> coordinates, List<String> combination) { for (Coordinate coordinate : coordinates) { Collection<CoordinatePoint> points = coordinate.getCoordinatePoints(); if (points.isEmpty()) { continue; } boolean matchFound = false; for (CoordinatePoint point : points) { if (!checkPoint(point, combination)) { matchFound = false; break; } matchFound = true; } if (matchFound) { return false; } } return true; } protected boolean checkPoint(CoordinatePoint point, List<String> combination) { for (String intVal : combination) { if (Integer.parseInt(intVal) == point.getNodeId()) { return true; } } return false; } @Override public void deleteCoordinates(CoordinatePK coordinatePK, ArrayList<?> coordinates) { try { getCoordinatesBm().deleteCoordinates(coordinatePK, coordinates); } catch (Exception e) { throw new KmaxRuntimeException("KmeliaBmEJB.deleteCoordinates()", ERROR, "kmax.EX_IMPOSSIBLE_DE_SUPPRIMER_LES_COORDINATES", e); } } @Override public void deletePublicationFromCombination(String pubId, String combinationId, String componentId) { SilverTrace.info("kmax", "KmeliaBmEjb.deletePublicationFromCombination()", "root.MSG_GEN_PARAM_VALUE", "combinationId = " + combinationId); PublicationPK pubPK = new PublicationPK(pubId, componentId); NodePK fatherPK = new NodePK(combinationId, componentId); CoordinatePK coordinatePK = new CoordinatePK(combinationId, pubPK); try { // remove publication fathers getPublicationBm().removeFather(pubPK, fatherPK); // remove coordinate List<String> coordinateIds = new ArrayList<String>(); coordinateIds.add(combinationId); getCoordinatesBm().deleteCoordinates(coordinatePK, (ArrayList<?>) coordinateIds); } catch (Exception e) { throw new KmaxRuntimeException("KmeliaBmEjb.deletePublicationFromCombination()", ERROR, "kmax.EX_IMPOSSIBLE_DE_SUPPRIMER_LA_COMBINAISON_DE_LA_PUBLICATION", e); } } /** * Create a new Publication (only the header - parameters) * @param pubDetail a PublicationDetail * @return the id of the new publication * @see com.stratelia.webactiv.util.publication.model.PublicationDetail * @since 1.0 */ @Override public String createKmaxPublication(PublicationDetail pubDetail) { SilverTrace.info("kmax", "KmeliaBmEJB.createKmaxPublication()", "root.MSG_GEN_ENTER_METHOD"); PublicationPK pubPK = null; Connection con = getConnection(); // connection usefull for content // service try { // create the publication pubDetail = changePublicationStatusOnCreation(pubDetail, new NodePK("useless", pubDetail.getPK())); pubPK = getPublicationBm().createPublication(pubDetail); pubDetail.getPK().setId(pubPK.getId()); // creates todos for publishers this.createTodosForPublication(pubDetail, true); // register the new publication as a new content to content manager createSilverContent(pubDetail, pubDetail.getCreatorId()); } catch (Exception e) { throw new KmeliaRuntimeException("KmeliaBmEJB.createKmaxPublication()", ERROR, "kmelia.EX_IMPOSSIBLE_DE_CREER_LA_PUBLICATION", e); } finally { freeConnection(con); } SilverTrace.info("kmax", "KmeliaBmEJB.createKmaxPublication()", "root.MSG_GEN_EXIT_METHOD"); return pubPK.getId(); } @Override public Collection<Alias> getAlias(PublicationPK pubPK) { try { return getPublicationBm().getAlias(pubPK); } catch (Exception e) { throw new KmeliaRuntimeException("KmeliaBmEJB.getAlias()", ERROR, "kmelia.EX_IMPOSSIBLE_DAVOIR_LES_ALIAS_DE_PUBLICATION", e); } } @Override public void setAlias(PublicationPK pubPK, List<Alias> alias) { List<Alias> oldAliases = (List<Alias>) getAlias(pubPK); List<Alias> newAliases = new ArrayList<Alias>(); List<Alias> remAliases = new ArrayList<Alias>(); List<Alias> stayAliases = new ArrayList<Alias>(); // Compute the remove list for (Alias a : oldAliases) { if (!alias.contains(a)) { remAliases.add(a); } } // Compute the add and stay list for (Alias a : alias) { if (!oldAliases.contains(a)) { newAliases.add(a); } else { stayAliases.add(a); } } try { getPublicationBm().addAlias(pubPK, newAliases); getPublicationBm().removeAlias(pubPK, remAliases); } catch (RemoteException e) { throw new KmeliaRuntimeException("KmeliaBmEJB.setAlias()", ERROR, "kmelia.EX_IMPOSSIBLE_DENREGISTRER_LES_ALIAS_DE_PUBLICATION", e); } // Send subscriptions to aliases subscribers PublicationDetail pubDetail = getPublicationDetail(pubPK); String originalComponentId = pubPK.getInstanceId(); for (Alias a : newAliases) { pubDetail.getPK().setComponentName(a.getInstanceId()); // Change the instanceId to make the // right URL sendSubscriptionsNotification(new NodePK(a.getId(), a.getInstanceId()), pubDetail, false); } // restore original primary key pubDetail.getPK().setComponentName(originalComponentId); } @Override public void addAttachmentToPublication(PublicationPK pubPK, String userId, String filename, String description, byte[] contents) { String context; String path; Date creationDate = new Date(); String type = FileRepositoryManager.getFileExtension(filename); String versioning = getOrganizationController().getComponentParameterValue( pubPK.getComponentName(), "versionControl"); boolean versioningActive = "yes".equalsIgnoreCase(versioning); VersioningUtil versioningUtil = new VersioningUtil(); if (versioningActive) { context = null; path = versioningUtil.createPath(null, pubPK.getComponentName(), context); } else { context = "Images"; path = AttachmentController.createPath(pubPK.getInstanceId(), context); } String physicalName = Long.toString(creationDate.getTime()) + "." + type; String logicalName = filename; File f = new File(path + physicalName); try { FileOutputStream fos = new FileOutputStream(f); if (contents != null && contents.length > 0) { fos.write(contents); fos.close(); String mimeType = FileTypeMap.getDefaultFileTypeMap().getContentType(f); long size = contents.length; if (versioningActive) { int user_id = Integer.parseInt(userId); ForeignPK pubForeignKey = new ForeignPK(pubPK.getId(), pubPK.getComponentName()); DocumentPK docPK = new DocumentPK(-1, pubPK.getSpaceId(), pubPK.getComponentName()); Document document = new Document(docPK, pubForeignKey, logicalName, description, -1, user_id, creationDate, null, null, null, null, 0, 0); int majorNumber = 1; int minorNumber = 0; DocumentVersion newVersion = new DocumentVersion(null, docPK, majorNumber, minorNumber, user_id, creationDate, "", 0, 0, physicalName, logicalName, mimeType, (int) size, pubPK.getComponentName()); // create the document with its first version DocumentPK documentPK = getVersioningBm().createDocument(document, newVersion); document.setPk(documentPK); if (newVersion.getType() == DocumentVersion.TYPE_PUBLIC_VERSION) { CallBackManager callBackManager = CallBackManager.get(); callBackManager.invoke(CallBackManager.ACTION_VERSIONING_UPDATE, newVersion.getAuthorId(), document.getForeignKey().getInstanceId(), document. getForeignKey().getId()); PublicationDetail detail = getPublicationDetail(pubPK); if (KmeliaHelper.isIndexable(detail)) { versioningUtil.createIndex(document, newVersion); } } } else { // create AttachmentPK with componentId AttachmentPK atPK = new AttachmentPK(null, pubPK.getComponentName()); // create foreignKey with spaceId, componentId and id // use AttachmentPK to build the foreign key of customer // object. WAPrimaryKey pubForeignKey = new AttachmentPK(pubPK.getId(), pubPK.getComponentName()); // create AttachmentDetail Object AttachmentDetail ad = new AttachmentDetail(atPK, physicalName, logicalName, description, mimeType, size, context, creationDate, pubForeignKey); ad.setAuthor(userId); AttachmentController.createAttachment(ad, true); } } } catch (FileNotFoundException fnfe) { throw new KmeliaRuntimeException("KmeliaBmEJB.addAttachmentToPublication()", ERROR, "kmelia.EX_IMPOSSIBLE_DAJOUTER_ATTACHEMENT", fnfe); } catch (IOException ioe) { throw new KmeliaRuntimeException("KmeliaBmEJB.addAttachmentToPublication()", ERROR, "kmelia.EX_IMPOSSIBLE_DAJOUTER_ATTACHEMENT", ioe); } } /** * Creates or updates a publication. * @param componentId The id of the component containing the publication. * @param topicId The id of the topic containing the publication. * @param spaceId The id of the space containing the publication. * @param userId The id of the user creating or updating the publication. * @param publiParams The publication's parameters. * @param formParams The parameters of the publication's form. * @param language The language of the publication. * @param xmlFormName The name of the publication's form. * @param discrimatingParameterName The name of the field included in the form which allowes to * retrieve the eventually existing publication to update. * @param userProfile The user's profile used to draft out the publication. * @return True if the publication is created, false if it is updated. * @throws RemoteException */ @Override public boolean importPublication(String componentId, String topicId, String spaceId, String userId, Map<String, String> publiParams, Map<String, String> formParams, String language, String xmlFormName, String discrimatingParameterName, String userProfile) throws RemoteException { PublicationImport publicationImport = new PublicationImport( this, componentId, topicId, spaceId, userId); return publicationImport.importPublication(publiParams, formParams, language, xmlFormName, discrimatingParameterName, userProfile); } /** * Creates or updates a publication. * @param publicationId The id of the publication to update. * @param componentId The id of the component containing the publication. * @param topicId The id of the topic containing the publication. * @param spaceId The id of the space containing the publication. * @param userId The id of the user creating or updating the publication. * @param publiParams The publication's parameters. * @param formParams The parameters of the publication's form. * @param language The language of the publication. * @param xmlFormName The name of the publication's form. * @param userProfile The user's profile used to draft out the publication. * @return True if the publication is created, false if it is updated. * @throws RemoteException */ @Override public boolean importPublication(String publicationId, String componentId, String topicId, String spaceId, String userId, Map<String, String> publiParams, Map<String, String> formParams, String language, String xmlFormName, String userProfile) throws RemoteException { PublicationImport publicationImport = new PublicationImport( this, componentId, topicId, spaceId, userId); return publicationImport.importPublication( publicationId, publiParams, formParams, language, xmlFormName, userProfile); } @Override public void importPublications(String componentId, String topicId, String spaceId, String userId, List<Map<String, String>> publiParamsList, List<Map<String, String>> formParamsList, String language, String xmlFormName, String discrimatingParameterName, String userProfile) throws RemoteException { PublicationImport publicationImport = new PublicationImport(this, componentId, topicId, spaceId, userId); publicationImport.importPublications(publiParamsList, formParamsList, language, xmlFormName, discrimatingParameterName, userProfile); } @Override public List<XMLField> getPublicationXmlFields(String publicationId, String componentId, String spaceId, String userId) { PublicationImport publicationImport = new PublicationImport(this, componentId, null, spaceId, userId); return publicationImport.getPublicationXmlFields(publicationId); } @Override public List<XMLField> getPublicationXmlFields(String publicationId, String componentId, String spaceId, String userId, String language) { PublicationImport publicationImport = new PublicationImport( this, componentId, null, spaceId, userId); return publicationImport.getPublicationXmlFields(publicationId, language); } @Override public String createTopic(String componentId, String topicId, String spaceId, String userId, String name, String description) throws RemoteException { PublicationImport publicationImport = new PublicationImport(this, componentId, topicId, spaceId, userId); return publicationImport.createTopic(name, description); } /** * Case standard -> LogicalName take from file name * @param publicationId * @param componentId * @param userId * @param filePath * @param title * @param info * @param creationDate * @throws RemoteException */ @Override public void importAttachment(String publicationId, String componentId, String userId, String filePath, String title, String info, Date creationDate) throws RemoteException { importAttachment(publicationId, componentId, userId, filePath, title, info, creationDate, null); } /** * In case of move -> can force the logicalName * @param publicationId * @param componentId * @param userId * @param filePath * @param title * @param info * @param creationDate * @param logicalName * @throws RemoteException */ @Override public void importAttachment(String publicationId, String componentId, String userId, String filePath, String title, String info, Date creationDate, String logicalName) throws RemoteException { PublicationImport publicationImport = new PublicationImport(this, componentId); publicationImport.importAttachment(publicationId, userId, filePath, title, info, creationDate, logicalName); } @Override public void deleteAttachment(AttachmentDetail attachmentDetail) throws RemoteException { com.stratelia.webactiv.util.attachment.control.AttachmentController.deleteAttachment( attachmentDetail); } @Override public Collection<String> getPublicationsSpecificValues(String componentId, String xmlFormName, String fieldName) throws RemoteException { PublicationImport publicationImport = new PublicationImport(this, componentId); return publicationImport.getPublicationsSpecificValues(componentId, xmlFormName, fieldName); } @Override public void draftInPublication(String componentId, String xmlFormName, String fieldName, String fieldValue) throws RemoteException { PublicationImport publicationImport = new PublicationImport(this, componentId); publicationImport.draftInPublication(xmlFormName, fieldName, fieldValue); } @Override public void updatePublicationEndDate(String componentId, String spaceId, String userId, String xmlFormName, String fieldName, String fieldValue, Date endDate) throws RemoteException { PublicationImport publicationImport = new PublicationImport(this, componentId, null, spaceId, userId); publicationImport.updatePublicationEndDate(xmlFormName, fieldName, fieldValue, endDate); } /** * Find a publication imported only by a xml field (old id for example) * @param componentId * @param xmlFormName * @param fieldName * @param fieldValue * @param topicId * @param spaceId * @param userId * @return pubId * @throws RemoteException */ @Override public String findPublicationIdBySpecificValue(String componentId, String xmlFormName, String fieldName, String fieldValue, String topicId, String spaceId, String userId) throws RemoteException { PublicationImport publicationImport = new PublicationImport(this, componentId, topicId, spaceId, userId); return publicationImport.getPublicationId(xmlFormName, fieldName, fieldValue); } @Override public void doAutomaticDraftOut() { // get all clones with draftoutdate <= current date // pubCloneId <> -1 AND pubCloneStatus == 'Draft' Collection<PublicationDetail> pubs; try { pubs = getPublicationBm().getPublicationsToDraftOut(true); // for each clone, call draftOutPublication method for (PublicationDetail pub : pubs) { draftOutPublication(pub.getClonePK(), null, "admin", true); } } catch (RemoteException e) { throw new KmeliaRuntimeException( "KmeliaBmEJB.doAutomaticDraftOut()", ERROR, "kmelia.CANT_DO_AUTOMATIC_DRAFTOUT", e); } } @Override public String clonePublication(CompletePublication refPubComplete, PublicationDetail pubDetail, String nextStatus) { String cloneId = null; try { // récupération de la publi de référence PublicationDetail refPub = refPubComplete.getPublicationDetail(); String fromId = refPub.getPK().getId(); String fromComponentId = refPub.getPK().getInstanceId(); PublicationDetail clone = getClone(refPub); ResourceLocator publicationSettings = new ResourceLocator("com.stratelia.webactiv.util.publication.publicationSettings", ""); String imagesSubDirectory = publicationSettings.getString("imagesSubDirectory"); String absolutePath = FileRepositoryManager.getAbsolutePath(fromComponentId); if (pubDetail != null) { clone.setAuthor(pubDetail.getAuthor()); clone.setBeginDate(pubDetail.getBeginDate()); clone.setBeginHour(pubDetail.getBeginHour()); clone.setDescription(pubDetail.getDescription()); clone.setEndDate(pubDetail.getEndDate()); clone.setEndHour(pubDetail.getEndHour()); clone.setImportance(pubDetail.getImportance()); clone.setKeywords(pubDetail.getKeywords()); clone.setName(pubDetail.getName()); clone.setTargetValidatorId(pubDetail.getTargetValidatorId()); } if (isInteger(refPub.getInfoId())) { // Case content = DB clone.setInfoId(null); } clone.setStatus(nextStatus); clone.setCloneId(fromId); clone.setIndexOperation(IndexManager.NONE); PublicationPK clonePK = getPublicationBm().createPublication(clone); clonePK.setComponentName(fromComponentId); cloneId = clonePK.getId(); // eventually, paste the model content if (refPubComplete.getModelDetail() != null && refPubComplete.getInfoDetail() != null) { // Paste images of model if (refPubComplete.getInfoDetail().getInfoImageList() != null) { for (InfoImageDetail attachment : refPubComplete.getInfoDetail().getInfoImageList()) { String from = absolutePath + imagesSubDirectory + File.separator + attachment. getPhysicalName(); String type = attachment.getPhysicalName().substring(attachment.getPhysicalName(). lastIndexOf('.') + 1, attachment.getPhysicalName().length()); String newName = Long.toString(System.currentTimeMillis()) + "." + type; attachment.setPhysicalName(newName); String to = absolutePath + imagesSubDirectory + File.separator + newName; FileRepositoryManager.copyFile(from, to); } } // Paste model content createInfoModelDetail(clonePK, refPubComplete.getModelDetail().getId(), refPubComplete. getInfoDetail()); } else { String infoId = refPub.getInfoId(); if (infoId != null && !"0".equals(infoId) && !isInteger(infoId)) { PublicationTemplateManager templateManager = PublicationTemplateManager.getInstance(); // Content = XMLForm // register xmlForm to publication String xmlFormShortName = infoId; templateManager.addDynamicPublicationTemplate(fromComponentId + ":" + xmlFormShortName, xmlFormShortName + ".xml"); PublicationTemplate pubTemplate = templateManager.getPublicationTemplate(fromComponentId + ":" + xmlFormShortName); RecordSet set = pubTemplate.getRecordSet(); // clone dataRecord set.clone(fromId, fromComponentId, cloneId, fromComponentId); } } // paste only links, reverseLinks can't be cloned because it'is a new content not referenced // by any publication if (refPubComplete.getLinkList() != null && refPubComplete.getLinkList().size() > 0) { addInfoLinks(clonePK, refPubComplete.getLinkList()); } // paste wysiwyg WysiwygController.copy(null, fromComponentId, fromId, null, fromComponentId, cloneId, clone. getCreatorId()); // clone attachments AttachmentPK pkFrom = new AttachmentPK(fromId, fromComponentId); AttachmentPK pkTo = new AttachmentPK(cloneId, fromComponentId); AttachmentController.cloneAttachments(pkFrom, pkTo); // paste versioning documents // pasteDocuments(pubPKFrom, clonePK.getId()); // affectation de l'id du clone à la publication de référence refPub.setCloneId(cloneId); refPub.setCloneStatus(nextStatus); refPub.setStatusMustBeChecked(false); refPub.setUpdateDateMustBeSet(false); updatePublication(refPub); // paste vignette String vignette = refPub.getImage(); if (vignette != null) { ThumbnailDetail thumbDetail = new ThumbnailDetail(clone.getPK().getInstanceId(), Integer.valueOf(clone.getPK().getId()), ThumbnailDetail.THUMBNAIL_OBJECTTYPE_PUBLICATION_VIGNETTE); thumbDetail.setMimeType(refPub.getImageMimeType()); if (vignette.startsWith("/")) { thumbDetail.setOriginalFileName(vignette); } else { String thumbnailsSubDirectory = publicationSettings.getString("imagesSubDirectory"); String from = absolutePath + thumbnailsSubDirectory + File.separator + vignette; String type = FilenameUtils.getExtension(vignette); String newVignette = Long.toString(System.currentTimeMillis()) + "." + type; String to = absolutePath + thumbnailsSubDirectory + File.separator + newVignette; FileRepositoryManager.copyFile(from, to); thumbDetail.setOriginalFileName(newVignette); } new ThumbnailServiceImpl().createThumbnail(thumbDetail); } } catch (IOException e) { throw new KmeliaRuntimeException("KmeliaBmEJB.clonePublication", ERROR, "kmelia.CANT_CLONE_PUBLICATION", e); } catch (AttachmentException ae) { throw new KmeliaRuntimeException("KmeliaBmEJB.clonePublication", ERROR, "kmelia.CANT_CLONE_PUBLICATION_FILES", ae); } catch (FormException fe) { throw new KmeliaRuntimeException("KmeliaBmEJB.clonePublication", ERROR, "kmelia.CANT_CLONE_PUBLICATION_XMLCONTENT", fe); } catch (PublicationTemplateException pe) { throw new KmeliaRuntimeException("KmeliaBmEJB.clonePublication", ERROR, "kmelia.CANT_CLONE_PUBLICATION_XMLCONTENT", pe); } catch (ThumbnailException e) { throw new KmeliaRuntimeException("KmeliaBmEJB.clonePublication", ERROR, "kmelia.CANT_CLONE_PUBLICATION", e); } return cloneId; } /** * Gets a service object on the comments. * @return a DefaultCommentService instance. */ private CommentService getCommentService() { if (commentService == null) { commentService = CommentServiceFactory.getFactory().getCommentService(); } return commentService; } private ResourceLocator getMultilang() { return new ResourceLocator("org.silverpeas.kmelia.multilang.kmeliaBundle", "fr"); } public NodeDetail getRoot(String componentId, String userId) throws RemoteException { return getRoot(componentId, userId, null); } private NodeDetail getRoot(String componentId, String userId, List<NodeDetail> treeview) throws RemoteException { NodePK rootPK = new NodePK(NodePK.ROOT_NODE_ID, componentId); NodeDetail root = getNodeBm().getDetail(rootPK); setRole(root, userId); root.setChildrenDetails(getRootChildren(root, userId, treeview)); return root; } private List<NodeDetail> getRootChildren(NodeDetail root, String userId, List<NodeDetail> treeview) { String instanceId = root.getNodePK().getInstanceId(); List<NodeDetail> children = new ArrayList<NodeDetail>(); try { setAllowedSubfolders(root, userId); List<NodeDetail> nodes = (List<NodeDetail>) root.getChildrenDetails(); // set nb objects in nodes setNbItemsOfSubfolders(root, treeview, userId); NodeDetail trash = null; for (NodeDetail node : nodes) { if (node.getNodePK().isTrash()) { trash = node; } else if (node.getNodePK().isUnclassed()) { // do not return it cause it is useless } else { children.add(node); } } // adding special folder "to validate" if (isUserCanValidate(instanceId, userId)) { NodeDetail temp = new NodeDetail(); temp.getNodePK().setId("tovalidate"); temp.setName(getMultilang().getString("ToValidateShort")); if (isNbItemsDisplayed(instanceId)) { int nbPublisToValidate = getPublicationsToValidate(instanceId).size(); temp.setNbObjects(nbPublisToValidate); } children.add(temp); } // adding special folder "trash" if (isUserCanWrite(instanceId, userId)) { children.add(trash); } root.setChildrenDetails(children); } catch (RemoteException e) { throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR); } return children; } public Collection<NodeDetail> getFolderChildren(NodePK nodePK, String userId) throws RemoteException { NodeDetail node = getNodeBm().getDetail(nodePK); if (node.getNodePK().isRoot()) { node.setChildrenDetails(getRootChildren(node, userId, null)); } else { setAllowedSubfolders(node, userId); } // set nb objects in nodes setNbItemsOfSubfolders(node, null, userId); return node.getChildrenDetails(); } private void setNbItemsOfSubfolders(NodeDetail node, List<NodeDetail> treeview, String userId) throws RemoteException { String instanceId = node.getNodePK().getInstanceId(); if (isNbItemsDisplayed(instanceId)) { if (treeview == null) { treeview = getTreeview(node.getNodePK(), userId); } // set nb objects in each nodes setNbItemsOfFolders(instanceId, node.getChildrenDetails(), treeview); } } private List<NodeDetail> getTreeview(NodePK pk, String userId) throws RemoteException { String instanceId = pk.getInstanceId(); if (isUserComponentAdmin(instanceId, userId)) { return getTreeview(pk, "admin", isCoWritingEnable(instanceId), isDraftVisibleWithCoWriting(), userId, isNbItemsDisplayed(instanceId), false); } else { return getTreeview(pk, getUserTopicProfile(pk, userId), isCoWritingEnable(instanceId), isDraftVisibleWithCoWriting(), userId, isNbItemsDisplayed(instanceId), isRightsOnTopicsEnabled(instanceId)); } } private void setNbItemsOfFolders(String componentId, Collection<NodeDetail> nodes, List<NodeDetail> treeview) throws RemoteException { if (isNbItemsDisplayed(componentId)) { for (NodeDetail child : nodes) { int index = treeview.indexOf(child); if (index != -1) { child.setNbObjects(treeview.get(index).getNbObjects()); } } } } private void setAllowedSubfolders(NodeDetail node, String userId) throws RemoteException { String instanceId = node.getNodePK().getInstanceId(); if (isRightsOnTopicsEnabled(instanceId)) { if (isUserComponentAdmin(instanceId, userId)) { // user is admin of application, all folders must be shown setRole(node.getChildrenDetails(), userId); } else { Collection<NodeDetail> allowedChildren = getAllowedSubfolders(node, userId); setRole(allowedChildren, userId); node.setChildrenDetails(allowedChildren); } } else { // no rights are used // keep children as they are } } private boolean isUserComponentAdmin(String componentId, String userId) { return "admin".equalsIgnoreCase(KmeliaHelper.getProfile(getUserRoles(componentId, userId))); } private void setRole(NodeDetail node, String userId) throws RemoteException { if (isRightsOnTopicsEnabled(node.getNodePK().getInstanceId())) { node.setUserRole(getUserTopicProfile(node.getNodePK(), userId)); } } private void setRole(Collection<NodeDetail> nodes, String userId) throws RemoteException { for (NodeDetail node : nodes) { setRole(node, userId); } } private boolean isRightsOnTopicsEnabled(String componentId) { return StringUtil.getBooleanValue(getOrganizationController().getComponentParameterValue( componentId, InstanceParameters.rightsOnFolders)); } private boolean isNbItemsDisplayed(String componentId) { return StringUtil.getBooleanValue(getOrganizationController().getComponentParameterValue( componentId, InstanceParameters.displayNbItemsOnFolders)); } private boolean isCoWritingEnable(String componentId) { return StringUtil.getBooleanValue(getOrganizationController().getComponentParameterValue( componentId, InstanceParameters.coWriting)); } private boolean isDraftVisibleWithCoWriting() { return getSettings().getBoolean("draftVisibleWithCoWriting", false); } public String getUserTopicProfile(NodePK pk, String userId) throws RemoteException { if (!isRightsOnTopicsEnabled(pk.getInstanceId())) { return KmeliaHelper.getProfile(getUserRoles(pk.getInstanceId(), userId)); } NodeDetail node = getNodeHeader(pk.getId(), pk.getInstanceId()); // check if we have to take care of topic's rights if (node != null && node.haveRights()) { int rightsDependsOn = node.getRightsDependsOn(); return KmeliaHelper.getProfile(getOrganizationController().getUserProfiles(userId, pk.getInstanceId(), rightsDependsOn, ObjectType.NODE)); } else { return KmeliaHelper.getProfile(getUserRoles(pk.getInstanceId(), userId)); } } private String[] getUserRoles(String componentId, String userId) { return getOrganizationController().getUserProfiles(userId, componentId); } private NodePK getRootPK(String componentId) { return new NodePK(NodePK.ROOT_NODE_ID, componentId); } public boolean isUserCanValidate(String componentId, String userId) throws RemoteException { if (KmeliaHelper.isToolbox(componentId)) { return false; } String profile = KmeliaHelper.getProfile(getUserRoles(componentId, userId)); boolean isPublisherOrAdmin = SilverpeasRole.admin.isInRole(profile) || SilverpeasRole.publisher.isInRole(profile); if (!isPublisherOrAdmin && isRightsOnTopicsEnabled(componentId)) { // check if current user is publisher or admin on at least one descendant Iterator<NodeDetail> descendants = getNodeBm().getDescendantDetails(getRootPK(componentId)).iterator(); while (!isPublisherOrAdmin && descendants.hasNext()) { NodeDetail descendant = descendants.next(); AdminController admin = null; if (descendant.haveLocalRights()) { // check if user is admin or publisher on this topic if (admin == null) { admin = new AdminController(userId); } String[] profiles = admin.getProfilesByObjectAndUserId(descendant.getId(), ObjectType.NODE.getCode(), componentId, userId); if (profiles != null && profiles.length > 0) { List<String> lProfiles = Arrays.asList(profiles); isPublisherOrAdmin = lProfiles.contains(SilverpeasRole.admin.name()) || lProfiles.contains(SilverpeasRole.publisher.name()); } } } } return isPublisherOrAdmin; } public boolean isUserCanWrite(String componentId, String userId) throws RemoteException { String profile = KmeliaHelper.getProfile(getUserRoles(componentId, userId)); boolean userCanWrite = SilverpeasRole.admin.isInRole(profile) || SilverpeasRole.publisher.isInRole(profile) || SilverpeasRole.writer.isInRole(profile); if (!userCanWrite && isRightsOnTopicsEnabled(componentId)) { // check if current user is publisher or admin on at least one descendant Iterator<NodeDetail> descendants = getNodeBm().getDescendantDetails(getRootPK(componentId)).iterator(); while (!userCanWrite && descendants.hasNext()) { NodeDetail descendant = descendants.next(); AdminController admin = null; if (descendant.haveLocalRights()) { // check if user is admin, publisher or writer on this topic if (admin == null) { admin = new AdminController(userId); } String[] profiles = admin.getProfilesByObjectAndUserId(descendant.getId(), ObjectType.NODE.getCode(), componentId, userId); if (profiles != null && profiles.length > 0) { List<String> lProfiles = Arrays.asList(profiles); userCanWrite = lProfiles.contains(SilverpeasRole.admin.name()) || lProfiles.contains(SilverpeasRole.publisher.name()) || lProfiles.contains(SilverpeasRole.writer.name()); } } } } return userCanWrite; } public NodeDetail getExpandedPathToNode(NodePK pk, String userId) throws RemoteException { String instanceId = pk.getInstanceId(); List<NodeDetail> nodes = new ArrayList<NodeDetail>(getNodeBm().getPath(pk)); Collections.reverse(nodes); NodeDetail root = nodes.remove(0); List<NodeDetail> treeview = null; if (isNbItemsDisplayed(instanceId)) { treeview = getTreeview(getRootPK(instanceId), userId); } root = getRoot(instanceId, userId, treeview); // set nb objects in nodes if (treeview != null) { // set nb objects on root root.setNbObjects(treeview.get(0).getNbObjects()); // set nb objects in each allowed nodes setNbItemsOfFolders(instanceId, nodes, treeview); } NodeDetail currentNode = root; for (NodeDetail node : nodes) { currentNode = find(currentNode.getChildrenDetails(), node); // get children of each node on path to target node Collection<NodeDetail> children = getNodeBm().getChildrenDetails(node.getNodePK()); node.setChildrenDetails(children); setAllowedSubfolders(node, userId); if (treeview != null) { setNbItemsOfSubfolders(node, treeview, userId); } currentNode.setChildrenDetails(node.getChildrenDetails()); } return root; } private NodeDetail find(Collection<NodeDetail> nodes, NodeDetail toFind) { for (NodeDetail node : nodes) { if (node.getNodePK().getId().equals(toFind.getNodePK().getId())) { return node; } } return null; } }
agpl-3.0
diqube/diqube
diqube-data/src/test/java/org/diqube/data/types/lng/compression/RunLengthWithBitEfficientRatioTest.java
3955
/** * diqube: Distributed Query Base. * * Copyright (C) 2015 Bastian Gloeckle * * This file is part of diqube. * * diqube 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.diqube.data.types.lng.compression; import org.diqube.data.types.lng.array.BitEfficientLongArray; import org.diqube.data.types.lng.array.RunLengthLongArray; import org.diqube.data.types.lng.array.TransitiveExplorableCompressedLongArray.TransitiveCompressionRatioCalculator; import org.testng.Assert; import org.testng.annotations.Test; /** * Tests compression ratios calculated by a combination of {@link RunLengthLongArray} with a * {@link BitEfficientLongArray}. * * @author Bastian Gloeckle */ public class RunLengthWithBitEfficientRatioTest { @Test public void withMinValueZeroTest() { long[] inputArray = new long[] { Long.MIN_VALUE, 0 }; double avgNumberOfBitsPerValue = 33.5; // BitEfficient stores '0' with 1 bit, the MIN_VALUE (special case!) with 64, // makes a avg of 32.5; additional 1 bit length encoding. assertRatio(inputArray, avgNumberOfBitsPerValue); } @Test public void withMinValueZeroPlus1Test() { long[] inputArray = new long[] { Long.MIN_VALUE + 1, 0 }; double avgNumberOfBitsPerValue = 65.; // BitEfficient does not use special case for MIN_VALUE+1 -> both 0 and // MIN_VALUE+1 are represented with 64 bits, additional 1 bit length assertRatio(inputArray, avgNumberOfBitsPerValue); } @Test public void withMaxValueZeroTest() { long[] inputArray = new long[] { 0, Long.MAX_VALUE }; double avgNumberOfBitsPerValue = 64.; assertRatio(inputArray, avgNumberOfBitsPerValue); } @Test public void withMinusOneToOneTest() { long[] inputArray = new long[] { -1, 0, 1 }; double avgNumberOfBitsPerValue = 3.; assertRatio(inputArray, avgNumberOfBitsPerValue); } @Test public void threeZeros() { long[] inputArray = new long[] { 0, 0, 0, 0, 1 }; int newLengthOfArrays = 2; // both "count" and "value" array have 2 entries. double avgNumberOfBitsPerValue = newLengthOfArrays * 4. / inputArray.length; // 1 bit value, 3 bits length assertRatio(inputArray, avgNumberOfBitsPerValue); } /** * Assert compression ratio */ private void assertRatio(long[] inputArray, double avgNumberOfBitsPerValue) { TransitiveCompressionRatioCalculator calculator = new TransitiveCompressionRatioCalculator() { @Override public double calculateTransitiveCompressionRatio(long min, long secondMin, long max, long size) { int numberOfMinValue = 0; if (min == Long.MIN_VALUE) { numberOfMinValue++; min = secondMin; } return BitEfficientLongArray.calculateApproxCompressionRatio(min, max, (int) size, numberOfMinValue); } }; RunLengthLongArray longArray = new RunLengthLongArray(); double ratioSorted = longArray.expectedCompressionRatio(inputArray, true, calculator); double ratioUnsorted = longArray.expectedCompressionRatio(inputArray, false, calculator); Assert.assertEquals(ratioUnsorted, ratioSorted, 0.001, "Sorted ratio should be equal to unsorted"); Assert.assertEquals(ratioUnsorted, avgNumberOfBitsPerValue / 64., 0.001, "Expected different ratio"); } }
agpl-3.0
guerrerocarlos/fiware-IoTAgent-Cplusplus
src/thinkingthings/TTService.cpp
15737
/** * Copyright 2015 Telefonica Investigación y Desarrollo, S.A.U * * This file is part of iotagent project. * * iotagent 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. * * iotagent 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 iotagent. If not, see http://www.gnu.org/licenses/. * * For those usages not covered by the GNU Affero General Public License * please contact with iot_support at tid dot es */ #include "TTService.h" #include <TDA.h> #include <ESP_SBC_Command.h> #include "services/admin_service.h" #include <pion/http/response_writer.hpp> #include <pion/algorithm.hpp> #include <boost/property_tree/xml_parser.hpp> #include "QueryContextWrapper.h" #include "SearchResponse.h" #include "DecodeTTJSON.h" #include "util/iota_exception.h" namespace iota { extern std::string logger; extern std::string URL_BASE; } extern iota::AdminService* AdminService_ptr; ESPLib* iota::esp::TTService::esplib_instance = NULL; ESPLib* iota::esp::TTService::getESPLib() { if (TTService::esplib_instance == NULL) { esplib_instance = new ESPLib(); } return esplib_instance; } iota::esp::TTService::TTService() : m_logger(PION_GET_LOGGER(iota::logger)) { std::cout << "esp::TTService " << std::endl; IOTA_LOG_DEBUG(m_logger,"iota::esp::TTService Running... "); _protocol_data.description = "Thinking Things Protocol"; _protocol_data.protocol = "PDI-IoTA-ThinkingThings"; //iota::tt::TTCBPublisher* cbPubImpl = new iota::tt::TTCBPublisher(); contextBrokerPub.reset(new iota::tt::TTCBPublisher()); idSensor = -1; tt_post_ptr_ = new ESP_Postprocessor_TT(); tt_post_ptr_->load_default_TTModules(); } iota::esp::TTService::TTService(boost::shared_ptr<iota::tt::TTCBPublisher> cbPub) : m_logger( PION_GET_LOGGER(iota::logger)) { _protocol_data.description = "Thinking Things Protocol"; _protocol_data.protocol = "PDI-IoTA-ThinkingThings"; contextBrokerPub = cbPub; idSensor = -1; tt_post_ptr_ = new ESP_Postprocessor_TT(); tt_post_ptr_->load_default_TTModules(); } iota::esp::TTService::~TTService() { //dtor //contextBrokerPub.reset(); iota::esp::TTService::getESPLib()->stopSensor(idSensor); iota::esp::TTService::getESPLib()->destroySensor(idSensor); } int iota::esp::TTService::initESPLib(std::string& pathToLog, std::string& sensorFile) { iota::esp::TTService::getESPLib()->setLoggerPath(pathToLog); if (iota::esp::TTService::getESPLib()->sensors.size() == 0) { int sensorid = iota::esp::TTService::getESPLib()->createSensor(sensorFile); if (sensorid >= 0) { return sensorid; } } else { IOTA_LOG_ERROR(m_logger, "Unexpected call to initESPLib. There are some sensors already in use: " << iota::esp::TTService::getESPLib()->sensors.size()); return -1; } } void iota::esp::TTService::set_option(const std::string& name, const std::string& value) { if (name.compare("ConfigFile") == 0) { IOTA_LOG_DEBUG(m_logger,"Reading Config File: " << value); try { read_xml(value, _service_configuration, boost::property_tree::xml_parser::no_comments); IOTA_LOG_DEBUG(m_logger,"XML READ"); std::string sensors = _service_configuration.get<std::string>("Sensors"); IOTA_LOG_DEBUG(m_logger,"Sensors: " << sensors); // Set LogPath std::string logpath = _service_configuration.get<std::string>("LogPath"); idSensor = initESPLib(logpath,sensors); } catch (boost::exception& e) { IOTA_LOG_DEBUG(m_logger,"boost::exception while parsing Config File "); } catch (std::exception& e) { IOTA_LOG_DEBUG(m_logger,"std::exception: " << e.what()); } } else { IOTA_LOG_DEBUG(m_logger,"OPTION: " << name << " IS UNKNOWN"); iota::RestHandle::set_option(name, value); } } void iota::esp::TTService::start() { std::cout << "START PLUGINESP" << std::endl; std::map<std::string, std::string> filters; add_url("", filters, REST_HANDLE(&iota::esp::TTService::service), this); //enable_ngsi_service(filters, REST_HANDLE(&iota::esp::TTService::service), this); } void iota::esp::TTService::service(pion::http::request_ptr& http_request_ptr, std::map<std::string, std::string>& url_args, std::multimap<std::string, std::string>& query_parameters, pion::http::response& http_response, std::string& response) { //Here is where I am going to place the code for doing three main things: //1. Parse input and get parameters, //2. Query the CB to get what I need to response to the device (HTTP Response) //3. Create NGSI publication. IOTA_LOG_DEBUG(m_logger, "TT: service "); std::string keyword("cadena"); std::string apikey; boost::property_tree::ptree pt_cb; std::string cb_url; std::string strResponse; boost::system::error_code error_code; int code_resp = pion::http::types::RESPONSE_CODE_OK; std::string strBuffer; int contentLength; std::string method = http_request_ptr->get_method(); std::string orig_resource = http_request_ptr->get_original_resource(); IOTA_LOG_DEBUG(m_logger, method << ":" << orig_resource); try { //strBuffer.assign(http_request_ptr->get_content()); strBuffer.assign(pion::algorithm::url_decode(http_request_ptr->get_content())); IOTA_LOG_DEBUG(m_logger, "TT Request received: [" << strBuffer << "]"); http_response.set_status_code(pion::http::types::RESPONSE_CODE_OK); response.assign(strBuffer);//Just to returns something in case of failure. //Now, ESPlib takes over: if (idSensor <= 0) { IOTA_LOG_ERROR(m_logger, "ESPlib was not started properly, nothing will be done."); http_response.set_status_code(500); http_response.set_status_message("IoTAgent not properly initialized"); response.assign("Error on ESPlib"); return; } std::map<std::string, std::string> params; params.clear(); ESP_Result mainResult = getESPLib()->executeRunnerFromBuffer(idSensor, "main", params, (char*)strBuffer.c_str(), strBuffer.length()); //get device-id. std::string device_id = mainResult.findInputAttributeAsString("request", true); //The keyword "request" is defined somewhere in the ESP Xml file, how could I get it? if (device_id != "") { boost::property_tree::ptree pt_cb; //add_info(pt_cb, get_resource(), ""); IOTA_LOG_DEBUG(m_logger, "TTService: Getting searching device : [" << device_id << "]"); boost::shared_ptr<Device> dev = get_device(device_id); if (dev.get() == NULL) { IOTA_LOG_ERROR(m_logger, "TTService: device : [" << device_id << "] Not FOUND"); std::string reason("Error: Device "); reason.append(device_id); reason.append(" not found"); http_response.set_status_code(404); //response.assign(reason); throw iota::IotaException("Not Found",reason,404); } std::string service_tt(dev->_service); std::string sub_service(dev->_service_path); IOTA_LOG_DEBUG(m_logger, "TTService: Getting info: Service: [" << service_tt << "] sub service ["<<sub_service<<"]"); get_service_by_name(pt_cb,service_tt, sub_service);//this replaces old "add_info" call to populate ptree. iota::esp::tt::SearchResponse seeker = iota::esp::tt::SearchResponse(); iota::esp::tt::QueryContextWrapper* queryC = new iota::esp::tt::QueryContextWrapper( &pt_cb); IOTA_LOG_DEBUG(m_logger, "TTService: Creating entity to be published: Service: [" << service_tt << "]"); //This values will be overwritten later on. ::iota::ContextElement cElem(device_id, "", "false"); cElem.set_env_info(pt_cb, dev); IOTA_LOG_DEBUG(m_logger, "TTService: Creating entity : [" << cElem.get_string() << "]"); //call to populate internal fields from cache, or by default, etc... not interesated in result //TWO vectors. std::vector <CC_AttributesType> attributes_result; std::string temp; std::vector<std::string> vJsonTT_Plain; //This would be published to CB if no previous entries are found. std::vector<std::string> vJsonTT_Processed; //This is the "normal" processed (with some prefixes) JSON of TT Attributes. iota::esp::tt::DecodeTTJSON* decodeTT = new iota::esp::tt::DecodeTTJSON(); std::string module; for(int i=0;i<mainResult.attresults.size();i++){ CC_AttributesType::iterator itModule = mainResult.attresults[i].find("module"); if (itModule == mainResult.attresults[i].end()) { IOTA_LOG_WARN(m_logger,"TTService: Missing keyword: [module] in parser's output device: ["<< device_id <<"]"); continue; } tt_post_ptr_->initialize(); tt_post_ptr_->execute(&mainResult.attresults[i]); module.assign(itModule->second.getValueAsString()); if (module == "K1"){ attributes_result.push_back(mainResult.attresults[i]); }else if (!tt_post_ptr_->isResultValid()) { IOTA_LOG_ERROR(m_logger, "TTService: ERROR-TT while processing module [" <<module << "] for id_device ["<< device_id<<"] " ); }else{ IOTA_LOG_DEBUG(m_logger, "TTService: adding module to response processing : [" << module << "]"); attributes_result.push_back(mainResult.attresults[i]); temp.assign(tt_post_ptr_->getResultData()); decodeTT->parse(temp); vJsonTT_Processed.push_back(decodeTT->getProcessedJSON()); vJsonTT_Plain.push_back(decodeTT->getPlainJSON()); IOTA_LOG_DEBUG(m_logger, "TTService: JSONS: [" << decodeTT->getPlainJSON() << "]"); } tt_post_ptr_->terminate(); } delete decodeTT; if (attributes_result.size() == 0){ IOTA_LOG_WARN(m_logger,"TTService: ignoring CB operations due to no valid modules found on the request for device:["<<device_id<<"]"); response.assign(""); return; } response.assign(seeker.searchTTResponse(attributes_result, cElem.get_id(), cElem.get_type(), queryC)); IOTA_LOG_DEBUG(m_logger, "TTService: Response after QueryContext: [" << response << "]"); iota::RiotISO8601 timeInstant; std::string responseCB; //no Response was found for the TT request. if (response == "") { //Need to publish new Attribute IOTA_LOG_DEBUG(m_logger, "TTService: No previous entries were found for these attributes, so publishing for the first time."); ::iota::ContextElement cElemNew(device_id, "", "false"); //This values will be overwritten later on. cElemNew.set_env_info(pt_cb, dev); cElemNew.get_string(); //call to populate internal fields from cache, or by default, etc... not interesated in result IOTA_LOG_DEBUG(m_logger, "TTService: About to publish on CB for the First Time"); responseCB.assign(contextBrokerPub->publishContextBroker(cElemNew, vJsonTT_Plain, pt_cb, timeInstant)); IOTA_LOG_DEBUG(m_logger, "TTService: Response from CB after Publishing FIRST TIME TT Events [" << responseCB << "]"); //Now quering the CB again... although I should get the same I just posted, just in case a real change happens in between. response.assign(seeker.searchTTResponse(attributes_result, cElemNew.get_id(), cElemNew.get_type(), queryC)); //response is what needs to be sent to the device. //What should I do if I get another 404 or empty response after publishing? is this even possible? if (response == ""){ IOTA_LOG_ERROR(m_logger,"TTService: unexpected empty response from ContextBroker."); http_response.set_status_code(500); throw iota::IotaException("Empty response from CB","An unexpected empty response received from ContextBroker. Entity was not published",500); } } //else, response is sent to device. //In anycase, as I have some message from the TT Device, I have to populate the ContextElement and send it to CB. //Get the response, and log it. responseCB.assign(contextBrokerPub->publishContextBroker(cElem, vJsonTT_Processed, pt_cb, timeInstant)); IOTA_LOG_DEBUG(m_logger, "TTService: Response from CB after Publishing received TT Events [" << responseCB << "]"); } else { IOTA_LOG_ERROR(m_logger, "[request] keyword not found in incoming TT message."); http_response.set_status_code(400); http_response.set_status_message("Bad Request"); response.assign("Error: TT message not properly formatted"); //throw new std::runtime_error("TT message not processed."); } } catch (iota::IotaException& ex) { IOTA_LOG_ERROR(m_logger, "Error: ["<<ex.what()<<"]"); http_response.set_status_message("IoTAgent Error"); response.assign(ex.what()); } catch (std::runtime_error& excep) { IOTA_LOG_ERROR(m_logger, "An error has occured and the message couldn't get processed."); http_response.set_status_code(500); http_response.set_status_message("IoTAgent Internal Error"); response.assign(excep.what()); } } void iota::esp::TTService::add_info(boost::property_tree::ptree& pt, const std::string& iotService, const std::string& apiKey) { try { get_service_by_apiKey(pt, apiKey); //TODO: this has to change, as it's not going to work anymore. std::string timeoutSTR = pt.get<std::string>("timeout", "0"); int timeout = boost::lexical_cast<int>(timeoutSTR); std::string service = pt.get<std::string>("service", ""); std::string service_path = pt.get<std::string>("service_path", ""); std::string token = pt.get<std::string>("token", ""); IOTA_LOG_DEBUG(m_logger, "Config retrieved: token: "<< token <<" service_path: "<< service_path); pt.put("timeout", timeout); pt.put("service", service); pt.put("service_path", service_path); } catch (std::exception& e) { IOTA_LOG_ERROR(m_logger, "Configuration error for service: " << iotService << " [" << e.what() << "] "); throw e; } } // creates new miplugin objects // extern "C" PION_PLUGIN iota::esp::TTService* pion_create_TTService(void) { return new iota::esp::TTService(); } /// destroys miplugin objects extern "C" PION_PLUGIN void pion_destroy_TTService(iota::esp::TTService* service_ptr) { delete service_ptr; }
agpl-3.0
ByersHouse/crmwork
cache/smarty/templates_c/%%F9^F9D^F9DE01E7%%DetailView.tpl.php
3407
<?php /* Smarty version 2.6.29, created on 2017-10-10 17:32:58 compiled from include/SugarFields/Fields/Float/DetailView.tpl */ ?> <?php require_once(SMARTY_CORE_DIR . 'core.load_plugins.php'); smarty_core_load_plugins(array('plugins' => array(array('function', 'sugarvar', 'include/SugarFields/Fields/Float/DetailView.tpl', 41, false),array('function', 'sugarvar_connector', 'include/SugarFields/Fields/Float/DetailView.tpl', 45, false),)), $this); ?> {* /********************************************************************************* * SugarCRM Community Edition is a customer relationship management program developed by * SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc. * SuiteCRM is an extension to SugarCRM Community Edition developed by Salesagility Ltd. * Copyright (C) 2011 - 2014 Salesagility Ltd. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by the * Free Software Foundation with the addition of the following permission added * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * 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 or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. * * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road, * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License version 3, * these Appropriate Legal Notices must retain the display of the "Powered by * SugarCRM" logo and "Supercharged by SuiteCRM" logo. If the display of the logos is not * reasonably feasible for technical reasons, the Appropriate Legal Notices must * display the words "Powered by SugarCRM" and "Supercharged by SuiteCRM". ********************************************************************************/ *} <span class="sugar_field" id="<?php if (empty ( $this->_tpl_vars['displayParams']['idName'] )): ?><?php echo smarty_function_sugarvar(array('key' => 'name'), $this);?> <?php else: ?><?php echo $this->_tpl_vars['displayParams']['idName']; ?> <?php endif; ?>"> {sugar_number_format var=<?php echo smarty_function_sugarvar(array('key' => 'value','stringFormat' => 'false'), $this);?> <?php if (isset ( $this->_tpl_vars['vardef']['precision'] )): ?>precision=<?php echo $this->_tpl_vars['vardef']['precision']; ?> <?php endif; ?> } </span> <?php if (! empty ( $this->_tpl_vars['displayParams']['enableConnectors'] )): ?> <?php echo smarty_function_sugarvar_connector(array('view' => 'DetailView'), $this);?> <?php endif; ?>
agpl-3.0
coder-molok/foowd_alpha2
mod_elgg/foowd_theme/assets/grid-loading/js/AnimOnScroll.js
10228
/** * animOnScroll.js v1.0.0 * http://www.codrops.com * * Licensed under the MIT license. * http://www.opensource.org/licenses/mit-license.php * * Copyright 2013, Codrops * http://www.codrops.com * * Versione dello script modificata al fine di concedere maggiore interazione con Masonry */ ;( function( window ) { 'use strict'; var docElem = window.document.documentElement; /* ritorna la concreta altezza a disposizione */ function getViewportH() { var client = docElem['clientHeight'], // the viewable height of an element in pixels, including padding, but not the border, scrollbar or margin. inner = window['innerHeight']; // altezza interna della finestra, ovvero senza tollbars/scrollbars (height of the browser window's viewpor) if( client < inner ) return inner; else return client; } function scrollY() { // pagYoffset: the pixels the current document has been scrolled from the upper left corner of the window, horizontally and vertically. // scrollTop: sets or returns the number of pixels an element's content is scrolled vertically var y = window.pageYOffset || docElem.scrollTop; return window.pageYOffset || docElem.scrollTop; } // http://stackoverflow.com/a/5598797/989439 // con questo controlla l'offset Totale: function getOffset( el ) { var offsetTop = 0, offsetLeft = 0; do { if ( !isNaN( el.offsetTop ) ) { offsetTop += el.offsetTop; } if ( !isNaN( el.offsetLeft ) ) { offsetLeft += el.offsetLeft; } } while( el = el.offsetParent ) // console.log({ // top : offsetTop, // left : offsetLeft // }); return { top : offsetTop, left : offsetLeft } } // per ciascun elemento controllo se e' nella viewport o meno (ovvero se e' o e' stato nella zona visibile); // se lo e' ritorna true function inViewport( el, h ) { var elH = el.offsetHeight, scrolled = scrollY(), viewed = scrolled + getViewportH(), elTop = getOffset(el).top, elBottom = elTop + elH, // if 0, the element is considered in the viewport as soon as it enters. // if 1, the element is considered in the viewport only when it's fully inside // value in percentage (1 >= h >= 0) h = h || 0; return (elTop + elH * h) <= viewed && (elBottom - elH * h) >= scrolled; } function extend( a, b ) { for( var key in b ) { if( b.hasOwnProperty( key ) ) { a[key] = b[key]; } } return a; } function AnimOnScroll( el, options ) { this.el = el; this.options = extend( this.defaults, options ); var start = this._init(true); for(var i in start) this[i] = start[i]; } // IE Fallback for array prototype slice if(navigator.appVersion.indexOf('MSIE 8') > 0) { var _slice = Array.prototype.slice; Array.prototype.slice = function() { if(this instanceof Array) { return _slice.apply(this, arguments); } else { var result = []; var start = (arguments.length >= 1) ? arguments[0] : 0; var end = (arguments.length >= 2) ? arguments[1] : this.length; for(var i=start; i<end; i++) { result.push(this[i]); } return result; } }; } AnimOnScroll.prototype = { defaults : { // Minimum and a maximum duration of the animation (random value is chosen) minDuration : 0, maxDuration : 0, // The viewportFactor defines how much of the appearing item has to be visible in order to trigger the animation // if we'd use a value of 0, this would mean that it would add the animation class as soon as the item is in the viewport. // If we were to use the value of 1, the animation would only be triggered when we see all of the item in the viewport (100% of it) viewportFactor : 0, }, // first time prepare all functions and listeners _init : function() { this.create = true; this.items = Array.prototype.slice.call( document.querySelectorAll( '#' + this.el.id + ' > li' ) ); this.itemsCount = this.items.length; this.itemsRenderedCount = 0; this.didScroll = false; // parametro utilizzato nello scroll per controllarlo: funge da semaforo per non sovrastare gli scroll $.bridget('masonry', Masonry); var self = this; if( !this.create ) return; this.create =! this.create; // $(self.el).masonry('destroy'); self.$grid = $(self.el).masonry({ itemSelector: 'li', transitionDuration : 0, isFitWidth : true, resize: true, initLayout: false, } ); imagesLoaded( this.el, function() { // avendo caricato come dipendenza jquery-bridget, riesco anche con requirejs a utilizzare masonry come plugin jquery. Lo faccio per comodita' // utilizzo masonry appendendolo all'oggetto giglia // console.log() self.$grid.masonry('layout'); // self.$grid = $(self.el); // self.masonry = new Masonry(self.el, { // itemSelector: 'li', // transitionDuration : '0.4s', // isFitWidth : true, // fitWidth: true, // resize: true // } ); if( Modernizr.cssanimations ) { // the items already shown... self.items.forEach( function( el, i ) { if( inViewport( el ) ) { self._checkTotalRendered(); classie.add( el, 'shown' ); } } ); // animate on scroll the items inside the viewport window.addEventListener( 'scroll', function() { self._onScrollFn(); }, false ); window.addEventListener( 'resize', function() { self._resizeHandler(); }, false ); } self._foowdEvent(); }); // per accedere ai suoi elementi... un po forzato return { 'removeElement': this.removeElement, 'appendElement': this.appendElement, 'prependElement': this.prependElement, 'update' : this._update, '$grid' : this.$grid }; }, _foowdEvent : function(){ // predo -------------------------- //custom event to see when images are loaded var event; var self = this; if (document.createEvent) { event = document.createEvent("HTMLEvents"); event.initEvent("images-loaded", true, true); } else { event = document.createEventObject(); event.eventType = "images-loaded"; } event.eventName = "images-loaded"; if (document.createEvent) { self.event = event; self.el.dispatchEvent(event); } else { self.el.fireEvent("on" + event.eventType, event); } //predo --------------------------- }, // call this when manage items. items in questo caso e' un array di elementi che voglio visualizzare. Se e' vuoto, allora visualizzo tutta la griglia _update : function(){ // aggiorno per i check che svolge il plugin al fine di applicare gli effetti this.items = Array.prototype.slice.call( document.querySelectorAll( '#' + this.el.id + ' > li' ) ); this.itemsCount = this.items.length; this.itemsRenderedCount = 0; this.didScroll = false; // parametro utilizzato nello scroll per controllarlo: funge da semaforo per non sovrastare gli scroll var self = this; imagesLoaded( this.el, function() { // $elements.each(function(){ // self.$grid.prepend($(this)).masonry('prepended', $(this)); // }) // console.log(self.$grid.masonry('getItemElements', $blockSelectors)); // self.$grid.masonry('layout'); if( Modernizr.cssanimations ) { // the items already shown... self.items.forEach( function( el, i ) { if( inViewport( el ) ) { self._checkTotalRendered(); classie.add( el, 'shown' ); } } ); } self._foowdEvent(); }); }, removeElement : function(Jel){ // se sto provando a eliminare qualcosa che non esiste if(this.el.length == 0) return; this.masonry.remove( elements ); this.update([]); }, appendElement : function(Jel){ // se sto provando a eliminare qualcosa che non esiste if(this.el.length == 0) return; this.$grid.append(Jel); var self = this; imagesLoaded( this.el, function() { self.$grid.masonry('appended', Jel ).masonry('layout'); self.update(); }); }, prependElement : function(Jel){ // se sto provando a eliminare qualcosa che non esiste if(this.el.length == 0) return; this.$grid.prepend(Jel).masonry('prepended', Jel ); this.update([]); }, _onScrollFn : function() { var self = this; if( !this.didScroll ) { this.didScroll = true; // garantisco che avvenga una sola di queste setTimeout( function() { self._scrollPage(); }, 60 ); } }, _scrollPage : function() { var self = this; // per ogni elemento controllo se e' nella viewport o meno, eseguendo eventuali animazioni this.items.forEach( function( el, i ) { if( !classie.has( el, 'shown' ) && !classie.has( el, 'animate' ) && inViewport( el, self.options.viewportFactor ) ) { setTimeout( function() { var perspY = scrollY() + getViewportH() / 2; self.el.style.WebkitPerspectiveOrigin = '50% ' + perspY + 'px'; self.el.style.MozPerspectiveOrigin = '50% ' + perspY + 'px'; self.el.style.perspectiveOrigin = '50% ' + perspY + 'px'; self._checkTotalRendered(); if( self.options.minDuration && self.options.maxDuration ) { var randDuration = ( Math.random() * ( self.options.maxDuration - self.options.minDuration ) + self.options.minDuration ) + 's'; el.style.WebkitAnimationDuration = randDuration; el.style.MozAnimationDuration = randDuration; el.style.animationDuration = randDuration; } classie.add( el, 'animate' ); }, 25 ); } }); // riattivo la possibilita' di realizzare nuovamente questa funzione this.didScroll = false; }, _resizeHandler : function() { var self = this; function delayed() { self._scrollPage(); self.resizeTimeout = null; } if ( this.resizeTimeout ) { clearTimeout( this.resizeTimeout ); } this.resizeTimeout = setTimeout( delayed, 1000 ); }, _checkTotalRendered : function() { ++this.itemsRenderedCount; if( this.itemsRenderedCount === this.itemsCount ) { window.removeEventListener( 'scroll', this._onScrollFn ); } } } // add to global namespace window.AnimOnScroll = AnimOnScroll; } )( window );
agpl-3.0
flyingSkull/shopware
engine/Shopware/Plugins/Community/Frontend/SatzBrands/Meta.php
1476
<?php return array( 'version' => $this->getVersion(), 'autor' => 'Satzmedia GmbH', 'copyright' => 'Copyright ' . '@' . ' 2013, Satzmedia GmbH', 'label' => $this->getLabel(), 'source' => 'Community', 'description' => '<table style="border: solid 2px #00b4ec; width: 100%; padding: 7px 0px 7px 7px; "> <tr> <td style="width: 100px; vertical-align: top;"> <a href="http://www.satzmedia.de/shopware-plugins" target="_blank"> <img style="border: none" src="http://www.shopware.de/images/articles/a3f0c30d69e8471520b8b3a544fddaca.jpg" alt="Satzmedia GmbH" /> </a> </td> <td> <p style="font-size: 12px; color: green; font-weight: bold;"> Satzmedia GmbH, Shopware Certified Developer & Shopware Solution Partner<br/> Support per Email: plugins@satzmedia.de </p> <p style="padding-top: 15px; font-size: 14px;"> Das Plugin erstellt automatisch eine Seite mit allen Markenlogos aus dem Shop. Keine Einstellungen nötig. Die Seite ist mit /brands aufrufbar </p> </td> </tr> </table> ', 'license' => '', 'support' => 'http://www.satzmedia.de/shopware-plugins', 'link' => 'http://www.satzmedia.de/shopware-plugins/brands' );
agpl-3.0
cejebuto/OrfeoWind
adodb/session/adodb-cryptsession.php
591
<?php /* V4.01 23 Oct 2003 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved. Contributed by Ross Smith (adodb@netebb.com). Released under both BSD license and Lesser GPL library license. Whenever there is any discrepancy between the two licenses, the BSD license will take precedence. Set tabs to 4 for best viewing. */ /* This file is provided for backwards compatibility purposes */ require_once dirname(__FILE__) . '/adodb-session.php'; require_once ADODB_SESSION . '/adodb-encrypt-md5.php'; ADODB_Session::filter(new ADODB_Encrypt_MD5()); ?>
agpl-3.0
CompassionCH/compassion-modules
message_center_compassion/controllers/__init__.py
48
from . import json_request from . import onramp
agpl-3.0
jonathanf/swarm
swarm_extraction/extraction.py
2579
# # Copyright (C) 2015 Jonathan Finlay <jfinlay@riseup.net> # # 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/>. # from openerp.osv.orm import Model from openerp.osv import fields _campaign_states = [ ('draft', 'Draft'), ('progress', 'In progress'), ('done', 'Done'), ('cancel', 'Cancel') ] class Campaign(Model): """ Class to configure data extraction campaigns """ _name = 'swarm.campaign' _description = __doc__ def _collection_size(self, cr, uid, ids, fields, args, context=None): res = {} for campaign in self.browse(cr, uid, ids, context=context): res[campaign.id] = campaign.items return res _columns = { 'name': fields.char('Name'), 'init_date': fields.datetime('Start date'), 'end_date': fields.datetime('End date'), 'tags_ids': fields.many2many('swarm_tag', 'swarm_campaign_tag_rel', 'campaign_id', 'tag_id', 'Tags'), 'min_items': fields.integer('Min items'), 'max_items': fields.integer('Max items'), 'resume_collected_items': fields.function(_collection_size, type='integer', string='Collected items'), 'collected_items': fields.one2many('swarm_campaign_item', 'campaign_id', 'Items'), 'state': fields.selection(_campaign_states, 'State'), } class CampaignItem(Model): """ Class to store data for extraction campaigns """ _name = 'swarm.campaign.item' _description = __doc__ _columns = { 'name': fields.char('Name'), 'campaign_id': fields.many2one('swarm_campaign', 'Campaign'), 'item': fields.text('Item'), } class CampaignTag(Model): """ Campaign tags """ _name = 'swarm.tag' _description = __doc__ _columns = { 'name', fields.char('Name') }
agpl-3.0
cozy-labs/cozy-desktop
core/ignore.js
7020
/** Ignored files/directories handling. * * Cozy-desktop can ignore some files and folders with a `.cozyignore` file. This * file is read only at the startup of Cozy-desktop. So, if this file is * modified, cozy-desktop has to be relaunched for the changes to be effective. * * There 4 places where ignoring files and folders can have a meaning: * * - when a change is detected on the local file system and cozy-desktop is going * to save it in its internal pouchdb * - when a change is detected on the remote cozy and cozy-desktop is going to * save it in its internal pouchdb * - when a change is taken from the pouchdb and cozy-desktop is going to apply * on the local file system * - when a change is taken from the pouchdb and cozy-desktop is going to apply * on the remote cozy. * * Even with the first two checks, pouchdb can have a change for an ignored file * from a previous run of cozy-desktop where the file was not yet ignored. So, we * have to implement the last two checks. It is enough for a file created on one * side (local or remote) won't be replicated on the other side if it is ignored. * * But, there is a special case: conflicts are treated ahead of pouchdb. So, if a * file is created in both the local file system and the remote cozy (with * different contents) is ignored, the conflict will still be resolved by * renaming if we implement only the last two checks. We have to avoid that by * also implementing at least one of the first two checks. * * In practice, it's really convenient to let the changes from the remote couchdb * flows to pouchdb, even for ignored files, as it is very costly to find them * later if `.cozyignore` has changed. And it's a lot easier to detect local * files that were ignored but are no longer at the startup, as cozy-desktop * already does a full scan of the local file system at that moment. * * Thus, cozy-desktop has a check for ignored files and folder in three of the * four relevant places: * * - when a change is detected on the local file system and cozy-desktop is going * to save it in its internal pouchdb * - when a change is taken from the pouchdb and cozy-desktop is going to apply * on the local file system * - when a change is taken from the pouchdb and cozy-desktop is going to apply * on the remote cozy. * * @module core/ignore * @see https://git-scm.com/docs/gitignore/#_pattern_format * @flow */ const { basename, dirname, resolve } = require('path') const { matcher, makeRe } = require('micromatch') const fs = require('fs') const logger = require('./utils/logger') const log = logger({ component: 'Ignore' }) /*:: export type IgnorePattern = { match: (string) => boolean, basename: boolean, folder: boolean, negate: boolean } */ /** Load both given file rules & default ones */ function loadSync(rulesFilePath /*: string */) /*: Ignore */ { let ignored try { ignored = readLinesSync(rulesFilePath) } catch (err) { if (err.code === 'ENOENT') { log.info( { rulesFilePath }, 'Skip loading of non-existent ignore rules file' ) } else { log.warn({ rulesFilePath, err }, 'Failed loading ignore rules file') } ignored = [] } return new Ignore(ignored).addDefaultRules() } /** Read lines from a file. */ function readLinesSync(filePath /*: string */) /*: string[] */ { return fs.readFileSync(filePath, 'utf8').split(/\r?\n/) } // Parse a line and build the corresponding pattern function buildPattern(line /*: string */) /*: IgnorePattern */ { let folder = false let negate = false let noslash = line.indexOf('/') === -1 if (line.indexOf('**') !== -1) { // Detect two asterisks noslash = false } if (line[0] === '!') { // Detect bang prefix line = line.slice(1) negate = true } if (line[0] === '/') { // Detect leading slash line = line.slice(1) } if (line[line.length - 1] === '/') { // Detect trailing slash line = line.slice(0, line.length - 1) folder = true } line = line.replace(/^\\/, '') // Remove leading escaping char line = line.replace(/( |\t)*$/, '') // Remove trailing spaces // Ignore case for case insensitive file-systems if (process.platform === 'darwin' || process.platform === 'win32') { line = makeRe(line, { nocase: true }) } let pattern = { match: matcher(line, {}), basename: noslash, // The pattern can match only the basename folder, // The pattern will only match a folder negate // The pattern is negated } return pattern } /** Parse many lines and build the corresponding pattern array */ function buildPatternArray(lines /*: string[] */) /*: IgnorePattern[] */ { return Array.from(lines) .filter(isNotBlankOrComment) .map(buildPattern) } function isNotBlankOrComment(line /*: string */) /*: boolean */ { return line !== '' && line[0] !== '#' } function match( path /*: string */, isFolder /*: boolean */, pattern /*: IgnorePattern */ ) /*: boolean */ { if (pattern.basename) { if (pattern.match(basename(path))) { return true } } if (isFolder || !pattern.folder) { if (pattern.match(path)) { return true } } let parent = dirname(path) if (parent === '.') { return false } // On Windows, the various `path.*()` functions don't play well with // relative paths where the top-level file or directory name includes a // forbidden `:` character and looks like a drive letter, even without a // separator. Better make sure we don't end up in an infinite loop. if (parent === path) { return false } return match(parent, true, pattern) } /** The default rules included in the repo */ const defaultRulesPath = resolve(__dirname, './config/.cozyignore') /** * Cozy-desktop can ignore some files and folders from a list of patterns in the * cozyignore file. This class can be used to know if a file/folder is ignored. */ class Ignore { /*:: patterns: IgnorePattern[] */ // Load patterns for detecting ignored files and folders constructor(lines /*: string[] */) { this.patterns = buildPatternArray(lines) } // Add some rules for things that should be always ignored (temporary // files, thumbnails db, trash, etc.) addDefaultRules() /*: this */ { const defaultPatterns = buildPatternArray(readLinesSync(defaultRulesPath)) this.patterns = defaultPatterns.concat(this.patterns) return this } // Return true if the given file/folder path should be ignored isIgnored( { relativePath, isFolder } /*: {relativePath: string, isFolder: boolean} */ ) /*: boolean */ { let result = false for (let pattern of Array.from(this.patterns)) { if (pattern.negate) { if (result) { result = !match(relativePath, isFolder, pattern) } } else { if (!result) { result = match(relativePath, isFolder, pattern) } } } return result } } module.exports = { Ignore, loadSync }
agpl-3.0
akvo/akvo-rsr
akvo/rsr/front-end/scripts-src/my-results/reducers/pageReducer.js
498
/* Akvo RSR is covered by the GNU Affero General Public License. See more details in the license.txt file located at the root folder of the Akvo RSR module. For additional details on the GNU license please see < http://www.gnu.org/licenses/agpl.html >. */ import * as c from "../const"; export default function pageReducer(state = {}, action) { switch (action.type) { case c.PAGE_SET_DATA: { return action.payload.data; } } return state; }
agpl-3.0
harrowio/harrow
frontend/app/scripts/vendor/ui-router-history.js
1112
angular.module("ui.router.history", [ "ui.router" ]).service("$history", function($state, $rootScope, $window) { var history = []; angular.extend(this, { push: function(state, params) { history.push({ state: state, params: params }); }, all: function() { return history; }, go: function(step) { // TODO: // (1) Determine # of states in stack with URLs, attempt to // shell out to $window.history when possible // (2) Attempt to figure out some algorthim for reversing that, // so you can also go forward var prev = this.previous(step || -1); return $state.go(prev.state, prev.params); }, previous: function(step) { return history[history.length - Math.abs(step || 1)]; }, back: function() { return this.go(-1); } }); }).run(function($history, $state, $rootScope) { $rootScope.$on("$stateChangeSuccess", function(event, to, toParams, from, fromParams) { if (!from.abstract) { $history.push(from, fromParams); } }); $history.push($state.current, $state.params); });
agpl-3.0
ontohub/ontohub
db/migrate/20150715081870_create_sine_symbol_axiom_triggers.rb
854
class CreateSineSymbolAxiomTriggers < ActiveRecord::Migration def change create_table :sine_symbol_axiom_triggers do |t| t.references :axiom_selection t.references :symbol t.references :axiom t.float :tolerance t.timestamps end add_index :sine_symbol_axiom_triggers, :axiom_selection_id add_index :sine_symbol_axiom_triggers, :symbol_id add_index :sine_symbol_axiom_triggers, :axiom_id add_index :sine_symbol_axiom_triggers, [:axiom_selection_id, :symbol_id, :axiom_id], unique: true, name: 'sine_symbol_axiom_triggers_unique' # We only want to send queries like # SELECT axiom FROM sine_symbol_triggers WHERE symbol_id = 1 AND tolerance <= 1.5 # Thus, we also add an index on the tolerance. add_index :sine_symbol_axiom_triggers, :tolerance end end
agpl-3.0
cpennington/edx-platform
lms/djangoapps/courseware/views/index.py
28826
""" View for Courseware Index """ # pylint: disable=attribute-defined-outside-init import logging import six import six.moves.urllib as urllib # pylint: disable=import-error import six.moves.urllib.error # pylint: disable=import-error import six.moves.urllib.parse # pylint: disable=import-error import six.moves.urllib.request # pylint: disable=import-error from django.conf import settings from django.contrib.auth.models import User from django.contrib.auth.views import redirect_to_login from django.http import Http404 from django.template.context_processors import csrf from django.urls import reverse from django.utils.decorators import method_decorator from django.utils.functional import cached_property from django.utils.translation import ugettext as _ from django.views.decorators.cache import cache_control from django.views.decorators.csrf import ensure_csrf_cookie from django.views.generic import View from edx_django_utils.monitoring import set_custom_metrics_for_course_key from opaque_keys import InvalidKeyError from opaque_keys.edx.keys import CourseKey, UsageKey from web_fragments.fragment import Fragment from edxmako.shortcuts import render_to_response, render_to_string from lms.djangoapps.courseware.exceptions import CourseAccessRedirect, Redirect from lms.djangoapps.experiments.utils import get_experiment_user_metadata_context from lms.djangoapps.gating.api import get_entrance_exam_score_ratio, get_entrance_exam_usage_key from lms.djangoapps.grades.api import CourseGradeFactory from openedx.core.djangoapps.content.course_overviews.models import CourseOverview from openedx.core.djangoapps.crawlers.models import CrawlersConfig from openedx.core.djangoapps.lang_pref import LANGUAGE_KEY from openedx.core.djangoapps.user_api.preferences.api import get_user_preference from openedx.core.djangoapps.util.user_messages import PageLevelMessages from openedx.core.djangoapps.waffle_utils import WaffleSwitchNamespace from openedx.core.djangolib.markup import HTML, Text from openedx.features.course_experience import ( COURSE_ENABLE_UNENROLLED_ACCESS_FLAG, COURSE_OUTLINE_PAGE_FLAG, default_course_url_name ) from openedx.features.course_experience.views.course_sock import CourseSockFragmentView from openedx.features.enterprise_support.api import data_sharing_consent_required from shoppingcart.models import CourseRegistrationCode from student.views import is_course_blocked from util.views import ensure_valid_course_key from xmodule.course_module import COURSE_VISIBILITY_PUBLIC from xmodule.modulestore.django import modulestore from xmodule.x_module import PUBLIC_VIEW, STUDENT_VIEW from ..access import has_access from ..courses import ( allow_public_access, check_course_access, get_course_with_access, get_current_child, get_studio_url ) from ..entrance_exams import ( course_has_entrance_exam, get_entrance_exam_content, user_can_skip_entrance_exam, user_has_passed_entrance_exam ) from ..masquerade import check_content_start_date_for_masquerade_user, setup_masquerade from ..model_data import FieldDataCache from ..module_render import get_module_for_descriptor, toc_for_course from ..permissions import MASQUERADE_AS_STUDENT from ..toggles import COURSEWARE_MICROFRONTEND_COURSE_TEAM_PREVIEW, should_redirect_to_courseware_microfrontend from ..url_helpers import get_microfrontend_url from .views import CourseTabView log = logging.getLogger("edx.courseware.views.index") TEMPLATE_IMPORTS = {'urllib': urllib} CONTENT_DEPTH = 2 class CoursewareIndex(View): """ View class for the Courseware page. """ @cached_property def enable_unenrolled_access(self): return COURSE_ENABLE_UNENROLLED_ACCESS_FLAG.is_enabled(self.course_key) @method_decorator(ensure_csrf_cookie) @method_decorator(cache_control(no_cache=True, no_store=True, must_revalidate=True)) @method_decorator(ensure_valid_course_key) @method_decorator(data_sharing_consent_required) def get(self, request, course_id, chapter=None, section=None, position=None): """ Displays courseware accordion and associated content. If course, chapter, and section are all specified, renders the page, or returns an error if they are invalid. If section is not specified, displays the accordion opened to the right chapter. If neither chapter or section are specified, displays the user's most recent chapter, or the first chapter if this is the user's first visit. Arguments: request: HTTP request course_id (unicode): course id chapter (unicode): chapter url_name section (unicode): section url_name position (unicode): position in module, eg of <sequential> module """ self.course_key = CourseKey.from_string(course_id) if not (request.user.is_authenticated or self.enable_unenrolled_access): return redirect_to_login(request.get_full_path()) self.original_chapter_url_name = chapter self.original_section_url_name = section self.chapter_url_name = chapter self.section_url_name = section self.position = position self.chapter, self.section = None, None self.course = None self.url = request.path try: set_custom_metrics_for_course_key(self.course_key) self._clean_position() with modulestore().bulk_operations(self.course_key): self.view = STUDENT_VIEW # Do the enrollment check if enable_unenrolled_access is not enabled. self.course = get_course_with_access( request.user, 'load', self.course_key, depth=CONTENT_DEPTH, check_if_enrolled=not self.enable_unenrolled_access, ) self.course_overview = CourseOverview.get_from_id(self.course.id) if self.enable_unenrolled_access: # Check if the user is considered enrolled (i.e. is an enrolled learner or staff). try: check_course_access( self.course, request.user, 'load', check_if_enrolled=True, ) except CourseAccessRedirect as exception: # If the user is not considered enrolled: if self.course.course_visibility == COURSE_VISIBILITY_PUBLIC: # If course visibility is public show the XBlock public_view. self.view = PUBLIC_VIEW else: # Otherwise deny them access. raise exception else: # If the user is considered enrolled show the default XBlock student_view. pass self.can_masquerade = request.user.has_perm(MASQUERADE_AS_STUDENT, self.course) self.is_staff = has_access(request.user, 'staff', self.course) self._setup_masquerade_for_effective_user() return self.render(request) except Exception as exception: # pylint: disable=broad-except return CourseTabView.handle_exceptions(request, self.course_key, self.course, exception) def _setup_masquerade_for_effective_user(self): """ Setup the masquerade information to allow the request to be processed for the requested effective user. """ self.real_user = self.request.user self.masquerade, self.effective_user = setup_masquerade( self.request, self.course_key, self.can_masquerade, reset_masquerade_data=True ) # Set the user in the request to the effective user. self.request.user = self.effective_user def _redirect_to_learning_mfe(self, request): """ Redirect to the new courseware micro frontend, unless this is a time limited exam. """ # learners should redirect, if the waffle flag is set if should_redirect_to_courseware_microfrontend(self.course_key): # but exams should not redirect to the mfe until they're supported if getattr(self.section, 'is_time_limited', False): return # and staff will not redirect, either if self.is_staff: return url = get_microfrontend_url( self.course_key, self.section.location ) raise Redirect(url) def render(self, request): """ Render the index page. """ self._redirect_if_needed_to_pay_for_course() self._prefetch_and_bind_course(request) if self.course.has_children_at_depth(CONTENT_DEPTH): self._reset_section_to_exam_if_required() self.chapter = self._find_chapter() self.section = self._find_section() if self.chapter and self.section: self._redirect_if_not_requested_section() self._save_positions() self._prefetch_and_bind_section() self._redirect_to_learning_mfe(request) check_content_start_date_for_masquerade_user(self.course_key, self.effective_user, request, self.course.start, self.chapter.start, self.section.start) if not request.user.is_authenticated: qs = six.moves.urllib.parse.urlencode({ 'course_id': self.course_key, 'enrollment_action': 'enroll', 'email_opt_in': False, }) allow_anonymous = allow_public_access(self.course, [COURSE_VISIBILITY_PUBLIC]) if not allow_anonymous: PageLevelMessages.register_warning_message( request, Text(_(u"You are not signed in. To see additional course content, {sign_in_link} or " u"{register_link}, and enroll in this course.")).format( sign_in_link=HTML(u'<a href="{url}">{sign_in_label}</a>').format( sign_in_label=_('sign in'), url='{}?{}'.format(reverse('signin_user'), qs), ), register_link=HTML(u'<a href="/{url}">{register_label}</a>').format( register_label=_('register'), url=u'{}?{}'.format(reverse('register_user'), qs), ), ) ) return render_to_response('courseware/courseware.html', self._create_courseware_context(request)) def _redirect_if_not_requested_section(self): """ If the resulting section and chapter are different from what was initially requested, redirect back to the index page, but with an updated URL that includes the correct section and chapter values. We do this so that our analytics events and error logs have the appropriate URLs. """ if ( self.chapter.url_name != self.original_chapter_url_name or (self.original_section_url_name and self.section.url_name != self.original_section_url_name) ): raise CourseAccessRedirect( reverse( 'courseware_section', kwargs={ 'course_id': six.text_type(self.course_key), 'chapter': self.chapter.url_name, 'section': self.section.url_name, }, ) ) def _clean_position(self): """ Verify that the given position is an integer. If it is not positive, set it to 1. """ if self.position is not None: try: self.position = max(int(self.position), 1) except ValueError: raise Http404(u"Position {} is not an integer!".format(self.position)) def _redirect_if_needed_to_pay_for_course(self): """ Redirect to dashboard if the course is blocked due to non-payment. """ redeemed_registration_codes = [] if self.request.user.is_authenticated: self.real_user = User.objects.prefetch_related("groups").get(id=self.real_user.id) redeemed_registration_codes = CourseRegistrationCode.objects.filter( course_id=self.course_key, registrationcoderedemption__redeemed_by=self.real_user ) if is_course_blocked(self.request, redeemed_registration_codes, self.course_key): # registration codes may be generated via Bulk Purchase Scenario # we have to check only for the invoice generated registration codes # that their invoice is valid or not # TODO Update message to account for the fact that the user is not authenticated. log.warning( u'User %s cannot access the course %s because payment has not yet been received', self.real_user, six.text_type(self.course_key), ) raise CourseAccessRedirect(reverse('dashboard')) def _reset_section_to_exam_if_required(self): """ Check to see if an Entrance Exam is required for the user. """ if not user_can_skip_entrance_exam(self.effective_user, self.course): exam_chapter = get_entrance_exam_content(self.effective_user, self.course) if exam_chapter and exam_chapter.get_children(): exam_section = exam_chapter.get_children()[0] if exam_section: self.chapter_url_name = exam_chapter.url_name self.section_url_name = exam_section.url_name def _get_language_preference(self): """ Returns the preferred language for the actual user making the request. """ language_preference = settings.LANGUAGE_CODE if self.request.user.is_authenticated: language_preference = get_user_preference(self.real_user, LANGUAGE_KEY) return language_preference def _is_masquerading_as_student(self): """ Returns whether the current request is masquerading as a student. """ return self.masquerade and self.masquerade.role == 'student' def _is_masquerading_as_specific_student(self): """ Returns whether the current request is masqueurading as a specific student. """ return self._is_masquerading_as_student() and self.masquerade.user_name def _find_block(self, parent, url_name, block_type, min_depth=None): """ Finds the block in the parent with the specified url_name. If not found, calls get_current_child on the parent. """ child = None if url_name: child = parent.get_child_by(lambda m: m.location.block_id == url_name) if not child: # User may be trying to access a child that isn't live yet if not self._is_masquerading_as_student(): raise Http404(u'No {block_type} found with name {url_name}'.format( block_type=block_type, url_name=url_name, )) elif min_depth and not child.has_children_at_depth(min_depth - 1): child = None if not child: child = get_current_child(parent, min_depth=min_depth, requested_child=self.request.GET.get("child")) return child def _find_chapter(self): """ Finds the requested chapter. """ return self._find_block(self.course, self.chapter_url_name, 'chapter', CONTENT_DEPTH - 1) def _find_section(self): """ Finds the requested section. """ if self.chapter: return self._find_block(self.chapter, self.section_url_name, 'section') def _prefetch_and_bind_course(self, request): """ Prefetches all descendant data for the requested section and sets up the runtime, which binds the request user to the section. """ self.field_data_cache = FieldDataCache.cache_for_descriptor_descendents( self.course_key, self.effective_user, self.course, depth=CONTENT_DEPTH, read_only=CrawlersConfig.is_crawler(request), ) self.course = get_module_for_descriptor( self.effective_user, self.request, self.course, self.field_data_cache, self.course_key, course=self.course, will_recheck_access=True, ) def _prefetch_and_bind_section(self): """ Prefetches all descendant data for the requested section and sets up the runtime, which binds the request user to the section. """ # Pre-fetch all descendant data self.section = modulestore().get_item(self.section.location, depth=None, lazy=False) self.field_data_cache.add_descriptor_descendents(self.section, depth=None) # Bind section to user self.section = get_module_for_descriptor( self.effective_user, self.request, self.section, self.field_data_cache, self.course_key, self.position, course=self.course, will_recheck_access=True, ) def _save_positions(self): """ Save where we are in the course and chapter. """ save_child_position(self.course, self.chapter_url_name) save_child_position(self.chapter, self.section_url_name) def _create_courseware_context(self, request): """ Returns and creates the rendering context for the courseware. Also returns the table of contents for the courseware. """ course_url_name = default_course_url_name(self.course.id) course_url = reverse(course_url_name, kwargs={'course_id': six.text_type(self.course.id)}) show_search = ( settings.FEATURES.get('ENABLE_COURSEWARE_SEARCH') or (settings.FEATURES.get('ENABLE_COURSEWARE_SEARCH_FOR_COURSE_STAFF') and self.is_staff) ) staff_access = self.is_staff courseware_context = { 'csrf': csrf(self.request)['csrf_token'], 'course': self.course, 'course_url': course_url, 'chapter': self.chapter, 'section': self.section, 'init': '', 'fragment': Fragment(), 'staff_access': staff_access, 'can_masquerade': self.can_masquerade, 'masquerade': self.masquerade, 'supports_preview_menu': True, 'studio_url': get_studio_url(self.course, 'course'), 'xqa_server': settings.FEATURES.get('XQA_SERVER', "http://your_xqa_server.com"), 'bookmarks_api_url': reverse('bookmarks'), 'language_preference': self._get_language_preference(), 'disable_optimizely': not WaffleSwitchNamespace('RET').is_enabled('enable_optimizely_in_courseware'), 'section_title': None, 'sequence_title': None, 'disable_accordion': COURSE_OUTLINE_PAGE_FLAG.is_enabled(self.course.id), 'show_search': show_search, } courseware_context.update( get_experiment_user_metadata_context( self.course, self.effective_user, ) ) table_of_contents = toc_for_course( self.effective_user, self.request, self.course, self.chapter_url_name, self.section_url_name, self.field_data_cache, ) courseware_context['accordion'] = render_accordion( self.request, self.course, table_of_contents['chapters'], ) courseware_context['course_sock_fragment'] = CourseSockFragmentView().render_to_fragment( request, course=self.course_overview) # entrance exam data self._add_entrance_exam_to_context(courseware_context) if self.section: # chromeless data if self.section.chrome: chrome = [s.strip() for s in self.section.chrome.lower().split(",")] if 'accordion' not in chrome: courseware_context['disable_accordion'] = True if 'tabs' not in chrome: courseware_context['disable_tabs'] = True # default tab if self.section.default_tab: courseware_context['default_tab'] = self.section.default_tab # section data courseware_context['section_title'] = self.section.display_name_with_default section_context = self._create_section_context( table_of_contents['previous_of_active_section'], table_of_contents['next_of_active_section'], ) courseware_context['fragment'] = self.section.render(self.view, section_context) if self.section.position and self.section.has_children: self._add_sequence_title_to_context(courseware_context) # Courseware MFE link if show_courseware_mfe_link(request.user, staff_access, self.course.id): if self.section: try: unit_key = UsageKey.from_string(request.GET.get('activate_block_id', '')) # `activate_block_id` is typically a Unit (a.k.a. Vertical), # but it can technically be any block type. Do a check to # make sure it's really a Unit before we use it for the MFE. if unit_key.block_type != 'vertical': unit_key = None except InvalidKeyError: unit_key = None courseware_context['microfrontend_link'] = get_microfrontend_url( self.course.id, self.section.location, unit_key ) else: courseware_context['microfrontend_link'] = get_microfrontend_url(self.course.id) else: courseware_context['microfrontend_link'] = None return courseware_context def _add_sequence_title_to_context(self, courseware_context): """ Adds sequence title to the given context. If we're rendering a section with some display items, but position exceeds the length of the displayable items, default the position to the first element. """ display_items = self.section.get_display_items() if not display_items: return if self.section.position > len(display_items): self.section.position = 1 courseware_context['sequence_title'] = display_items[self.section.position - 1].display_name_with_default def _add_entrance_exam_to_context(self, courseware_context): """ Adds entrance exam related information to the given context. """ if course_has_entrance_exam(self.course) and getattr(self.chapter, 'is_entrance_exam', False): courseware_context['entrance_exam_passed'] = user_has_passed_entrance_exam(self.effective_user, self.course) courseware_context['entrance_exam_current_score'] = get_entrance_exam_score_ratio( CourseGradeFactory().read(self.effective_user, self.course), get_entrance_exam_usage_key(self.course), ) def _create_section_context(self, previous_of_active_section, next_of_active_section): """ Returns and creates the rendering context for the section. """ def _compute_section_url(section_info, requested_child): """ Returns the section URL for the given section_info with the given child parameter. """ return "{url}?child={requested_child}".format( url=reverse( 'courseware_section', args=[six.text_type(self.course_key), section_info['chapter_url_name'], section_info['url_name']], ), requested_child=requested_child, ) # NOTE (CCB): Pull the position from the URL for un-authenticated users. Otherwise, pull the saved # state from the data store. position = None if self.request.user.is_authenticated else self.position section_context = { 'activate_block_id': self.request.GET.get('activate_block_id'), 'requested_child': self.request.GET.get("child"), 'progress_url': reverse('progress', kwargs={'course_id': six.text_type(self.course_key)}), 'user_authenticated': self.request.user.is_authenticated, 'position': position, } if previous_of_active_section: section_context['prev_url'] = _compute_section_url(previous_of_active_section, 'last') if next_of_active_section: section_context['next_url'] = _compute_section_url(next_of_active_section, 'first') # sections can hide data that masquerading staff should see when debugging issues with specific students section_context['specific_masquerade'] = self._is_masquerading_as_specific_student() return section_context def render_accordion(request, course, table_of_contents): """ Returns the HTML that renders the navigation for the given course. Expects the table_of_contents to have data on each chapter and section, including which ones are active. """ context = dict( [ ('toc', table_of_contents), ('course_id', six.text_type(course.id)), ('csrf', csrf(request)['csrf_token']), ('due_date_display_format', course.due_date_display_format), ] + list(TEMPLATE_IMPORTS.items()) ) return render_to_string('courseware/accordion.html', context) def save_child_position(seq_module, child_name): """ child_name: url_name of the child """ for position, child in enumerate(seq_module.get_display_items(), start=1): if child.location.block_id == child_name: # Only save if position changed if position != seq_module.position: seq_module.position = position # Save this new position to the underlying KeyValueStore seq_module.save() def save_positions_recursively_up(user, request, field_data_cache, xmodule, course=None): """ Recurses up the course tree starting from a leaf Saving the position property based on the previous node as it goes """ current_module = xmodule while current_module: parent_location = modulestore().get_parent_location(current_module.location) parent = None if parent_location: parent_descriptor = modulestore().get_item(parent_location) parent = get_module_for_descriptor( user, request, parent_descriptor, field_data_cache, current_module.location.course_key, course=course ) if parent and hasattr(parent, 'position'): save_child_position(parent, current_module.location.block_id) current_module = parent def show_courseware_mfe_link(user, staff_access, course_key): """ Return whether to display the button to switch to the Courseware MFE. """ # The MFE isn't enabled at all, so don't show the button. if not settings.FEATURES.get('ENABLE_COURSEWARE_MICROFRONTEND'): return False # MFE does not work for Old Mongo courses. if course_key.deprecated: return False # Global staff members always get to see the courseware MFE button if the # platform and course are capable, regardless of rollout waffle flags. if user.is_staff: return True # If you have course staff access, you see this link if we've enabled the # course team preview CourseWaffleFlag for this course *or* if we've turned # on the redirect for your students. mfe_enabled_for_course_team = COURSEWARE_MICROFRONTEND_COURSE_TEAM_PREVIEW.is_enabled(course_key) mfe_enabled_for_students = should_redirect_to_courseware_microfrontend(course_key) if staff_access and (mfe_enabled_for_course_team or mfe_enabled_for_students): return True return False
agpl-3.0
kinnou02/navitia
source/jormungandr/jormungandr/autocomplete/geocodejson.py
13686
# coding=utf-8 # Copyright (c) 2001-2016, Canal TP and/or its affiliates. All rights reserved. # # This file is part of Navitia, # the software to build cool stuff with public transport. # # Hope you'll enjoy and contribute to this project, # powered by Canal TP (www.canaltp.fr). # Help us simplify mobility and open public transport: # a non ending quest to the responsive locomotion way of traveling! # # LICENCE: 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/>. # # Stay tuned using # twitter @navitia # channel `#navitia` on riot https://riot.im/app/#/room/#navitia:matrix.org # https://groups.google.com/d/forum/navitia # www.navitia.io from __future__ import absolute_import, print_function, unicode_literals, division import logging import jormungandr from jormungandr.autocomplete.abstract_autocomplete import ( AbstractAutocomplete, AutocompleteUnavailable, AutocompleteError, ) from jormungandr.utils import get_lon_lat as get_lon_lat_from_id, get_house_number import requests import pybreaker from jormungandr import app from jormungandr.exceptions import UnknownObject def create_admin_field(geocoding): """ This field is needed to respect the geocodejson-spec https://github.com/geocoders/geocodejson-spec/tree/master/draft#feature-object """ if not geocoding: return None admin_list = geocoding.get('admin', {}) response = [] for level, name in admin_list.items(): response.append( { "insee": None, "name": name, "level": int(level.replace('level', '')), "coord": {"lat": None, "lon": None}, "label": None, "id": None, "zip_code": None, } ) return response def format_zip_code(zip_codes): if all(zip_code == "" for zip_code in zip_codes): return None elif len(zip_codes) == 1: return zip_codes[0] else: return '{}-{}'.format(min(zip_codes), max(zip_codes)) def create_administrative_regions_field(geocoding): if not geocoding: return None administrative_regions = geocoding.get('administrative_regions', {}) response = [] for admin in administrative_regions: coord = admin.get('coord', {}) lat = str(coord.get('lat')) if coord and coord.get('lat') else None lon = str(coord.get('lon')) if coord and coord.get('lon') else None zip_codes = admin.get('zip_codes', []) response.append( { "insee": admin.get('insee'), "name": admin.get('name'), "level": int(admin.get('level')) if admin.get('level') else None, "coord": {"lat": lat, "lon": lon}, "label": admin.get('label'), "id": admin.get('id'), "zip_code": format_zip_code(zip_codes), } ) return response def create_modes_field(modes): if not modes: return [] return [{"id": mode.get('id'), "name": mode.get('name')} for mode in modes] def create_comments_field(modes): if not modes: return [] # To be compatible, type = 'standard' return [{"type": 'standard', "value": mode.get('name')} for mode in modes] def create_codes_field(codes): if not codes: return [] # The code type value 'navitia1' replaced by 'external_code' for code in codes: if code.get('name') == 'navitia1': code['name'] = 'external_code' return [{"type": code.get('name'), "value": code.get('value')} for code in codes] def get_lon_lat(obj): if not obj or not obj.get('geometry') or not obj.get('geometry').get('coordinates'): return None, None coordinates = obj.get('geometry', {}).get('coordinates', []) if len(coordinates) == 2: lon = str(coordinates[0]) lat = str(coordinates[1]) else: lon = None lat = None return lon, lat def create_address_field(geocoding, poi_lat=None, poi_lon=None): if not geocoding: return None coord = geocoding.get('coord', {}) lat = str(coord.get('lat')) if coord and coord.get('lat') else poi_lat lon = str(coord.get('lon')) if coord and coord.get('lon') else poi_lon address_id = '{lon};{lat}'.format(lon=lon, lat=lat) resp = { "id": address_id, "label": geocoding.get('label'), "name": geocoding.get('name'), "coord": {"lat": lat, "lon": lon}, "house_number": get_house_number(geocoding.get('housenumber')), } admins = create_administrative_regions_field(geocoding) or create_admin_field(geocoding) if admins: resp['administrative_regions'] = admins return resp class GeocodeJson(AbstractAutocomplete): """ Autocomplete with an external service returning geocodejson (https://github.com/geocoders/geocodejson-spec/) """ # the geocodejson types TYPE_STOP_AREA = "public_transport:stop_area" TYPE_CITY = "city" TYPE_POI = "poi" TYPE_HOUSE = "house" TYPE_STREET = "street" TYPE_LIST = [TYPE_STOP_AREA, TYPE_CITY, TYPE_POI, TYPE_HOUSE, TYPE_STREET] def __init__(self, **kwargs): self.host = kwargs.get('host') self.timeout = kwargs.get('timeout', 2) # used for slow call, like geocoding # used for fast call like reverse geocoding and features self.fast_timeout = kwargs.get('fast_timeout', 0.2) self.breaker = pybreaker.CircuitBreaker( fail_max=app.config['CIRCUIT_BREAKER_MAX_BRAGI_FAIL'], reset_timeout=app.config['CIRCUIT_BREAKER_BRAGI_TIMEOUT_S'], ) # create a session to allow connection pooling via keep alive if kwargs.get('disable_keepalive', False): self.session = requests else: self.session = requests.Session() def call_bragi(self, url, method, **kwargs): try: return self.breaker.call(method, url, **kwargs) except pybreaker.CircuitBreakerError as e: logging.getLogger(__name__).error('external autocomplete service dead (error: {})'.format(e)) raise GeocodeJsonUnavailable('circuit breaker open') except requests.Timeout: logging.getLogger(__name__).error('autocomplete request timeout') raise GeocodeJsonUnavailable('external autocomplete service timeout') except: logging.getLogger(__name__).exception('error in autocomplete request') raise GeocodeJsonUnavailable('impossible to access external autocomplete service') @classmethod def _check_response(cls, response, uri): if response is None: raise GeocodeJsonError('impossible to access autocomplete service') if response.status_code == 404: raise UnknownObject(uri) if response.status_code == 503: raise GeocodeJsonUnavailable('geocodejson responded with 503') if response.status_code != 200: error_msg = 'Autocomplete request failed with HTTP code {}'.format(response.status_code) if response.text: error_msg += ' ({})'.format(response.text) raise GeocodeJsonError(error_msg) @classmethod def _clean_response(cls, response, depth=1): def is_deleteable(_key, _value, _depth): if _depth > -1: return False else: if _key == 'administrative_regions': return True elif isinstance(_value, dict) and _value.get('type') in cls.TYPE_LIST: return True else: return False def _clear_object(obj): if isinstance(obj, list): del obj[:] elif isinstance(obj, dict): obj.clear() def _manage_depth(_key, _value, _depth): if is_deleteable(_key, _value, _depth): _clear_object(_value) elif isinstance(_value, dict): for k, v in _value.items(): _manage_depth(k, v, _depth - 1) features = response.get('features') if features: for feature in features: key = 'geocoding' value = feature.get('properties', {}).get('geocoding') if not value: continue _manage_depth(key, value, depth) return response @classmethod def response_marshaler(cls, response_bragi, uri=None, depth=1): cls._check_response(response_bragi, uri) try: json_response = response_bragi.json() except ValueError: logging.getLogger(__name__).error( "impossible to get json for response %s with body: %s", response_bragi.status_code, response_bragi.text, ) raise # Clean dict objects depending on depth passed in request parameter. json_response = cls._clean_response(json_response, depth) from jormungandr.interfaces.v1.serializer.geocode_json import GeocodePlacesSerializer return GeocodePlacesSerializer(json_response).data def make_url(self, end_point, uri=None): if end_point not in ['autocomplete', 'features', 'reverse']: raise GeocodeJsonError('Unknown endpoint') if not self.host: raise GeocodeJsonError('global autocomplete not configured') url = "{host}/{end_point}".format(host=self.host, end_point=end_point) if uri: url = '{url}/{uri}'.format(url=url, uri=uri) return url def basic_params(self, instances): ''' These are the parameters common to the three endpoints ''' if not instances: return [] params = [('pt_dataset[]', i.name) for i in instances] params.extend([('poi_dataset[]', i.poi_dataset) for i in instances if i.poi_dataset]) return params def make_params(self, request, instances, timeout): ''' These are the parameters used specifically for the autocomplete endpoint. ''' params = self.basic_params(instances) params.extend([("q", request["q"]), ("limit", request["count"])]) if request.get("type[]"): types = [] map_type = { "administrative_region": [self.TYPE_CITY], "address": [self.TYPE_STREET, self.TYPE_HOUSE], "stop_area": [self.TYPE_STOP_AREA], "poi": [self.TYPE_POI], } for type in request.get("type[]"): if type == 'stop_point': logging.getLogger(__name__).debug('stop_point is not handled by bragi') continue for t in map_type[type]: params.append(("type[]", t)) if request.get("from"): lon, lat = self.get_coords(request["from"]) params.extend([('lon', lon), ('lat', lat)]) if timeout: # bragi timeout is in ms params.append(("timeout", int(timeout * 1000))) return params def get(self, request, instances): params = self.make_params(request, instances, self.timeout) shape = request.get('shape', None) url = self.make_url('autocomplete') kwargs = {"params": params, "timeout": self.timeout} method = self.session.get if shape: kwargs["json"] = {"shape": shape} method = self.session.post logging.getLogger(__name__).debug("call bragi with parameters %s", kwargs) raw_response = self.call_bragi(url, method, **kwargs) depth = request.get('depth', 1) return self.response_marshaler(raw_response, None, depth) def geo_status(self, instance): raise NotImplementedError @staticmethod def get_coords(param): """ Get coordinates (longitude, latitude). For moment we consider that the param can only be a coordinate. """ return param.split(";") def get_by_uri(self, uri, instances=None, current_datetime=None): params = self.basic_params(instances) lon, lat = get_lon_lat_from_id(uri) if lon is not None and lat is not None: url = self.make_url('reverse') params.extend([('lon', lon), ('lat', lat)]) else: url = self.make_url('features', uri) params.append(("timeout", int(self.fast_timeout * 1000))) raw_response = self.call_bragi(url, self.session.get, timeout=self.fast_timeout, params=params) return self.response_marshaler(raw_response, uri) def status(self): return {'class': self.__class__.__name__, 'timeout': self.timeout, 'fast_timeout': self.fast_timeout} def is_handling_stop_points(self): return False class GeocodeJsonError(AutocompleteError): pass class GeocodeJsonUnavailable(AutocompleteUnavailable): pass
agpl-3.0
michaelletzgus/nextcloud-server
settings/ajax/setquota.php
2916
<?php /** * @copyright Copyright (c) 2016, ownCloud, Inc. * * @author Arthur Schiwon <blizzz@arthur-schiwon.de> * @author Bart Visscher <bartv@thisnet.nl> * @author Björn Schießle <bjoern@schiessle.org> * @author Christopher Schäpers <kondou@ts.unde.re> * @author Felix Moeller <mail@felixmoeller.de> * @author Georg Ehrke <oc.list@georgehrke.com> * @author Joas Schilling <coding@schilljs.com> * @author Lukas Reschke <lukas@statuscode.ch> * @author Morris Jobke <hey@morrisjobke.de> * @author Robin Appelman <robin@icewind.nl> * @author Thomas Müller <thomas.mueller@tmit.eu> * * @license AGPL-3.0 * * This code is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License, version 3, * along with this program. If not, see <http://www.gnu.org/licenses/> * */ OC_JSON::checkSubAdminUser(); OCP\JSON::callCheck(); $lastConfirm = (int) \OC::$server->getSession()->get('last-password-confirm'); if ($lastConfirm < (time() - 30 * 60 + 15)) { // allow 15 seconds delay $l = \OC::$server->getL10N('core'); OC_JSON::error(array( 'data' => array( 'message' => $l->t('Password confirmation is required')))); exit(); } $username = isset($_POST["username"]) ? (string)$_POST["username"] : ''; $isUserAccessible = false; $currentUserObject = \OC::$server->getUserSession()->getUser(); $targetUserObject = \OC::$server->getUserManager()->get($username); if($targetUserObject !== null && $currentUserObject !== null) { $isUserAccessible = \OC::$server->getGroupManager()->getSubAdmin()->isUserAccessible($currentUserObject, $targetUserObject); } if(($username === '' && !OC_User::isAdminUser(OC_User::getUser())) || (!OC_User::isAdminUser(OC_User::getUser()) && !$isUserAccessible)) { $l = \OC::$server->getL10N('core'); OC_JSON::error(array( 'data' => array( 'message' => $l->t('Authentication error') ))); exit(); } //make sure the quota is in the expected format $quota= (string)$_POST["quota"]; if($quota !== 'none' and $quota !== 'default') { $quota= OC_Helper::computerFileSize($quota); $quota=OC_Helper::humanFileSize($quota); } // Return Success story if($username) { $targetUserObject->setQuota($quota); }else{//set the default quota when no username is specified if($quota === 'default') {//'default' as default quota makes no sense $quota='none'; } \OC::$server->getConfig()->setAppValue('files', 'default_quota', $quota); } OC_JSON::success(array("data" => array( "username" => $username , 'quota' => $quota)));
agpl-3.0
paulmartel/voltdb
tests/frontend/org/voltdb/TestRoutingEdgeCases.java
4473
/* This file is part of VoltDB. * Copyright (C) 2008-2016 VoltDB Inc. * * 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 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.voltdb; import java.nio.ByteBuffer; import java.nio.ByteOrder; import junit.framework.TestCase; import org.junit.Test; import org.voltdb.VoltDB.Configuration; import org.voltdb.client.Client; import org.voltdb.client.ClientFactory; import org.voltdb.client.ProcCallException; import org.voltdb.compiler.VoltProjectBuilder; import org.voltdb.utils.MiscUtils; public class TestRoutingEdgeCases extends TestCase { /** * Insert into a <8byte integer column using byte[] to send * the int. The column is also the partition column. Make sure * TheHashinator doesn't screw up. */ @Test public void testPartitionKeyAsBytes() throws Exception { ServerThread localServer = null; Client client = null; try { String simpleSchema = "create table blah (" + "ival integer default 0 not null, " + "PRIMARY KEY(ival)); " + "PARTITION TABLE blah ON COLUMN ival;"; VoltProjectBuilder builder = new VoltProjectBuilder(); builder.addLiteralSchema(simpleSchema); builder.addStmtProcedure("Insert", "insert into blah values (?);", null); boolean success = builder.compile(Configuration.getPathToCatalogForTest("edgecases.jar"), 7, 1, 0); assert(success); MiscUtils.copyFile(builder.getPathToDeployment(), Configuration.getPathToCatalogForTest("edgecases.xml")); VoltDB.Configuration config = new VoltDB.Configuration(); config.m_pathToCatalog = Configuration.getPathToCatalogForTest("edgecases.jar"); config.m_pathToDeployment = Configuration.getPathToCatalogForTest("edgecases.xml"); localServer = new ServerThread(config); localServer.start(); localServer.waitForInitialization(); client = ClientFactory.createClient(); client.createConnection("localhost"); try { ByteBuffer buf = ByteBuffer.allocate(4); buf.order(ByteOrder.LITTLE_ENDIAN); buf.putInt(7); byte[] value = buf.array(); client.callProcedure("Insert", value); fail(); } catch (ProcCallException pce) { assertTrue(pce.getMessage().contains("Array / Scalar parameter mismatch")); } // For now, @LoadSinglepartitionTable assumes 8 byte integers, even if type is < 8 bytes // This is ok because we don't expose this functionality. // The code below will throw a constraint violation, but it really shouldn't. There's // Another comment about this in ProcedureRunner about a reasonable fix for this. //VoltTable t = new VoltTable(new VoltTable.ColumnInfo("foo", VoltType.INTEGER)); //t.addRow(13); // //ByteBuffer buf = ByteBuffer.allocate(4); //buf.order(ByteOrder.LITTLE_ENDIAN); //buf.putInt(13); //byte[] value = buf.array(); //client.callProcedure("@LoadSinglepartitionTable", value, "blah", t); } finally { if (client != null) client.close(); if (localServer != null) localServer.shutdown(); } } }
agpl-3.0
gspringtech/pekoe-form
lib/ckeditor/config.js
1982
/** * @license Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.editorConfig = function( config ) { // Define changes to default configuration here. // For complete reference see: // http://docs.ckeditor.com/#!/api/CKEDITOR.config // The toolbar groups arrangement, optimized for two toolbar rows. /* config.toolbarGroups = [ { name: 'clipboard', groups: [ 'clipboard', 'undo' ] }, { name: 'editing', groups: [ 'find', 'selection', 'spellchecker' ] }, { name: 'links' }, { name: 'insert' }, { name: 'forms' }, { name: 'tools' }, { name: 'document', groups: [ 'mode', 'document', 'doctools' ] }, { name: 'others' }, '/', { name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ] }, { name: 'paragraph', groups: [ 'list', 'indent', 'blocks', 'align', 'bidi' ] }, { name: 'styles' }, { name: 'colors' }, { name: 'about' } ]; */ // Remove some buttons provided by the standard plugins, which are // not needed in the Standard(s) toolbar. config.removeButtons = 'Underline,Subscript,Superscript'; config.fontSize_sizes = '8/8pt;9/9pt;10/10pt;11/11pt;12/12pt;14/14pt;16/16pt;18/18pt;20/20pt;22/22pt;24/24pt;26/26pt;28/28pt;36/36pt;48/48pt;72/72pt'; config.font_names = 'Arial/Arial, Helvetica, sans-serif;' + 'Calibri/Calibri, Verdana, Geneva, sans-serif;' + 'Comic Sans MS/Comic Sans MS, cursive;' + 'Courier New/Courier New, Courier, monospace;' + 'Georgia/Georgia, serif;' + 'Lucida Sans Unicode/Lucida Sans Unicode, Lucida Grande, sans-serif;' + 'Tahoma/Tahoma, Geneva, sans-serif;' + 'Times New Roman/Times New Roman, Times, serif;' + 'Trebuchet MS/Trebuchet MS, Helvetica, sans-serif;' + 'Verdana/Verdana, Geneva, sans-serif'; // Set the most common block elements. config.format_tags = 'p;h1;h2;h3;pre'; // Simplify the dialog windows. config.removeDialogTabs = 'image:advanced;link:advanced'; };
agpl-3.0
bet0x/pipecode
post/user/journal/write.php
1422
<? // // Pipecode - distributed social network // Copyright (C) 2014-2015 Bryan Beicker <bryan@pipedot.org> // // 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/>. // include("clean.php"); require_mine(); $title = clean_subject(); $topic = clean_topic(); list($clean_body, $dirty_body) = clean_body(false, "journal"); $time = time(); $journal = db_new_rec("journal"); $journal["journal_id"] = create_short(TYPE_JOURNAL); $journal["body"] = $clean_body; $journal["edit_time"] = $time; $journal["photo_id"] = 0; $journal["publish_time"] = 0; $journal["published"] = 0; $journal["slug"] = clean_url($title); $journal["title"] = $title; $journal["topic"] = $topic; $journal["zid"] = $auth_zid; db_set_rec("journal", $journal); header("Location: /journal/" . crypt_crockford_encode($journal["journal_id"]));
agpl-3.0
Tatwi/legend-of-hondo
MMOCoreORB/bin/scripts/mobile/talus/docile_kahmurra.lua
822
docile_kahmurra = Creature:new { objectName = "@mob/creature_names:docile_kahmurra", socialGroup = "self", faction = "", level = 10, chanceHit = 0.28, damageMin = 80, damageMax = 90, baseXp = 292, baseHAM = 1000, baseHAMmax = 1200, armor = 0, resists = {0,0,110,0,0,0,0,-1,-1}, meatType = "meat_herbivore", meatAmount = 45, hideType = "hide_bristley", hideAmount = 27, boneType = "bone_mammal", boneAmount = 32, milkType = "milk_domesticated", milk = 20, tamingChance = 0, ferocity = 1, pvpBitmask = ATTACKABLE, creatureBitmask = NONE, optionsBitmask = AIENABLED, diet = HERBIVORE, templates = {"object/mobile/kahmurra.iff"}, scale = 0.9, lootGroups = {}, weapons = {}, conversationTemplate = "", attacks = { } } CreatureTemplates:addCreatureTemplate(docile_kahmurra, "docile_kahmurra")
agpl-3.0
lis-epfl/qgroundcontrol
src/ui/designer/QGCParamSlider.cc
19263
#include <QMenu> #include <QContextMenuEvent> #include <QSettings> #include <QTimer> #include <QToolTip> #include <QDebug> #include "QGCParamSlider.h" #include "ui_QGCParamSlider.h" #include "UASInterface.h" #include "UASManager.h" QGCParamSlider::QGCParamSlider(QWidget *parent) : QGCToolWidgetItem("Slider", parent), parameterName(""), parameterValue(0.0f), parameterScalingFactor(0.0), parameterMin(0.0f), parameterMax(0.0f), componentId(0), ui(new Ui::QGCParamSlider) { valueModLock = false; visibleEnabled = true; valueModLockParam = false; ui->setupUi(this); ui->intValueSpinBox->hide(); ui->valueSlider->setEnabled(false); ui->doubleValueSpinBox->setEnabled(false); uas = NULL; scaledInt = ui->valueSlider->maximum() - ui->valueSlider->minimum(); ui->editInfoCheckBox->hide(); ui->editDoneButton->hide(); ui->editNameLabel->hide(); ui->editRefreshParamsButton->hide(); ui->editSelectParamComboBox->hide(); ui->editSelectComponentComboBox->hide(); ui->editStatusLabel->hide(); ui->editMinSpinBox->hide(); ui->editMaxSpinBox->hide(); ui->editLine1->hide(); ui->editLine2->hide(); ui->infoLabel->hide(); connect(ui->editDoneButton, SIGNAL(clicked()), this, SLOT(endEditMode())); // Sending actions connect(ui->writeButton, SIGNAL(clicked()), this, SLOT(setParamPending())); connect(ui->editSelectComponentComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(selectComponent(int))); connect(ui->editSelectParamComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(selectParameter(int))); connect(ui->valueSlider, SIGNAL(valueChanged(int)), this, SLOT(setSliderValue(int))); connect(ui->doubleValueSpinBox, SIGNAL(valueChanged(double)), this, SLOT(setParamValue(double))); connect(ui->intValueSpinBox, SIGNAL(valueChanged(int)), this, SLOT(setParamValue(int))); connect(ui->editNameLabel, SIGNAL(textChanged(QString)), ui->nameLabel, SLOT(setText(QString))); connect(ui->readButton, SIGNAL(clicked()), this, SLOT(requestParameter())); connect(ui->editRefreshParamsButton, SIGNAL(clicked()), this, SLOT(refreshParamList())); connect(ui->editInfoCheckBox, SIGNAL(clicked(bool)), this, SLOT(showInfo(bool))); // connect to self connect(ui->infoLabel, SIGNAL(released()), this, SLOT(showTooltip())); init(); requestParameter(); } QGCParamSlider::~QGCParamSlider() { delete ui; } void QGCParamSlider::showTooltip() { QWidget* sender = dynamic_cast<QWidget*>(QObject::sender()); if (sender) { QPoint point = mapToGlobal(ui->infoLabel->pos()); QToolTip::showText(point, sender->toolTip()); } } void QGCParamSlider::refreshParamList() { ui->editSelectParamComboBox->setEnabled(true); ui->editSelectComponentComboBox->setEnabled(true); if (uas) { uas->getParamManager()->requestParameterList(); ui->editStatusLabel->setText(tr("Parameter list updating..")); } } void QGCParamSlider::setActiveUAS(UASInterface* activeUas) { if (uas != activeUas) { if (uas) { disconnect(uas, SIGNAL(parameterChanged(int,int,int,int,QString,QVariant)), this, SLOT(setParameterValue(int,int,int,int,QString,QVariant))); } if (activeUas) { connect(activeUas, SIGNAL(parameterChanged(int,int,int,int,QString,QVariant)), this, SLOT(setParameterValue(int,int,int,int,QString,QVariant)), Qt::UniqueConnection); } uas = activeUas; } if (uas && !parameterName.isEmpty()) { QString text = uas->getParamManager()->dataModel()->getParamDescription(parameterName); if (!text.isEmpty()) { ui->infoLabel->setToolTip(text); ui->infoLabel->show(); } // Force-uncheck and hide label if no description is available if (ui->editInfoCheckBox->isChecked()) { showInfo((text.length() > 0)); } } } void QGCParamSlider::requestParameter() { if (uas && !parameterName.isEmpty()) { uas->getParamManager()->requestParameterUpdate(componentId, parameterName); } } void QGCParamSlider::showInfo(bool enable) { ui->editInfoCheckBox->setChecked(enable); ui->infoLabel->setVisible(enable); } void QGCParamSlider::setParamValue(double value) { parameterValue = (float)value; //disconnect(ui->valueSlider,SIGNAL(valueChanged(int))); if (!valueModLock && !valueModLockParam) { valueModLock = true; ui->valueSlider->setValue(floatToScaledInt(value)); } else { valueModLock = false; } //connect(ui->valueSlider, SIGNAL(valueChanged(int)), this, SLOT(setSliderValue(int))); } void QGCParamSlider::setParamValue(int value) { parameterValue = value; // disconnect(ui->valueSlider,SIGNAL(valueChanged(int))); if (!valueModLock && !valueModLockParam) { valueModLock = true; ui->valueSlider->setValue(floatToScaledInt(value)); } else { valueModLock = false; } //connect(ui->valueSlider, SIGNAL(valueChanged(int)), this, SLOT(setSliderValue(int))); } void QGCParamSlider::selectComponent(int componentIndex) { this->componentId = ui->editSelectComponentComboBox->itemData(componentIndex).toInt(); } void QGCParamSlider::selectParameter(int paramIndex) { // Set name parameterName = ui->editSelectParamComboBox->itemText(paramIndex); if (parameterName.isEmpty()) { return; } // Update min and max values if available if (uas) { UASParameterDataModel* dataModel = uas->getParamManager()->dataModel(); if (dataModel) { // Minimum if (dataModel->isParamMinKnown(parameterName)) { parameterMin = dataModel->getParamMin(parameterName); ui->editMinSpinBox->setValue(parameterMin); } // Maximum if (dataModel->isParamMaxKnown(parameterName)) { parameterMax = dataModel->getParamMax(parameterName); ui->editMaxSpinBox->setValue(parameterMax); } } } } void QGCParamSlider::setEditMode(bool editMode) { if(!editMode) { // Store component id selectComponent(ui->editSelectComponentComboBox->currentIndex()); // Store parameter name and id selectParameter(ui->editSelectParamComboBox->currentIndex()); // Min/max parameterMin = ui->editMinSpinBox->value(); parameterMax = ui->editMaxSpinBox->value(); requestParameter(); switch ((int)parameterValue.type()) { case QVariant::Char: case QVariant::Int: case QVariant::UInt: ui->intValueSpinBox->show(); break; case QMetaType::Float: ui->doubleValueSpinBox->show(); break; default: qCritical() << "ERROR: NO VALID PARAM TYPE"; return; } } else { ui->doubleValueSpinBox->hide(); ui->intValueSpinBox->hide(); } ui->valueSlider->setVisible(!editMode); ui->nameLabel->setVisible(!editMode); ui->writeButton->setVisible(!editMode); ui->readButton->setVisible(!editMode); ui->editInfoCheckBox->setVisible(editMode); ui->editDoneButton->setVisible(editMode); ui->editNameLabel->setVisible(editMode); ui->editRefreshParamsButton->setVisible(editMode); ui->editSelectParamComboBox->setVisible(editMode); ui->editSelectComponentComboBox->setVisible(editMode); ui->editStatusLabel->setVisible(editMode); ui->editMinSpinBox->setVisible(editMode); ui->editMaxSpinBox->setVisible(editMode); ui->writeButton->setVisible(!editMode); ui->readButton->setVisible(!editMode); ui->editLine1->setVisible(editMode); ui->editLine2->setVisible(editMode); QGCToolWidgetItem::setEditMode(editMode); } void QGCParamSlider::setParamPending() { if (uas) { uas->getParamManager()->setPendingParam(componentId, parameterName, parameterValue); uas->getParamManager()->sendPendingParameters(true, true); } else { qDebug() << __FILE__ << __LINE__ << "NO UAS SET, DOING NOTHING"; } } void QGCParamSlider::setSliderValue(int sliderValue) { if (!valueModLock && !valueModLockParam) { valueModLock = true; switch ((int)parameterValue.type()) { case QVariant::Char: parameterValue = QVariant(QChar((unsigned char)scaledIntToFloat(sliderValue))); ui->intValueSpinBox->setValue(parameterValue.toInt()); break; case QVariant::Int: parameterValue = (int)scaledIntToFloat(sliderValue); ui->intValueSpinBox->setValue(parameterValue.toInt()); break; case QVariant::UInt: parameterValue = (unsigned int)scaledIntToFloat(sliderValue); ui->intValueSpinBox->setValue(parameterValue.toUInt()); break; case QMetaType::Float: parameterValue = scaledIntToFloat(sliderValue); ui->doubleValueSpinBox->setValue(parameterValue.toFloat()); break; default: qCritical() << "ERROR: NO VALID PARAM TYPE"; valueModLock = false; return; } } else { valueModLock = false; } } /** * @brief uas Unmanned system sending the parameter * @brief component UAS component sending the parameter * @brief parameterName Key/name of the parameter * @brief value Value of the parameter */ void QGCParamSlider::setParameterValue(int uasId, int compId, int paramCount, int paramIndex, QString paramName, QVariant value) { Q_UNUSED(paramCount); if (uasId != this->uas->getUASID()) { return; } if (ui->nameLabel->text() == "Name") { ui->nameLabel->setText(paramName); } // Check if this component and parameter are part of the list bool found = false; for (int i = 0; i< ui->editSelectComponentComboBox->count(); ++i) { if (compId == ui->editSelectComponentComboBox->itemData(i).toInt()) { found = true; } } if (!found) { ui->editSelectComponentComboBox->addItem(tr("Component #%1").arg(compId), compId); } // Parameter checking found = false; for (int i = 0; i < ui->editSelectParamComboBox->count(); ++i) { if (paramName == ui->editSelectParamComboBox->itemText(i)) { found = true; } } if (!found) { ui->editSelectParamComboBox->addItem(paramName, paramIndex); } if (visibleParam != "") { if (paramName == visibleParam) { if (visibleVal == value.toInt()) { uas->getParamManager()->requestParameterUpdate(compId,paramName); visibleEnabled = true; this->show(); } else { //Disable the component here. ui->valueSlider->setEnabled(false); ui->intValueSpinBox->setEnabled(false); ui->doubleValueSpinBox->setEnabled(false); visibleEnabled = false; this->hide(); } } } Q_UNUSED(uas); if (compId == this->componentId && paramName == this->parameterName) { if (!visibleEnabled) { return; } parameterValue = value; ui->valueSlider->setEnabled(true); valueModLockParam = true; switch ((int)value.type()) { case QVariant::Char: ui->intValueSpinBox->show(); ui->intValueSpinBox->setEnabled(true); ui->doubleValueSpinBox->hide(); ui->intValueSpinBox->setValue(value.toUInt()); ui->intValueSpinBox->setRange(0, UINT8_MAX); if (parameterMax == 0 && parameterMin == 0) { ui->editMaxSpinBox->setValue(UINT8_MAX); ui->editMinSpinBox->setValue(0); } ui->valueSlider->setValue(floatToScaledInt(value.toUInt())); break; case QVariant::Int: ui->intValueSpinBox->show(); ui->intValueSpinBox->setEnabled(true); ui->doubleValueSpinBox->hide(); ui->intValueSpinBox->setValue(value.toInt()); ui->intValueSpinBox->setRange(INT32_MIN, INT32_MAX); if (parameterMax == 0 && parameterMin == 0) { ui->editMaxSpinBox->setValue(INT32_MAX); ui->editMinSpinBox->setValue(INT32_MIN); } ui->valueSlider->setValue(floatToScaledInt(value.toInt())); break; case QVariant::UInt: ui->intValueSpinBox->show(); ui->intValueSpinBox->setEnabled(true); ui->doubleValueSpinBox->hide(); ui->intValueSpinBox->setValue(value.toUInt()); ui->intValueSpinBox->setRange(0, UINT32_MAX); if (parameterMax == 0 && parameterMin == 0) { ui->editMaxSpinBox->setValue(UINT32_MAX); ui->editMinSpinBox->setValue(0); } ui->valueSlider->setValue(floatToScaledInt(value.toUInt())); break; case QMetaType::Float: ui->doubleValueSpinBox->setValue(value.toFloat()); ui->doubleValueSpinBox->show(); ui->doubleValueSpinBox->setEnabled(true); ui->intValueSpinBox->hide(); if (parameterMax == 0 && parameterMin == 0) { ui->editMaxSpinBox->setValue(10000); ui->editMinSpinBox->setValue(0); } ui->valueSlider->setValue(floatToScaledInt(value.toFloat())); break; default: qCritical() << "ERROR: NO VALID PARAM TYPE"; valueModLockParam = false; return; } valueModLockParam = false; parameterMax = ui->editMaxSpinBox->value(); parameterMin = ui->editMinSpinBox->value(); } if (paramIndex == paramCount - 1) { ui->editStatusLabel->setText(tr("Complete parameter list received.")); } } void QGCParamSlider::changeEvent(QEvent *e) { QWidget::changeEvent(e); switch (e->type()) { case QEvent::LanguageChange: ui->retranslateUi(this); break; default: break; } } float QGCParamSlider::scaledIntToFloat(int sliderValue) { float result = (((double)sliderValue)/(double)scaledInt)*(ui->editMaxSpinBox->value() - ui->editMinSpinBox->value()); //qDebug() << "INT TO FLOAT: CONVERTED" << sliderValue << "TO" << result; return result; } int QGCParamSlider::floatToScaledInt(float value) { int result = ((value - ui->editMinSpinBox->value())/(ui->editMaxSpinBox->value() - ui->editMinSpinBox->value()))*scaledInt; //qDebug() << "FLOAT TO INT: CONVERTED" << value << "TO" << result << "SCALEDINT" << scaledInt; return result; } void QGCParamSlider::writeSettings(QSettings& settings) { settings.setValue("TYPE", "SLIDER"); settings.setValue("QGC_PARAM_SLIDER_DESCRIPTION", ui->nameLabel->text()); //settings.setValue("QGC_PARAM_SLIDER_BUTTONTEXT", ui->actionButton->text()); settings.setValue("QGC_PARAM_SLIDER_PARAMID", parameterName); settings.setValue("QGC_PARAM_SLIDER_COMPONENTID", componentId); settings.setValue("QGC_PARAM_SLIDER_MIN", ui->editMinSpinBox->value()); settings.setValue("QGC_PARAM_SLIDER_MAX", ui->editMaxSpinBox->value()); settings.setValue("QGC_PARAM_SLIDER_DISPLAY_INFO", ui->editInfoCheckBox->isChecked()); settings.sync(); } void QGCParamSlider::readSettings(const QString& pre,const QVariantMap& settings) { parameterName = settings.value(pre + "QGC_PARAM_SLIDER_PARAMID").toString(); componentId = settings.value(pre + "QGC_PARAM_SLIDER_COMPONENTID").toInt(); ui->nameLabel->setText(settings.value(pre + "QGC_PARAM_SLIDER_DESCRIPTION").toString()); ui->editNameLabel->setText(settings.value(pre + "QGC_PARAM_SLIDER_DESCRIPTION").toString()); //settings.setValue("QGC_PARAM_SLIDER_BUTTONTEXT", ui->actionButton->text()); ui->editSelectParamComboBox->addItem(settings.value(pre + "QGC_PARAM_SLIDER_PARAMID").toString()); ui->editSelectParamComboBox->setCurrentIndex(ui->editSelectParamComboBox->count()-1); ui->editSelectComponentComboBox->addItem(tr("Component #%1").arg(settings.value(pre + "QGC_PARAM_SLIDER_COMPONENTID").toInt()), settings.value(pre + "QGC_PARAM_SLIDER_COMPONENTID").toInt()); ui->editMinSpinBox->setValue(settings.value(pre + "QGC_PARAM_SLIDER_MIN").toFloat()); ui->editMaxSpinBox->setValue(settings.value(pre + "QGC_PARAM_SLIDER_MAX").toFloat()); visibleParam = settings.value(pre+"QGC_PARAM_SLIDER_VISIBLE_PARAM","").toString(); visibleVal = settings.value(pre+"QGC_PARAM_SLIDER_VISIBLE_VAL",0).toInt(); parameterMax = ui->editMaxSpinBox->value(); parameterMin = ui->editMinSpinBox->value(); //ui->valueSlider->setMaximum(parameterMax); //ui->valueSlider->setMinimum(parameterMin); showInfo(settings.value(pre + "QGC_PARAM_SLIDER_DISPLAY_INFO", true).toBool()); ui->editSelectParamComboBox->setEnabled(true); ui->editSelectComponentComboBox->setEnabled(true); setActiveUAS(UASManager::instance()->getActiveUAS()); } void QGCParamSlider::readSettings(const QSettings& settings) { QVariantMap map; foreach (QString key,settings.allKeys()) { map[key] = settings.value(key); } readSettings("",map); return; parameterName = settings.value("QGC_PARAM_SLIDER_PARAMID").toString(); componentId = settings.value("QGC_PARAM_SLIDER_COMPONENTID").toInt(); ui->nameLabel->setText(settings.value("QGC_PARAM_SLIDER_DESCRIPTION").toString()); ui->editNameLabel->setText(settings.value("QGC_PARAM_SLIDER_DESCRIPTION").toString()); //settings.setValue("QGC_PARAM_SLIDER_BUTTONTEXT", ui->actionButton->text()); ui->editSelectParamComboBox->addItem(settings.value("QGC_PARAM_SLIDER_PARAMID").toString()); ui->editSelectParamComboBox->setCurrentIndex(ui->editSelectParamComboBox->count()-1); ui->editSelectComponentComboBox->addItem(tr("Component #%1").arg(settings.value("QGC_PARAM_SLIDER_COMPONENTID").toInt()), settings.value("QGC_PARAM_SLIDER_COMPONENTID").toInt()); ui->editMinSpinBox->setValue(settings.value("QGC_PARAM_SLIDER_MIN").toFloat()); ui->editMaxSpinBox->setValue(settings.value("QGC_PARAM_SLIDER_MAX").toFloat()); visibleParam = settings.value("QGC_PARAM_SLIDER_VISIBLE_PARAM","").toString(); //QGC_TOOL_WIDGET_ITEMS\1\QGC_PARAM_SLIDER_VISIBLE_PARAM=RC5_FUNCTION visibleVal = settings.value("QGC_PARAM_SLIDER_VISIBLE_VAL",0).toInt(); parameterMax = ui->editMaxSpinBox->value(); parameterMin = ui->editMinSpinBox->value(); showInfo(settings.value("QGC_PARAM_SLIDER_DISPLAY_INFO", true).toBool()); ui->editSelectParamComboBox->setEnabled(true); ui->editSelectComponentComboBox->setEnabled(true); setActiveUAS(UASManager::instance()->getActiveUAS()); }
agpl-3.0
metrodango/pip3line
defaultplugins/baseplugins/sha3_384.cpp
926
/** Released as open source by Gabriel Caudrelier Developed by Gabriel Caudrelier, gabriel dot caudrelier at gmail dot com https://github.com/metrodango/pip3line Released under AGPL see LICENSE for more information **/ #include "sha3_384.h" #include <QCryptographicHash> const QString Sha3_384::id = "SHA3-384"; Sha3_384::Sha3_384() { } Sha3_384::~Sha3_384() { } QString Sha3_384::name() const { return id; } QString Sha3_384::description() const { return tr("Sha3-384 hash"); } bool Sha3_384::isTwoWays() { return false; } QString Sha3_384::help() const { QString help; help.append("<p>Sha3-384 hash</p><p>This transformation is using the QT internal hash function.</p>"); return help; } void Sha3_384::transform(const QByteArray &input, QByteArray &output) { output = QCryptographicHash::hash(input,QCryptographicHash::Sha3_384); }
agpl-3.0
mcosand/KCSARA-database-foo
src/Website/Api/Models/Document.cs
517
/* * Copyright (c) 2013 Matt Cosand */ namespace Kcsar.Database.Website.Api.Models { using System; public class Document { public Guid Id { get; set; } public string Type { get; set; } public Guid Reference { get; set; } public string Title { get; set; } public int Size { get; set; } public string Mime { get; set; } public DateTime? Changed { get; set; } public string Url { get; set; } public string Thumbnail { get; set; } } }
agpl-3.0
Trustroots/trustroots
modules/users/client/components/BlockedMemberBanner.component.js
872
/** * Banner that describes that user is blocked */ import '@/config/client/i18n'; import { useTranslation } from 'react-i18next'; import PropTypes from 'prop-types'; import React from 'react'; import BlockMember from './BlockMember.component'; import ReportMember from '@/modules/support/client/components/ReportMember.component.js'; export default function BlockedMemberBanner({ username }) { const { t } = useTranslation('users'); return ( <div className="alert alert-warning" role="alert"> <p> {t('You have blocked this member.')}{' '} {t('They cannot see or message you.')} <ReportMember username={username} className="btn btn-link" /> <BlockMember isBlocked username={username} className="btn btn-link" /> </p> </div> ); } BlockedMemberBanner.propTypes = { username: PropTypes.string.isRequired, };
agpl-3.0
unitystation/unitystation
UnityProject/Assets/Scripts/UI/Items/PDA/GUI_PDAMainMenu.cs
1716
using System; using UnityEngine; using UI.Core.NetUI; namespace UI.Items.PDA { public class GUI_PDAMainMenu : NetPage, IPageReadyable { [SerializeField] private GUI_PDA controller = null; [SerializeField] private NetLabel idLabel = null; [SerializeField] private NetLabel lightLabel = null; private IDCard IDCard => controller.PDA.GetIDCard(); private void Start() { controller.PDA.idSlotUpdated += UpdateIDStatus; } public void OnPageActivated() { UpdateElements(); } public void EjectID() { controller.PDA.EjectIDCard(); UpdateIDStatus(); UpdateBreadcrumb(); } public void ToggleFlashlight() { controller.PDA.ToggleFlashlight(); UpdateFlashlightText(); } private void UpdateElements() { UpdateBreadcrumb(); UpdateIDStatus(); UpdateFlashlightText(); } private void UpdateBreadcrumb() { //Checks to see if the PDA has a registered name, if it does make that the Desktop name if (controller.PDA.RegisteredPlayerName != null) { string editedString = controller.PDA.RegisteredPlayerName.Replace(" ", "_"); controller.SetBreadcrumb($"/home/{editedString}/Desktop"); } else { controller.SetBreadcrumb("/home/Guest/Desktop"); } } private void UpdateIDStatus() { SetIDStatus(IDCard != null ? $"{IDCard.RegisteredName}, {IDCard.GetJobTitle()}" : "<No ID Inserted>"); if (controller.mainSwitcher.CurrentPage == this) { UpdateBreadcrumb(); } } private void UpdateFlashlightText() { lightLabel.SetValueServer(controller.PDA.FlashlightOn ? "Flashlight (ON)" : "Flashlight (OFF)"); } private void SetIDStatus(string status) { idLabel.SetValueServer(status); } } }
agpl-3.0
Terradue/DotNetOpenSearch
Terradue.OpenSearch.Test/CacheTest.cs
1733
using System; using log4net.Config; using System.IO; using Terradue.OpenSearch.Engine; using Terradue.OpenSearch.Filters; using System.Collections.Specialized; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using System.Linq; using log4net; using System.Reflection; using Xunit; namespace Terradue.OpenSearch.Test { public class CacheTest : IClassFixture<TestFixture> { OpenSearchEngine ose; OpenSearchableFactorySettings settings; public CacheTest() { ose = new OpenSearchEngine(); ose.LoadPlugins(); settings = new OpenSearchableFactorySettings(ose); OpenSearchMemoryCache cache = new OpenSearchMemoryCache(); ose.RegisterPreSearchFilter(cache.TryReplaceWithCacheRequest); ose.RegisterPostSearchFilter(cache.CacheResponse); } [Fact(DisplayName = "Cache Test #1")] [Trait("Category", "unit")] public void CacheTest1() { TestOpenSearchable entity1 = TestOpenSearchable.GenerateNumberedItomFeed("A", 100, new TimeSpan(0)); ose.Query(entity1, new NameValueCollection()); List<IOpenSearchable> entities = new List<IOpenSearchable>(); entities.Add(entity1); entity1.Items.First().Identifier = "AA1"; entity1.OnOpenSearchableChange(this, new OnOpenSearchableChangeEventArgs(entity1)); ose.Query(entity1, new NameValueCollection()); Thread.Sleep(1000); ose.Query(entity1, new NameValueCollection()); IOpenSearchable multiEntity = new MultiGenericOpenSearchable(entities, settings, true); } } }
agpl-3.0
fossaag/rolp
test/org/fossa/vaadin/test/laso/AllLasoTests.java
251
package org.fossa.vaadin.test.laso; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) @SuiteClasses({ FossaLasoTest.class }) public class AllLasoTests { }
agpl-3.0
myplaceonline/myplaceonline_rails
app/models/hotel.rb
640
class Hotel < ApplicationRecord include MyplaceonlineActiveRecordIdentityConcern include AllowExistingConcern child_property(name: :location, required: true) def display result = location.display_really_simple #result = Myp.appendstr(result, room_number.to_s, nil, " (" + I18n.t("myplaceonline.hotels.room_number") + " ", ")") result end def self.category_split_button_link Rails.application.routes.url_helpers.send("#{self.table_name}_map_path") end def self.category_split_button_title I18n.t("myplaceonline.general.map") end def self.category_split_button_icon "navigation" end end
agpl-3.0
vodkina/GlobaLeaks
backend/globaleaks/tests/handlers/test_token.py
2081
# -*- encoding: utf-8 -*- from twisted.internet.defer import inlineCallbacks from globaleaks.anomaly import Alarm from globaleaks.handlers import token from globaleaks.tests import helpers from globaleaks.utils.token import Token from globaleaks.rest import errors from globaleaks.settings import GLSettings class Test_TokenCreate(helpers.TestHandlerWithPopulatedDB): _handler = token.TokenCreate def assert_default_token_values(self, token): self.assertEqual(token['type'], u'submission') self.assertEqual(token['remaining_uses'], Token.MAX_USES) self.assertEqual(token['human_captcha_answer'], 0) @inlineCallbacks def test_post(self): yield Alarm.compute_activity_level() handler = self.request({'type': 'submission'}) yield handler.post() token = self.responses[0] self.assert_default_token_values(token) class Test_TokenInstance(helpers.TestHandlerWithPopulatedDB): _handler = token.TokenInstance @inlineCallbacks def test_put_right_answer(self): self.pollute_events() yield Alarm.compute_activity_level() token = Token('submission') token.human_captcha = {'question': 'XXX','answer': 1, 'solved': False} token.proof_of_work['solved'] = True request_payload = token.serialize() request_payload['human_captcha_answer'] = 1 handler = self.request(request_payload) yield handler.put(token.id) token.use() self.assertFalse(self.responses[0]['human_captcha']) self.assertTrue(token.human_captcha['solved']) @inlineCallbacks def test_put_wrong_answer(self): self.pollute_events() yield Alarm.compute_activity_level() token = Token('submission') token.human_captcha = {'question': 'XXX','answer': 1, 'solved': False} request_payload = token.serialize() request_payload['human_captcha_answer'] = 883 handler = self.request(request_payload) self.assertRaises(errors.TokenFailure, handler.put, token.id)
agpl-3.0
tickbox-smc-ltd/xfero
src/xfero/test/test_manage_partner.py
27931
#!/usr/bin/env python ''' Test Manage Partner''' import unittest import configparser import os import sqlite3 as lite from /xfero/.db import manage_partner as db_partner from /xfero/.db import create_XFERO_DB as db class Test(unittest.TestCase): ''' **Purpose:** Unit Test class for the function ```crud_XFERO_Partner``` **Usage Notes:** XFERO stores the database location and database name in an ini file which is found in <INSTALL_DIR>/conf/XFERO_config.ini. Before proceeding with the test please ensure that the XFERO_config.ini file has been suitably modified for the purposes of this test. **Warning:** ALL DATABASE TABLE WILL BE DROPPED DURING THE EXECUTION OF THESE TESTS *External dependencies* os (/xfero/.test.test_manage_partner) /xfero/ db create_XFERO_DB (/xfero/.test.test_manage_partner) manage_partner (/xfero/.test.test_manage_partner) +------------+-------------+-----------------------------------------------+ | Date | Author | Change Details | +============+=============+===============================================+ | 02/06/2013 | Chris Falck | Created | +------------+-------------+-----------------------------------------------+ | 08/01/2014 | Chris Falck | Tested to confirm changes to DB | +------------+-------------+-----------------------------------------------+ ''' def setUp(self): ''' **Purpose:** Create a test /Xfero/ Database ''' # Create the database db.create_db() def tearDown(self): ''' **Purpose:** Delete the test /Xfero/ Database. **Usage Notes:** XFERO stores the database location and database name in an ini file which is found in <INTALL_DIR>/conf/XFERO_config.ini. ''' config = configparser.RawConfigParser() try: config.read('conf/XFERO_config.ini') except configparser.Error as err: raise err xfero_db = config.get('database', 'db_location') # Delete the test DB os.remove(xfero_db) def test_create_XFERO_Partner(self): ''' **Purpose:** INSERT rows into the XFERO_Partner table and confirm they have been successfully inserted. +------------+-------------+-------------------------------------------+ | Date | Author | Change Details | +============+=============+===========================================+ | 02/06/2013 | Chris Falck | Created | +------------+-------------+-------------------------------------------+ | 08/01/2014 | Chris Falck | Added additional inputs to be tested | +------------+-------------+-------------------------------------------+ | 10/01/2014 | Chris Falck | Tested to confirm changes to DB | +------------+-------------+-------------------------------------------+ ''' for tst in [('WIN1', 'Win2008 Server 1', 'SFTPPlus', '192.168.0.65', '', '', '', '', 'xfero', 'xferopassword', '', '', '10021', '', '', 'key1'), ('WIN2', 'Win2008 Server 2', 'SFTPPlus', '192.168.0.66', '', '', '', '', 'xfero', 'xferopassword', '', '', '10221', '', '', 'key2'), ('CENT1', 'CentOS6 Server 1', 'SFTPPlus', '192.168.0.11', '', '', '', '', 'xfero', 'xferopassword', '', '', '10121', '', '', 'key3'), ('CENT2', 'CentOS6 Server 2', 'SFTPPlus', '192.168.0.12', '', '', '', '', 'xfero', 'xferopassword', '', '', '10321', '', '', 'key4'),]: (partner_service_name, partner_service_description, partner_COTS_type, partner_remote_system_id, partner_code, partner_mode, partner_local_username, partner_local_password, partner_remote_user, partner_remote_password, partner_CA_certificate, partner_cert_bundle, partner_control_port, partner_IDF, partner_parm, partner_pub_key) = tst result = db_partner.create_XFERO_Partner(partner_service_name, partner_service_description, partner_COTS_type, partner_remote_system_id, partner_code, partner_mode, partner_local_username, partner_local_password, partner_remote_user, partner_remote_password, partner_CA_certificate, partner_cert_bundle, partner_control_port, partner_IDF, partner_parm, partner_pub_key) config = configparser.RawConfigParser() try: config.read('conf/XFERO_config.ini') except configparser.Error as err: raise err xfero_db = config.get('database', 'db_location') con = lite.connect(xfero_db) try: cur = con.cursor() cur = con.execute("pragma foreign_keys=ON") cur.execute('SELECT partner_id FROM XFERO_Partner') except lite.Error as err: print("Error %s:" % err.args[0]) expected_tuple = ((1,), (2,), (3,), (4,)) rows = cur.fetchall() for row in rows: self.assertIn(row, expected_tuple, 'Unexpected row retrieved') def test_read_XFERO_Partner(self): ''' **Purpose:** SELECT a specified row from the XFERO_Patner table with partner_id = 1 and confirm that the row returned is as expected +------------+-------------+-------------------------------------------+ | Date | Author | Change Details | +============+=============+===========================================+ | 02/06/2013 | Chris Falck | Created | +------------+-------------+-------------------------------------------+ | 10/01/2014 | Chris Falck | Tested to confirm changes to DB | +------------+-------------+-------------------------------------------+ ''' # Create the row in the database for tst in [('WIN1', 'Win2008 Server 1', 'SFTPPlus', '192.168.0.65', '', '', '', '', 'xfero', 'xferopassword', '', '', '10021', '', '', 'key1'),]: (partner_service_name, partner_service_description, partner_COTS_type, partner_remote_system_id, partner_code, partner_mode, partner_local_username, partner_local_password, partner_remote_user, partner_remote_password, partner_CA_certificate, partner_cert_bundle, partner_control_port, partner_IDF, partner_parm, partner_pub_key) = tst result = db_partner.create_XFERO_Partner(partner_service_name, partner_service_description, partner_COTS_type, partner_remote_system_id, partner_code, partner_mode, partner_local_username, partner_local_password, partner_remote_user, partner_remote_password, partner_CA_certificate, partner_cert_bundle, partner_control_port, partner_IDF, partner_parm, partner_pub_key) # Perform the select self.partner_id = '1' rows = db_partner.read_XFERO_Partner(self.partner_id) expected_tuple = (1, 'WIN1', 'Win2008 Server 1', 'SFTPPlus', '192.168.0.65', '', '', '', '', 'xfero', 'xferopassword', '', '', 10021, '', '', 'key1') self.assertTupleEqual(expected_tuple, rows, 'Unexpected row retrieved') def test_read_psn_XFERO_Partner(self): ''' **Purpose:** SELECT a specified row from the XFERO_Patner table with partner_service_name and confirm that the row returned is as expected +------------+-------------+-------------------------------------------+ | Date | Author | Change Details | +============+=============+===========================================+ | 02/06/2013 | Chris Falck | Created | +------------+-------------+-------------------------------------------+ | 10/01/2014 | Chris Falck | Tested to confirm changes to DB | +------------+-------------+-------------------------------------------+ ''' # Create the row in the database for tst in [('WIN1', 'Win2008 Server 1', 'SFTPPlus', '192.168.0.65', '', '', '', '', 'xfero', 'xferopassword', '', '', '10021', '', '', 'key1'),]: (partner_service_name, partner_service_description, partner_COTS_type, partner_remote_system_id, partner_code, partner_mode, partner_local_username, partner_local_password, partner_remote_user, partner_remote_password, partner_CA_certificate, partner_cert_bundle, partner_control_port, partner_IDF, partner_parm, partner_pub_key) = tst result = db_partner.create_XFERO_Partner(partner_service_name, partner_service_description, partner_COTS_type, partner_remote_system_id, partner_code, partner_mode, partner_local_username, partner_local_password, partner_remote_user, partner_remote_password, partner_CA_certificate, partner_cert_bundle, partner_control_port, partner_IDF, partner_parm, partner_pub_key) # Perform the select self.partner_service_name = 'WIN1' rows = db_partner.read_psn_XFERO_Partner(self.partner_service_name) for row in rows: expected_tuple = (1, 'WIN1', 'Win2008 Server 1', 'SFTPPlus', '192.168.0.65', '', '', '', '', 'xfero', 'xferopassword', '', '', 10021, '', '', 'key1') self.assertTupleEqual( expected_tuple, row, 'Unexpected row retrieved') def test_update_XFERO_Partner(self): ''' **Purpose:** UPDATE row on the XFERO_Partner table with partner_id = 1 and confirm that the update has been applied to the table. +------------+-------------+-------------------------------------------+ | Date | Author | Change Details | +============+=============+===========================================+ | 02/06/2013 | Chris Falck | Created | +------------+-------------+-------------------------------------------+ | 10/01/2014 | Chris Falck | Tested to confirm changes to DB | +------------+-------------+-------------------------------------------+ ''' # Create the row in the database for tst in [('WIN1', 'Win2008 Server 1', 'SFTPPlus', '192.168.0.65', '', '', '', '', 'xfero', 'xferopassword', '', '', '10021', '', '', 'key1'),]: (partner_service_name, partner_service_description, partner_COTS_type, partner_remote_system_id, partner_code, partner_mode, partner_local_username, partner_local_password, partner_remote_user, partner_remote_password, partner_CA_certificate, partner_cert_bundle, partner_control_port, partner_IDF, partner_parm, partner_pub_key) = tst result = db_partner.create_XFERO_Partner(partner_service_name, partner_service_description, partner_COTS_type, partner_remote_system_id, partner_code, partner_mode, partner_local_username, partner_local_password, partner_remote_user, partner_remote_password, partner_CA_certificate, partner_cert_bundle, partner_control_port, partner_IDF, partner_parm, partner_pub_key) # Perform the select self.partner_id = '1' self.partner_service_name = 'Test' self.partner_service_description = 'TEST' self.partner_COTS_type = 'Testing' self.partner_remote_system_id = 'Falck' self.partner_code = 'b' self.partner_mode = 'w' self.partner_local_username = 'test' self.partner_local_password = 'test' self.partner_remote_user = 'test' self.partner_remote_password = 'test' self.partner_CA_certificate = 'CA_cert_bundle' self.partner_cert_bundle = 'cert_bundle' self.partner_control_port = '10121' self.partner_IDF = 'idf' self.partner_parm = 'parm' self.partner_pub_key = 'pub_key' result = db_partner.update_XFERO_Partner(self.partner_id, self.partner_service_name, self.partner_service_description, self.partner_COTS_type, self.partner_remote_system_id, self.partner_code, self.partner_mode, self.partner_local_username, self.partner_local_password, self.partner_remote_user, self.partner_remote_password, self.partner_CA_certificate, self.partner_cert_bundle, self.partner_control_port, self.partner_IDF, self.partner_parm, self.partner_pub_key) # Check update rows = db_partner.read_XFERO_Partner(self.partner_id) expected_tuple = (1, 'Test', 'TEST', 'Testing', 'Falck', 'b', 'w', 'test', 'test', 'test', 'test', 'CA_cert_bundle', 'cert_bundle', 10121, 'idf', 'parm', 'pub_key') # for row in rows: self.assertTupleEqual(expected_tuple, rows, 'Unexpected row retrieved') def test_delete_XFERO_Partner(self): ''' **Purpose:** DELETE row on the XFERO_Partner table with Partner ID = 1 and confirm that the deletion has been successful. +------------+-------------+-------------------------------------------+ | Date | Author | Change Details | +============+=============+===========================================+ | 02/06/2013 | Chris Falck | Created | +------------+-------------+-------------------------------------------+ | 10/01/2014 | Chris Falck | Tested to confirm changes to DB | +------------+-------------+-------------------------------------------+ ''' # Create the row in the database for tst in [('WIN1', 'Win2008 Server 1', 'SFTPPlus', '192.168.0.65', '', '', '', '', 'xfero', 'xferopassword', '', '', '10021', '', '', 'key1'),]: (partner_service_name, partner_service_description, partner_COTS_type, partner_remote_system_id, partner_code, partner_mode, partner_local_username, partner_local_password, partner_remote_user, partner_remote_password, partner_CA_certificate, partner_cert_bundle, partner_control_port, partner_IDF, partner_parm, partner_pub_key) = tst result = db_partner.create_XFERO_Partner(partner_service_name, partner_service_description, partner_COTS_type, partner_remote_system_id, partner_code, partner_mode, partner_local_username, partner_local_password, partner_remote_user, partner_remote_password, partner_CA_certificate, partner_cert_bundle, partner_control_port, partner_IDF, partner_parm, partner_pub_key) # Perform the test self.partner_id = '1' rows = db_partner.delete_XFERO_Partner(self.partner_id) # Check update config = configparser.RawConfigParser() try: config.read('conf/XFERO_config.ini') except configparser.Error as e: raise e xfero_db = config.get('database', 'db_location') con = lite.connect(xfero_db) try: cur = con.cursor() cur = con.execute("pragma foreign_keys=ON") cur.execute('SELECT count(*) FROM XFERO_Partner') except lite.Error as e: print("Error %s:" % e.args[0]) data = cur.fetchone()[0] expected = 0 self.assertEqual(expected == data, True, "Unexpected row selected") def test_list_XFERO_Partner(self): ''' **Purpose:** SELECT ALL rows on the XFERO_Partner table and confirm that all rows have been returned successfully. +------------+-------------+-------------------------------------------+ | Date | Author | Change Details | +============+=============+===========================================+ | 02/06/2013 | Chris Falck | Created | +------------+-------------+-------------------------------------------+ | 08/01/2014 | Chris Falck | Added additional inputs to be tested | +------------+-------------+-------------------------------------------+ | 10/01/2014 | Chris Falck | Tested to confirm changes to DB | +------------+-------------+-------------------------------------------+ ''' expected_tuple = ((1, 'WIN1', 'Win2008 Server 1', 'SFTPPlus', '192.168.0.65', '', '', '', '', 'xfero', 'xferopassword', '', '', 10021, '', '', 'key1'), (2, 'WIN2', 'Win2008 Server 2', 'SFTPPlus', '192.168.0.66', '', '', '', '', 'xfero', 'xferopassword', '', '', 10221, '', '', 'key2'), (3, 'CENT1', 'CentOS6 Server 1', 'SFTPPlus', '192.168.0.11', '', '', '', '', 'xfero', 'xferopassword', '', '', 10121, '', '', 'key3'), (4, 'CENT2', 'CentOS6 Server 2', 'SFTPPlus', '192.168.0.12', '', '', '', '', 'xfero', 'xferopassword', '', '', 10321, '', '', 'key4')) for tst in [('WIN1', 'Win2008 Server 1', 'SFTPPlus', '192.168.0.65', '', '', '', '', 'xfero', 'xferopassword', '', '', '10021', '', '', 'key1'), ('WIN2', 'Win2008 Server 2', 'SFTPPlus', '192.168.0.66', '', '', '', '', 'xfero', 'xferopassword', '', '', '10221', '', '', 'key2'), ('CENT1', 'CentOS6 Server 1', 'SFTPPlus', '192.168.0.11', '', '', '', '', 'xfero', 'xferopassword', '', '', '10121', '', '', 'key3'), ('CENT2', 'CentOS6 Server 2', 'SFTPPlus', '192.168.0.12', '', '', '', '', 'xfero', 'xferopassword', '', '', '10321', '', '', 'key4'), ]: (partner_service_name, partner_service_description, partner_COTS_type, partner_remote_system_id, partner_code, partner_mode, partner_local_username, partner_local_password, partner_remote_user, partner_remote_password, partner_CA_certificate, partner_cert_bundle, partner_control_port, partner_IDF, partner_parm, partner_pub_key) = tst result = db_partner.create_XFERO_Partner(partner_service_name, partner_service_description, partner_COTS_type, partner_remote_system_id, partner_code, partner_mode, partner_local_username, partner_local_password, partner_remote_user, partner_remote_password, partner_CA_certificate, partner_cert_bundle, partner_control_port, partner_IDF, partner_parm, partner_pub_key) rows = db_partner.list_XFERO_Partner() for row in rows: self.assertIn(row, expected_tuple, 'Unexpected row selected') def test_list_service_name_XFERO_Partner(self): ''' **Purpose:** SELECT ALL rows from the XFERO_Partner table returning only the service name and confirm that all rows have been returned successfully. +------------+-------------+-------------------------------------------+ | Date | Author | Change Details | +============+=============+===========================================+ | 02/06/2013 | Chris Falck | Created | +------------+-------------+-------------------------------------------+ | 08/01/2014 | Chris Falck | Added additional inputs to be tested | +------------+-------------+-------------------------------------------+ | 10/01/2014 | Chris Falck | Tested to confirm changes to DB | +------------+-------------+-------------------------------------------+ ''' expected_tuple = (('WIN1',), ('WIN2',), ('CENT1',), ('CENT2',)) for tst in [('WIN1', 'Win2008 Server 1', 'SFTPPlus', '192.168.0.65', '', '', '', '', 'xfero', 'xferopassword', '', '', '10021', '', '', 'key1'), ('WIN2', 'Win2008 Server 2', 'SFTPPlus', '192.168.0.66', '', '', '', '', 'xfero', 'xferopassword', '', '', '10221', '', '', 'key2'), ('CENT1', 'CentOS6 Server 1', 'SFTPPlus', '192.168.0.11', '', '', '', '', 'xfero', 'xferopassword', '', '', '10121', '', '', 'key3'), ('CENT2', 'CentOS6 Server 2', 'SFTPPlus', '192.168.0.12', '', '', '', '', 'xfero', 'xferopassword', '', '', '10321', '', '', 'key4'), ]: (partner_service_name, partner_service_description, partner_COTS_type, partner_remote_system_id, partner_code, partner_mode, partner_local_username, partner_local_password, partner_remote_user, partner_remote_password, partner_CA_certificate, partner_cert_bundle, partner_control_port, partner_IDF, partner_parm, partner_pub_key) = tst result = db_partner.create_XFERO_Partner(partner_service_name, partner_service_description, partner_COTS_type, partner_remote_system_id, partner_code, partner_mode, partner_local_username, partner_local_password, partner_remote_user, partner_remote_password, partner_CA_certificate, partner_cert_bundle, partner_control_port, partner_IDF, partner_parm, partner_pub_key) rows = db_partner.list_service_name_XFERO_Partner() for row in rows: self.assertIn(row, expected_tuple, 'Unexpected row selected') if __name__ == "__main__": # import sys;sys.argv = ['', 'Test.testName'] unittest.main()
agpl-3.0
davecheney/juju
apiserver/service/service.go
17650
// Copyright 2014 Canonical Ltd. // Licensed under the AGPLv3, see LICENCE file for details. // Package service contains api calls for functionality // related to deploying and managing services and their // related charms. package service import ( "github.com/juju/errors" "github.com/juju/loggo" "github.com/juju/names" "gopkg.in/juju/charm.v6-unstable" goyaml "gopkg.in/yaml.v2" "github.com/juju/juju/apiserver/common" "github.com/juju/juju/apiserver/params" "github.com/juju/juju/instance" jjj "github.com/juju/juju/juju" "github.com/juju/juju/state" statestorage "github.com/juju/juju/state/storage" ) var ( logger = loggo.GetLogger("juju.apiserver.service") newStateStorage = statestorage.NewStorage ) func init() { common.RegisterStandardFacade("Service", 3, NewAPI) } // Service defines the methods on the service API end point. type Service interface { SetMetricCredentials(args params.ServiceMetricCredentials) (params.ErrorResults, error) } // API implements the service interface and is the concrete // implementation of the api end point. type API struct { check *common.BlockChecker state *state.State authorizer common.Authorizer } // NewAPI returns a new service API facade. func NewAPI( st *state.State, resources *common.Resources, authorizer common.Authorizer, ) (*API, error) { if !authorizer.AuthClient() { return nil, common.ErrPerm } return &API{ state: st, authorizer: authorizer, check: common.NewBlockChecker(st), }, nil } // SetMetricCredentials sets credentials on the service. func (api *API) SetMetricCredentials(args params.ServiceMetricCredentials) (params.ErrorResults, error) { result := params.ErrorResults{ Results: make([]params.ErrorResult, len(args.Creds)), } if len(args.Creds) == 0 { return result, nil } for i, a := range args.Creds { service, err := api.state.Service(a.ServiceName) if err != nil { result.Results[i].Error = common.ServerError(err) continue } err = service.SetMetricCredentials(a.MetricCredentials) if err != nil { result.Results[i].Error = common.ServerError(err) } } return result, nil } // Deploy fetches the charms from the charm store and deploys them // using the specified placement directives. func (api *API) Deploy(args params.ServicesDeploy) (params.ErrorResults, error) { result := params.ErrorResults{ Results: make([]params.ErrorResult, len(args.Services)), } if err := api.check.ChangeAllowed(); err != nil { return result, errors.Trace(err) } owner := api.authorizer.GetAuthTag().String() for i, arg := range args.Services { err := deployService(api.state, owner, arg) result.Results[i].Error = common.ServerError(err) } return result, nil } // DeployService fetches the charm from the charm store and deploys it. // The logic has been factored out into a common function which is called by // both the legacy API on the client facade, as well as the new service facade. func deployService(st *state.State, owner string, args params.ServiceDeploy) error { curl, err := charm.ParseURL(args.CharmUrl) if err != nil { return errors.Trace(err) } if curl.Revision < 0 { return errors.Errorf("charm url must include revision") } // Do a quick but not complete validation check before going any further. for _, p := range args.Placement { if p.Scope != instance.MachineScope { continue } _, err = st.Machine(p.Directive) if err != nil { return errors.Annotatef(err, `cannot deploy "%v" to machine %v`, args.ServiceName, p.Directive) } } // Try to find the charm URL in state first. ch, err := st.Charm(curl) if errors.IsNotFound(err) { // Clients written to expect 1.16 compatibility require this next block. if curl.Schema != "cs" { return errors.Errorf(`charm url has unsupported schema %q`, curl.Schema) } if err = AddCharmWithAuthorization(st, params.AddCharmWithAuthorization{ URL: args.CharmUrl, }); err == nil { ch, err = st.Charm(curl) } } if err != nil { return errors.Trace(err) } var settings charm.Settings if len(args.ConfigYAML) > 0 { settings, err = ch.Config().ParseSettingsYAML([]byte(args.ConfigYAML), args.ServiceName) } else if len(args.Config) > 0 { // Parse config in a compatible way (see function comment). settings, err = parseSettingsCompatible(ch, args.Config) } if err != nil { return errors.Trace(err) } // Convert network tags to names for any given networks. requestedNetworks, err := networkTagsToNames(args.Networks) if err != nil { return errors.Trace(err) } _, err = jjj.DeployService(st, jjj.DeployServiceParams{ ServiceName: args.ServiceName, Series: args.Series, // TODO(dfc) ServiceOwner should be a tag ServiceOwner: owner, Charm: ch, NumUnits: args.NumUnits, ConfigSettings: settings, Constraints: args.Constraints, Placement: args.Placement, Networks: requestedNetworks, Storage: args.Storage, EndpointBindings: args.EndpointBindings, Resources: args.Resources, }) return errors.Trace(err) } // ServiceSetSettingsStrings updates the settings for the given service, // taking the configuration from a map of strings. func ServiceSetSettingsStrings(service *state.Service, settings map[string]string) error { ch, _, err := service.Charm() if err != nil { return errors.Trace(err) } // Parse config in a compatible way (see function comment). changes, err := parseSettingsCompatible(ch, settings) if err != nil { return errors.Trace(err) } return service.UpdateConfigSettings(changes) } func networkTagsToNames(tags []string) ([]string, error) { netNames := make([]string, len(tags)) for i, tag := range tags { t, err := names.ParseNetworkTag(tag) if err != nil { return nil, err } netNames[i] = t.Id() } return netNames, nil } // parseSettingsCompatible parses setting strings in a way that is // compatible with the behavior before this CL based on the issue // http://pad.lv/1194945. Until then setting an option to an empty // string caused it to reset to the default value. We now allow // empty strings as actual values, but we want to preserve the API // behavior. func parseSettingsCompatible(ch *state.Charm, settings map[string]string) (charm.Settings, error) { setSettings := map[string]string{} unsetSettings := charm.Settings{} // Split settings into those which set and those which unset a value. for name, value := range settings { if value == "" { unsetSettings[name] = nil continue } setSettings[name] = value } // Validate the settings. changes, err := ch.Config().ParseSettingsStrings(setSettings) if err != nil { return nil, err } // Validate the unsettings and merge them into the changes. unsetSettings, err = ch.Config().ValidateSettings(unsetSettings) if err != nil { return nil, err } for name := range unsetSettings { changes[name] = nil } return changes, nil } // Update updates the service attributes, including charm URL, // minimum number of units, settings and constraints. // All parameters in params.ServiceUpdate except the service name are optional. func (api *API) Update(args params.ServiceUpdate) error { if !args.ForceCharmUrl { if err := api.check.ChangeAllowed(); err != nil { return errors.Trace(err) } } svc, err := api.state.Service(args.ServiceName) if err != nil { return errors.Trace(err) } // Set the charm for the given service. if args.CharmUrl != "" { if err = api.serviceSetCharm(svc, args.CharmUrl, args.ForceSeries, args.ForceCharmUrl); err != nil { return errors.Trace(err) } } // Set the minimum number of units for the given service. if args.MinUnits != nil { if err = svc.SetMinUnits(*args.MinUnits); err != nil { return errors.Trace(err) } } // Set up service's settings. if args.SettingsYAML != "" { if err = serviceSetSettingsYAML(svc, args.SettingsYAML); err != nil { return errors.Annotate(err, "setting configuration from YAML") } } else if len(args.SettingsStrings) > 0 { if err = ServiceSetSettingsStrings(svc, args.SettingsStrings); err != nil { return errors.Trace(err) } } // Update service's constraints. if args.Constraints != nil { return svc.SetConstraints(*args.Constraints) } return nil } // SetCharm sets the charm for a given service. func (api *API) SetCharm(args params.ServiceSetCharm) error { // when forced units in error, don't block if !args.ForceUnits { if err := api.check.ChangeAllowed(); err != nil { return errors.Trace(err) } } service, err := api.state.Service(args.ServiceName) if err != nil { return errors.Trace(err) } return api.serviceSetCharm(service, args.CharmUrl, args.ForceSeries, args.ForceUnits) } // serviceSetCharm sets the charm for the given service. func (api *API) serviceSetCharm(service *state.Service, url string, forceSeries, forceUnits bool) error { curl, err := charm.ParseURL(url) if err != nil { return errors.Trace(err) } sch, err := api.state.Charm(curl) if err != nil { return errors.Trace(err) } return service.SetCharm(sch, forceSeries, forceUnits) } // settingsYamlFromGetYaml will parse a yaml produced by juju get and generate // charm.Settings from it that can then be sent to the service. func settingsFromGetYaml(yamlContents map[string]interface{}) (charm.Settings, error) { onlySettings := charm.Settings{} settingsMap, ok := yamlContents["settings"].(map[interface{}]interface{}) if !ok { return nil, errors.New("unknown format for settings") } for setting := range settingsMap { s, ok := settingsMap[setting].(map[interface{}]interface{}) if !ok { return nil, errors.Errorf("unknown format for settings section %v", setting) } // some keys might not have a value, we don't care about those. v, ok := s["value"] if !ok { continue } stringSetting, ok := setting.(string) if !ok { return nil, errors.Errorf("unexpected setting key, expected string got %T", setting) } onlySettings[stringSetting] = v } return onlySettings, nil } // serviceSetSettingsYAML updates the settings for the given service, // taking the configuration from a YAML string. func serviceSetSettingsYAML(service *state.Service, settings string) error { b := []byte(settings) var all map[string]interface{} if err := goyaml.Unmarshal(b, &all); err != nil { return errors.Annotate(err, "parsing settings data") } // The file is already in the right format. if _, ok := all[service.Name()]; !ok { changes, err := settingsFromGetYaml(all) if err != nil { return errors.Annotate(err, "processing YAML generated by get") } return errors.Annotate(service.UpdateConfigSettings(changes), "updating settings with service YAML") } ch, _, err := service.Charm() if err != nil { return errors.Annotate(err, "obtaining charm for this service") } changes, err := ch.Config().ParseSettingsYAML(b, service.Name()) if err != nil { return errors.Annotate(err, "creating config from YAML") } return errors.Annotate(service.UpdateConfigSettings(changes), "updating settings") } // GetCharmURL returns the charm URL the given service is // running at present. func (api *API) GetCharmURL(args params.ServiceGet) (params.StringResult, error) { service, err := api.state.Service(args.ServiceName) if err != nil { return params.StringResult{}, err } charmURL, _ := service.CharmURL() return params.StringResult{Result: charmURL.String()}, nil } // Set implements the server side of Service.Set. // It does not unset values that are set to an empty string. // Unset should be used for that. func (api *API) Set(p params.ServiceSet) error { if err := api.check.ChangeAllowed(); err != nil { return errors.Trace(err) } svc, err := api.state.Service(p.ServiceName) if err != nil { return err } ch, _, err := svc.Charm() if err != nil { return err } // Validate the settings. changes, err := ch.Config().ParseSettingsStrings(p.Options) if err != nil { return err } return svc.UpdateConfigSettings(changes) } // Unset implements the server side of Client.Unset. func (api *API) Unset(p params.ServiceUnset) error { if err := api.check.ChangeAllowed(); err != nil { return errors.Trace(err) } svc, err := api.state.Service(p.ServiceName) if err != nil { return err } settings := make(charm.Settings) for _, option := range p.Options { settings[option] = nil } return svc.UpdateConfigSettings(settings) } // CharmRelations implements the server side of Service.CharmRelations. func (api *API) CharmRelations(p params.ServiceCharmRelations) (params.ServiceCharmRelationsResults, error) { var results params.ServiceCharmRelationsResults service, err := api.state.Service(p.ServiceName) if err != nil { return results, err } endpoints, err := service.Endpoints() if err != nil { return results, err } results.CharmRelations = make([]string, len(endpoints)) for i, endpoint := range endpoints { results.CharmRelations[i] = endpoint.Relation.Name } return results, nil } // Expose changes the juju-managed firewall to expose any ports that // were also explicitly marked by units as open. func (api *API) Expose(args params.ServiceExpose) error { if err := api.check.ChangeAllowed(); err != nil { return errors.Trace(err) } svc, err := api.state.Service(args.ServiceName) if err != nil { return err } return svc.SetExposed() } // Unexpose changes the juju-managed firewall to unexpose any ports that // were also explicitly marked by units as open. func (api *API) Unexpose(args params.ServiceUnexpose) error { if err := api.check.ChangeAllowed(); err != nil { return errors.Trace(err) } svc, err := api.state.Service(args.ServiceName) if err != nil { return err } return svc.ClearExposed() } // addServiceUnits adds a given number of units to a service. func addServiceUnits(st *state.State, args params.AddServiceUnits) ([]*state.Unit, error) { service, err := st.Service(args.ServiceName) if err != nil { return nil, err } if args.NumUnits < 1 { return nil, errors.New("must add at least one unit") } return jjj.AddUnits(st, service, args.NumUnits, args.Placement) } // AddUnits adds a given number of units to a service. func (api *API) AddUnits(args params.AddServiceUnits) (params.AddServiceUnitsResults, error) { if err := api.check.ChangeAllowed(); err != nil { return params.AddServiceUnitsResults{}, errors.Trace(err) } units, err := addServiceUnits(api.state, args) if err != nil { return params.AddServiceUnitsResults{}, err } unitNames := make([]string, len(units)) for i, unit := range units { unitNames[i] = unit.String() } return params.AddServiceUnitsResults{Units: unitNames}, nil } // DestroyUnits removes a given set of service units. func (api *API) DestroyUnits(args params.DestroyServiceUnits) error { if err := api.check.RemoveAllowed(); err != nil { return errors.Trace(err) } var errs []string for _, name := range args.UnitNames { unit, err := api.state.Unit(name) switch { case errors.IsNotFound(err): err = errors.Errorf("unit %q does not exist", name) case err != nil: case unit.Life() != state.Alive: continue case unit.IsPrincipal(): err = unit.Destroy() default: err = errors.Errorf("unit %q is a subordinate", name) } if err != nil { errs = append(errs, err.Error()) } } return common.DestroyErr("units", args.UnitNames, errs) } // Destroy destroys a given service. func (api *API) Destroy(args params.ServiceDestroy) error { if err := api.check.RemoveAllowed(); err != nil { return errors.Trace(err) } svc, err := api.state.Service(args.ServiceName) if err != nil { return err } return svc.Destroy() } // GetConstraints returns the constraints for a given service. func (api *API) GetConstraints(args params.GetServiceConstraints) (params.GetConstraintsResults, error) { svc, err := api.state.Service(args.ServiceName) if err != nil { return params.GetConstraintsResults{}, err } cons, err := svc.Constraints() return params.GetConstraintsResults{cons}, err } // SetConstraints sets the constraints for a given service. func (api *API) SetConstraints(args params.SetConstraints) error { if err := api.check.ChangeAllowed(); err != nil { return errors.Trace(err) } svc, err := api.state.Service(args.ServiceName) if err != nil { return err } return svc.SetConstraints(args.Constraints) } // AddRelation adds a relation between the specified endpoints and returns the relation info. func (api *API) AddRelation(args params.AddRelation) (params.AddRelationResults, error) { if err := api.check.ChangeAllowed(); err != nil { return params.AddRelationResults{}, errors.Trace(err) } inEps, err := api.state.InferEndpoints(args.Endpoints...) if err != nil { return params.AddRelationResults{}, err } rel, err := api.state.AddRelation(inEps...) if err != nil { return params.AddRelationResults{}, err } outEps := make(map[string]charm.Relation) for _, inEp := range inEps { outEp, err := rel.Endpoint(inEp.ServiceName) if err != nil { return params.AddRelationResults{}, err } outEps[inEp.ServiceName] = outEp.Relation } return params.AddRelationResults{Endpoints: outEps}, nil } // DestroyRelation removes the relation between the specified endpoints. func (api *API) DestroyRelation(args params.DestroyRelation) error { if err := api.check.RemoveAllowed(); err != nil { return errors.Trace(err) } eps, err := api.state.InferEndpoints(args.Endpoints...) if err != nil { return err } rel, err := api.state.EndpointsRelation(eps...) if err != nil { return err } return rel.Destroy() }
agpl-3.0
marius-wieschollek/passwords
src/lib/EventListener/Tag/BeforeTagDeletedListener.php
1352
<?php /* * @copyright 2020 Passwords App * * @author Marius David Wieschollek * @license AGPL-3.0 * * This file is part of the Passwords App * created by Marius David Wieschollek. */ namespace OCA\Passwords\EventListener\Tag; use Exception; use OCA\Passwords\Events\Tag\BeforeTagDeletedEvent; use OCA\Passwords\Services\Object\PasswordTagRelationService; use OCP\EventDispatcher\Event; use OCP\EventDispatcher\IEventListener; /** * Class BeforeTagDeletedListener * * @package OCA\Passwords\EventListener\Tag */ class BeforeTagDeletedListener implements IEventListener { /** * @var PasswordTagRelationService */ protected PasswordTagRelationService $relationService; /** * BeforeTagDeletedListener constructor. * * @param PasswordTagRelationService $relationService */ public function __construct(PasswordTagRelationService $relationService) { $this->relationService = $relationService; } /** * @param Event $event * * @throws Exception */ public function handle(Event $event): void { if(!($event instanceof BeforeTagDeletedEvent)) return; $relations = $this->relationService->findByTag($event->getTag()->getUuid()); foreach($relations as $relation) { $this->relationService->delete($relation); } } }
agpl-3.0
tochman/onebody
spec/requests/sign_in_spec.rb
2524
require_relative '../rails_helper' describe 'SignIn', type: :request do before do @user = FactoryGirl.create(:person) Setting.set(nil, 'Features', 'SSL', true) end context 'given sign in with wrong email address' do before do post '/session', email: 'bad-email', password: 'bla' end it 'should show error message' do expect(response).to be_success assert_select 'div.callout', /email address/ end end context 'given sign in with wrong password' do before do post '/session', email: @user.email, password: 'wrong-password' end it 'should show error message' do expect(response).to be_success assert_select 'div.callout', /password/ end end context 'given sign in by bot' do before do post '/session', email: @user.email, password: 'secret', fellforit: 'whatever' end it 'should redirect to root' do expect(response).to redirect_to(new_session_path) end end context 'given proper email and password' do before do post '/session', email: @user.email, password: 'secret' end it 'should redirect to stream' do expect(response).to redirect_to(stream_path) end end context 'given two users in the same family with the same email address' do before do @user2 = FactoryGirl.create(:person, email: @user.email, family: @user.family) end it 'should allow both to sign in' do post '/session', email: @user.email, password: 'secret' expect(response).to redirect_to(stream_path) post '/session', email: @user2.email, password: 'secret' expect(response).to redirect_to(stream_path) end end context 'given a session using a "feed code"' do it 'should allow access to stream xml' do get "/stream.xml?code=#{@user.feed_code}" expect(response).to be_success end it 'should allow access to disable group emails' do @group = FactoryGirl.create(:group) @membership = @group.memberships.create!(person: @user) get "/groups/#{@group.id}/memberships/#{@user.id}?code=#{@user.feed_code}&email=off", {}, referer: "/groups/#{@group.id}" expect(response).to redirect_to(@group) expect(@membership.reload.get_email).to eq(false) end it 'should not allow user to access most other actions' do get "/people?code=#{@user.feed_code}" expect(response).to be_redirect get "/groups?code=#{@user.feed_code}" expect(response).to be_redirect end end end
agpl-3.0
brainsqueezer/fffff
branches/version5/www/libs/tags.php
2330
<?php // The source code packaged with this file is Free Software, Copyright (C) 2005 by // Ricardo Galli <gallir at uib dot es>. // It's licensed under the AFFERO GENERAL PUBLIC LICENSE unless stated otherwise. // You can get copies of the licenses here: // http://www.affero.org/oagpl.html // AFFERO GENERAL PUBLIC LICENSE is also included in the file called "COPYING". function tags_normalize_string($string) { $string = clear_whitespace($string); $string = html_entity_decode(trim($string), ENT_COMPAT, 'UTF-8'); $string = preg_replace('/-+/', '-', $string); // Don't allow a sequence of more than a "-" $string = preg_replace('/ +,/', ',', $string); // Avoid errors like " ," $string = preg_replace('/[\n\t\r]+/s', ' ', $string); if (!preg_match('/,/', $string)) { // The user didn't put any comma, we add them $string = preg_replace('/ +/', ', ', $string); } $string = preg_replace('/[\.\,] *$/', "", $string); // Clean strange characteres, there are feed reader (including feedburner) that are just too strict and complain loudly $string = preg_replace('/[\\\\<>;"\'\]\[&]/', "", $string); return htmlspecialchars(mb_substr(mb_strtolower($string, 'UTF-8'), 0, 80), ENT_COMPAT, 'UTF-8'); } function tags_insert_string($link, $lang, $string, $date = 0) { global $db; $string = tags_normalize_string($string); if ($date == 0) $date=time(); $words = preg_split('/[,]+/', $string); if ($words) { $db->query("delete from tags where tag_link_id = $link"); foreach ($words as $word) { $word=$db->escape(trim($word)); if (mb_strlen($word) >= 2 && !$inserted[$word] && !empty($word)) { $db->query("insert into tags (tag_link_id, tag_lang, tag_words, tag_date) values ($link, '$lang', '$word', from_unixtime($date))"); $inserted[$word] = true; } } return true; } return false; } function tags_get_string($link, $lang) { global $db; $counter = 0; $res = $db->get_col("select tag_words from tags where tag_link_id=$link and tag_lang='$lang'"); if (!$res) return false; foreach ($db->get_col("select tag_words from tags where tag_link_id=$link and tag_lang='$lang'") as $word) { if($counter>0) $string .= ', '; $string .= $word; $counter++; } return $string; } class Tag { var $link=0; var $lang=0; var $words=''; var $date; function Tag() { return; } }
agpl-3.0
malikov/platform-android
ushahidi/src/main/java/com/ushahidi/android/presentation/state/ReloadPostEvent.java
1414
/* * Copyright (c) 2015 Ushahidi Inc * * 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 in the file LICENSE-AGPL. If not, see * https://www.gnu.org/licenses/agpl-3.0.html */ package com.ushahidi.android.presentation.state; import com.ushahidi.android.presentation.model.DeploymentModel; /** * Event class used by {@link RxEventBus} to trigger the app to load post * * @author Ushahidi Team <team@ushahidi.com> */ public class ReloadPostEvent { private DeploymentModel mDeploymentModel; /** * Default constructor * * @param deploymentModel The deployment to be passed to the event listener */ public ReloadPostEvent(DeploymentModel deploymentModel) { mDeploymentModel = deploymentModel; } public DeploymentModel getDeploymentModel() { return mDeploymentModel; } }
agpl-3.0
openfisca/openfisca-france-data
openfisca_france_data/erfs/__init__.py
1045
def get_of2erf(year=None): of2erf = dict() of2erf["csg"] = "csgim" # imposable, et "csgdm", déductible #of2erf["csgd"] = "csgdm" of2erf["crds"] = "crdsm" of2erf["irpp"] = "zimpom" of2erf["ppe"] = "m_ppem" of2erf["af"] = "m_afm" #af_base #af_majo #af_forf of2erf["cf"] = "m_cfm" of2erf["paje_base"] = "m_pajem" of2erf["paje_nais"] = "m_naism" of2erf["paje_clca"] = "" of2erf["paje_cmg"] = "" of2erf["ars"] = "m_arsm" of2erf["aeeh"] = "m_aesm" # allocation d'éducation spéciale of2erf["asf"] = "m_asfm" of2erf["aspa"] = "m_minvm" of2erf["aah"] = "m_aahm" of2erf["caah"] = "m_caahm" #of2erf["rmi"] = "m_rmim" of2erf["rsa"] = "m_rsam" of2erf["rsa_act"] = "" of2erf["aefa"] = "m_crmim" of2erf["api"] = "m_apim" of2erf["logt"] = "logtm" of2erf["alf"] = "m_alfm" of2erf["als"] = "m_alsm" of2erf["apl"] = "m_aplm" return of2erf def get_erf2of(): of2erf = get_of2erf() erf2of = dict((v,k) for k, v in of2erf.items()) return erf2of
agpl-3.0
jittat/ku-eng-direct-admission
scripts/import_results_for_public_display.py
2552
import codecs import sys if len(sys.argv)!=3: print "Usage: import_results [result_set_id] [results.csv]" quit() result_set_id = int(sys.argv[1]) if result_set_id==0: print "Result set id error" quit() file_name = sys.argv[2] from django.conf import settings from django_bootstrap import bootstrap bootstrap(__file__) from result.models import ReportCategory, QualifiedApplicant from application.models import Applicant, SubmissionInfo applicants = [] def read_results(): f = codecs.open(file_name, encoding="utf-8", mode="r") lines = f.readlines() order = 1 for l in lines: items = l.split(',') app = {'order': order, 'ticket_number': items[0], 'first_name': items[1], 'last_name': items[2] } applicants.append(app) order += 1 def delete_results_in_result_set(): for cat in ReportCategory.objects.filter(result_set_id=result_set_id).all(): cat.qualifiedapplicant_set.all().delete() def import_report_category(): print 'Importing categories...' ReportCategory.objects.filter(result_set_id=result_set_id).all().delete() cat_order = 1 categories = set() for a in applicants: name = ReportCategory.get_category_name_from_first_name(a['first_name']) if name not in categories: categories.add(name) rep_cat = ReportCategory(name=name, order=cat_order, result_set_id=result_set_id) rep_cat.save() cat_order += 1 print name, print 'added.' def import_results(): print 'Importing results...' app_order = 1 for a in applicants: q_app = QualifiedApplicant() q_app.order = app_order q_app.ticket_number = a['ticket_number'] q_app.first_name = a['first_name'] q_app.last_name = a['last_name'] q_app.category = ReportCategory.get_category_by_app_first_name( result_set_id, a['first_name']) submission_info = SubmissionInfo.find_by_ticket_number(a['ticket_number']) if submission_info == None: print 'TICKET:', a['ticket_number'] applicant = submission_info.applicant q_app.applicant = applicant q_app.save() app_order += 1 print a['ticket_number'] def main(): read_results() delete_results_in_result_set() import_report_category() import_results() if __name__ == '__main__': main()
agpl-3.0
gangadhar-kadam/sapphire_app
accounts/page/general_ledger/general_ledger.js
13127
// Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. // License: GNU General Public License v3. See license.txt wn.pages['general-ledger'].onload = function(wrapper) { wn.ui.make_app_page({ parent: wrapper, title: 'General Ledger', single_column: true }); erpnext.general_ledger = new erpnext.GeneralLedger(wrapper); wrapper.appframe.add_module_icon("Accounts") } erpnext.GeneralLedger = wn.views.GridReport.extend({ init: function(wrapper) { this._super({ title: "General Ledger", page: wrapper, parent: $(wrapper).find('.layout-main'), appframe: wrapper.appframe, doctypes: ["Company", "Account", "GL Entry", "Cost Center"], }); }, setup_columns: function() { this.columns = [ {id: "posting_date", name: "Posting Date", field: "posting_date", width: 100, formatter: this.date_formatter}, {id: "account", name: "Account", field: "account", width: 240, link_formatter: { filter_input: "account", open_btn: true, doctype: "'Account'" }}, {id: "against_account", name: "Against Account", field: "against_account", width: 240, hidden: !this.account}, {id: "debit", name: "Debit", field: "debit", width: 100, formatter: this.currency_formatter}, {id: "credit", name: "Credit", field: "credit", width: 100, formatter: this.currency_formatter}, {id: "voucher_type", name: "Voucher Type", field: "voucher_type", width: 120}, {id: "voucher_no", name: "Voucher No", field: "voucher_no", width: 160, link_formatter: { filter_input: "voucher_no", open_btn: true, doctype: "dataContext.voucher_type" }}, {id: "remarks", name: "Remarks", field: "remarks", width: 200, formatter: this.text_formatter}, ]; }, filters: [ {fieldtype:"Select", label: "Company", link:"Company", default_value: "Select Company...", filter: function(val, item, opts) { return item.company == val || val == opts.default_value; }}, {fieldtype:"Link", label: "Account", link:"Account", filter: function(val, item, opts, me) { if(!val) { return true; } else { // true if GL Entry belongs to selected // account ledger or group return me.is_child_account(val, item.account); } }}, {fieldtype:"Data", label: "Voucher No", filter: function(val, item, opts) { if(!val) return true; return (item.voucher_no && item.voucher_no.indexOf(val)!=-1); }}, {fieldtype:"Date", label: "From Date", filter: function(val, item) { return dateutil.str_to_obj(val) <= dateutil.str_to_obj(item.posting_date); }}, {fieldtype:"Label", label: "To"}, {fieldtype:"Date", label: "To Date", filter: function(val, item) { return dateutil.str_to_obj(val) >= dateutil.str_to_obj(item.posting_date); }}, {fieldtype: "Check", label: "Group by Ledger"}, {fieldtype: "Check", label: "Group by Voucher"}, {fieldtype:"Button", label: "Refresh", icon:"icon-refresh icon-white", cssClass:"btn-info"}, {fieldtype:"Button", label: "Reset Filters"} ], setup_filters: function() { this._super(); var me = this; this.accounts_by_company = this.make_accounts_by_company(); // filter accounts options by company this.filter_inputs.company.on("change", function() { me.setup_account_filter(this); me.refresh(); }); this.trigger_refresh_on_change(["group_by_ledger", "group_by_voucher"]); }, setup_account_filter: function(company_filter) { var me = this; var $account = me.filter_inputs.account; var company = $(company_filter).val(); var default_company = this.filter_inputs.company.get(0).opts.default_value; var opts = $account.get(0).opts; opts.list = $.map(wn.report_dump.data["Account"], function(ac) { return (company===default_company || me.accounts_by_company[company].indexOf(ac.name)!=-1) ? ac.name : null; }); this.set_autocomplete($account, opts.list); }, init_filter_values: function() { this._super(); this.toggle_group_by_checks(); this.filter_inputs.company.trigger("change"); }, apply_filters_from_route: function() { this._super(); this.toggle_group_by_checks(); }, make_accounts_by_company: function() { var accounts_by_company = {}; var me = this; $.each(wn.report_dump.data["Account"], function(i, ac) { if(!accounts_by_company[ac.company]) accounts_by_company[ac.company] = []; accounts_by_company[ac.company].push(ac.name); }); return accounts_by_company; }, is_child_account: function(account, item_account) { account = this.account_by_name[account]; item_account = this.account_by_name[item_account]; return ((item_account.lft >= account.lft) && (item_account.rgt <= account.rgt)); }, toggle_group_by_checks: function() { this.make_account_by_name(); // this.filter_inputs.group_by_ledger // .parent().toggle(!!(this.account_by_name[this.account] // && this.account_by_name[this.account].group_or_ledger==="Group")); // // this.filter_inputs.group_by_voucher // .parent().toggle(!!(this.account_by_name[this.account] // && this.account_by_name[this.account].group_or_ledger==="Ledger")); }, prepare_data: function() { var me = this; var data = wn.report_dump.data["GL Entry"]; var out = []; this.toggle_group_by_checks(); var from_date = dateutil.str_to_obj(this.from_date); var to_date = dateutil.str_to_obj(this.to_date); if(to_date < from_date) { msgprint("From Date must be before To Date"); return; } // add Opening, Closing, Totals rows // if filtered by account and / or voucher var opening = this.make_summary_row("Opening", this.account); var totals = this.make_summary_row("Totals", this.account); var grouped_ledgers = {}; $.each(data, function(i, item) { if(me.apply_filter(item, "company") && (me.account ? me.is_child_account(me.account, item.account) : true) && (me.voucher_no ? item.voucher_no==me.voucher_no : true)) { var date = dateutil.str_to_obj(item.posting_date); // create grouping by ledger if(!grouped_ledgers[item.account]) { grouped_ledgers[item.account] = { entries: [], entries_group_by_voucher: {}, opening: me.make_summary_row("Opening", item.account), totals: me.make_summary_row("Totals", item.account), closing: me.make_summary_row("Closing (Opening + Totals)", item.account) }; } if(!grouped_ledgers[item.account].entries_group_by_voucher[item.voucher_no]) { grouped_ledgers[item.account].entries_group_by_voucher[item.voucher_no] = { row: {}, totals: {"debit": 0, "credit": 0} } } if(!me.voucher_no && (date < from_date || item.is_opening=="Yes")) { opening.debit += item.debit; opening.credit += item.credit; grouped_ledgers[item.account].opening.debit += item.debit; grouped_ledgers[item.account].opening.credit += item.credit; } else if(date <= to_date) { totals.debit += item.debit; totals.credit += item.credit; grouped_ledgers[item.account].totals.debit += item.debit; grouped_ledgers[item.account].totals.credit += item.credit; grouped_ledgers[item.account].entries_group_by_voucher[item.voucher_no] .totals.debit += item.debit; grouped_ledgers[item.account].entries_group_by_voucher[item.voucher_no] .totals.credit += item.credit; } if(item.account) { item.against_account = me.voucher_accounts[item.voucher_type + ":" + item.voucher_no][(item.debit > 0 ? "credits" : "debits")].join(", "); } if(me.apply_filters(item) && (me.voucher_no || item.is_opening=="No")) { out.push(item); grouped_ledgers[item.account].entries.push(item); if(grouped_ledgers[item.account].entries_group_by_voucher[item.voucher_no].row){ grouped_ledgers[item.account].entries_group_by_voucher[item.voucher_no] .row = $.extend({}, item); } } } }); var closing = this.make_summary_row("Closing (Opening + Totals)", this.account); closing.debit = opening.debit + totals.debit; closing.credit = opening.credit + totals.credit; if(me.account) { me.appframe.set_title("General Ledger: " + me.account); // group by ledgers if(this.account_by_name[this.account].group_or_ledger==="Group" && this.group_by_ledger) { out = this.group_data_by_ledger(grouped_ledgers); } if(this.account_by_name[this.account].group_or_ledger==="Ledger" && this.group_by_voucher) { out = this.group_data_by_voucher(grouped_ledgers); } opening = me.get_balance(me.account_by_name[me.account].debit_or_credit, opening) closing = me.get_balance(me.account_by_name[me.account].debit_or_credit, closing) out = [opening].concat(out).concat([totals, closing]); } else { me.appframe.set_title("General Ledger"); out = out.concat([totals]); } this.data = out; }, group_data_by_ledger: function(grouped_ledgers) { var me = this; var out = [] $.each(Object.keys(grouped_ledgers).sort(), function(i, account) { if(grouped_ledgers[account].entries.length) { grouped_ledgers[account].closing.debit = grouped_ledgers[account].opening.debit + grouped_ledgers[account].totals.debit; grouped_ledgers[account].closing.credit = grouped_ledgers[account].opening.credit + grouped_ledgers[account].totals.credit; grouped_ledgers[account].opening = me.get_balance(me.account_by_name[me.account].debit_or_credit, grouped_ledgers[account].opening) grouped_ledgers[account].closing = me.get_balance(me.account_by_name[me.account].debit_or_credit, grouped_ledgers[account].closing) out = out.concat([grouped_ledgers[account].opening]) .concat(grouped_ledgers[account].entries) .concat([grouped_ledgers[account].totals, grouped_ledgers[account].closing, {id: "_blank" + i, debit: "", credit: ""}]); } }); return [{id: "_blank_first", debit: "", credit: ""}].concat(out); }, group_data_by_voucher: function(grouped_ledgers) { var me = this; var out = [] $.each(Object.keys(grouped_ledgers).sort(), function(i, account) { if(grouped_ledgers[account].entries.length) { $.each(Object.keys(grouped_ledgers[account].entries_group_by_voucher), function(j, voucher) { voucher_dict = grouped_ledgers[account].entries_group_by_voucher[voucher]; if(voucher_dict && (voucher_dict.totals.debit || voucher_dict.totals.credit)) { voucher_dict.row.debit = voucher_dict.totals.debit; voucher_dict.row.credit = voucher_dict.totals.credit; voucher_dict.row.id = "entry_grouped_by_" + voucher out = out.concat(voucher_dict.row); } }); } }); return out; }, get_balance: function(debit_or_credit, balance) { if(debit_or_credit == "Debit") { balance.debit -= balance.credit; balance.credit = 0; } else { balance.credit -= balance.debit; balance.debit = 0; } return balance }, make_summary_row: function(label, item_account) { return { account: label, debit: 0.0, credit: 0.0, id: ["", label, item_account].join("_").replace(" ", "_").toLowerCase(), _show: true, _style: "font-weight: bold" } }, make_account_by_name: function() { this.account_by_name = this.make_name_map(wn.report_dump.data["Account"]); this.make_voucher_accounts_map(); }, make_voucher_accounts_map: function() { this.voucher_accounts = {}; var data = wn.report_dump.data["GL Entry"]; for(var i=0, j=data.length; i<j; i++) { var gl = data[i]; if(!this.voucher_accounts[gl.voucher_type + ":" + gl.voucher_no]) this.voucher_accounts[gl.voucher_type + ":" + gl.voucher_no] = { debits: [], credits: [] } var va = this.voucher_accounts[gl.voucher_type + ":" + gl.voucher_no]; if(gl.debit > 0) { va.debits.push(gl.account); } else { va.credits.push(gl.account); } } }, get_plot_data: function() { var data = []; var me = this; if(!me.account || me.voucher_no) return false; var debit_or_credit = me.account_by_name[me.account].debit_or_credit; var balance = debit_or_credit=="Debit" ? me.data[0].debit : me.data[0].credit; data.push({ label: me.account, data: [[dateutil.str_to_obj(me.from_date).getTime(), balance]] .concat($.map(me.data, function(col, idx) { if (col.posting_date) { var diff = (debit_or_credit == "Debit" ? 1 : -1) * (flt(col.debit) - flt(col.credit)); balance += diff; return [[dateutil.str_to_obj(col.posting_date).getTime(), balance - diff], [dateutil.str_to_obj(col.posting_date).getTime(), balance]] } return null; })).concat([ // closing [dateutil.str_to_obj(me.to_date).getTime(), balance] ]), points: {show: true}, lines: {show: true, fill: true}, }); return data; }, get_plot_options: function() { return { grid: { hoverable: true, clickable: true }, xaxis: { mode: "time", min: dateutil.str_to_obj(this.from_date).getTime(), max: dateutil.str_to_obj(this.to_date).getTime() }, series: { downsample: { threshold: 1000 } } } }, });
agpl-3.0
xakutin/deTapeo
www/user.php
1451
<?php // +-----------------------------------------------------------+ // | The source code packaged with this file is Free Software, | // | licensed under the AFFERO GENERAL PUBLIC LICENSE. | // | Please see: | // | http://www.affero.org/oagpl.html for more information. | // | Copyright: 2009 xakutin | // +-----------------------------------------------------------+ include 'inc.common.php'; include includes.'html_user.php'; //Consultamos el usuario $user_id = 0; $is_me = false; $user = null; $from = ''; //Recogemos el id del usuario if (isset($_GET['id'])) $user_id = (int)$_GET['id']; if (isset($_GET['from'])) $from = $_GET['from']; //Si viene de validación o de recuperar contraseña //Si no se ha recibido ningún id, se muestra la información del usuario actual (si ha entrado) if (!$user_id && $current_user) $user_id = $current_user->id; if ($user_id){ $user=UserManager::get_user($user_id); if ($current_user) $is_me = ($user_id == $current_user->id); } print_header('Perfil'); if ($is_me) print_tabs(TAB_PROFILE); else if ($user) print_tabs($user->login); echo '<div id="main_sub">', "\n"; print_user_right_side($user); echo ' <div id="main_izq">'."\n"; print_user_tabs(TAB_USER_PROFILE); print_user_profile($user, $is_me, $from); echo ' <div class="clear"></div>', "\n"; echo ' </div>'."\n"; echo '</div>', "\n"; print_footer(); ?>
agpl-3.0
d120/kifplan
kiffelverwaltung/settings.py
5077
""" Django settings for kiffelverwaltung project. Generated by 'django-admin startproject' using Django 1.8.5. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) BASE_URL = "http://localhost:8000/" # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '$_^yz6o93(#y)p-s(n8skccx*umc$3=y+3h0#mpebc6hva)pij' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_filters', 'rest_framework', 'import_export', 'ajax_select', 'kiffel', 'eduroam', 'oplan', 'frontend', 'kdvadmin', 'neuigkeiten', #'debug_toolbar', ) MIDDLEWARE = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', ) ROOT_URLCONF = 'kiffelverwaltung.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates') ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'kiffelverwaltung.wsgi.application' # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Internationalization # https://docs.djangoproject.com/en/1.8/topics/i18n/ LANGUAGE_CODE = 'de-de' TIME_ZONE = 'Europe/Berlin' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.8/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = 'static' REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], 'DEFAULT_FILTER_BACKENDS': ( 'django_filters.rest_framework.DjangoFilterBackend', 'rest_framework.filters.SearchFilter', 'rest_framework.filters.OrderingFilter', ) } # Auth AUTH_USER_MODEL = 'kiffel.Person' LOGIN_URL = 'mysite_login' LOGOUT_URL = 'mysite_logout' LOGIN_REDIRECT_URL = 'frontend:index' # Use KDV tables managed by kifplan/django (True)? Or access existing tables by external KDV App (False) USE_KIFPLAN_KDV_TABLES = True #from django.http import HttpResponse #import json # #MIDDLEWARE_CLASSES += ( # 'kiffelverwaltung.settings.NonHtmlDebugToolbarMiddleware', #) #INTERNAL_IPS = ['178.8.206.38'] # #class NonHtmlDebugToolbarMiddleware(object): # """ # The Django Debug Toolbar usually only works for views that return HTML. # This middleware wraps any non-HTML response in HTML if the request # has a 'debug' query parameter (e.g. http://localhost/foo?debug) # Special handling for json (pretty printing) and # binary data (only show data length) # """ # # @staticmethod # def process_response(request, response): # if request.GET.get('debug') == '': # if response['Content-Type'] == 'application/octet-stream': # new_content = '<html><body>Binary Data, ' \ # 'Length: {}</body></html>'.format(len(response.content)) # response = HttpResponse(new_content) # elif response['Content-Type'] != 'text/html': # content = response.content # try: # json_ = json.loads(content) # content = json.dumps(json_, sort_keys=True, indent=2) # except ValueError: # pass # except TypeError: # pass # response = HttpResponse('<html><body><pre>{}' # '</pre></body></html>'.format(content)) # # return response try: from kiffelverwaltung.settings_local import * except ImportError: pass
agpl-3.0
o2oa/o2oa
o2server/x_cms_assemble_control/src/main/java/com/x/cms/assemble/control/jaxrs/appinfo/ActionListWhatICanViewAllDocType.java
3026
package com.x.cms.assemble.control.jaxrs.appinfo; import com.x.base.core.project.cache.Cache; import com.x.base.core.project.cache.CacheManager; import com.x.base.core.project.http.ActionResult; import com.x.base.core.project.http.EffectivePerson; import com.x.base.core.project.logger.Logger; import com.x.base.core.project.logger.LoggerFactory; import com.x.base.core.project.tools.ListTools; import com.x.base.core.project.tools.SortTools; import net.sf.ehcache.Element; import javax.servlet.http.HttpServletRequest; import java.util.ArrayList; import java.util.List; import java.util.Optional; public class ActionListWhatICanViewAllDocType extends BaseAction { private static Logger logger = LoggerFactory.getLogger(ActionListWhatICanViewAllDocType.class); @SuppressWarnings("unchecked") protected ActionResult<List<Wo>> execute(HttpServletRequest request, EffectivePerson effectivePerson) throws Exception { ActionResult<List<Wo>> result = new ActionResult<>(); List<Wo> wos = new ArrayList<>(); List<Wo> wos_out = new ArrayList<>(); Boolean isXAdmin = false; Boolean check = true; Boolean isAnonymous = effectivePerson.isAnonymous(); String personName = effectivePerson.getDistinguishedName(); try { isXAdmin = userManagerService.isManager( effectivePerson ); } catch (Exception e) { check = false; Exception exception = new ExceptionAppInfoProcess(e, "系统在检查用户是否是平台管理员时发生异常。Name:" + personName); result.error(exception); logger.error(e, effectivePerson, request, null); } Cache.CacheKey cacheKey = new Cache.CacheKey( this.getClass(), personName, isAnonymous, isXAdmin ); Optional<?> optional = CacheManager.get(cacheCategory, cacheKey); if (optional.isPresent()) { result.setData((List<Wo>)optional.get()); } else { if (check) { try { wos_out = listViewAbleAppInfoByPermission( personName, isAnonymous, null, "all", "全部", isXAdmin, 1000 ); } catch (Exception e) { check = false; Exception exception = new ExceptionAppInfoProcess(e, "系统在根据用户权限查询所有可见的分类信息时发生异常。Name:" + personName); result.error(exception); logger.error(e, effectivePerson, request, null); } if( ListTools.isNotEmpty( wos_out )){ for( Wo wo : wos_out ) { // if( ListTools.isNotEmpty( wo.getWrapOutCategoryList() )) { try { wo.setConfig( appInfoServiceAdv.getConfigJson( wo.getId() ) ); } catch (Exception e) { check = false; Exception exception = new ExceptionAppInfoProcess(e, "系统根据ID查询栏目配置支持信息时发生异常。ID=" + wo.getId() ); result.error(exception); logger.error(e, effectivePerson, request, null); } wos.add( wo ); // } } //按appInfoSeq列的值, 排个序 SortTools.asc( wos, "appInfoSeq"); CacheManager.put(cacheCategory, cacheKey, wos); result.setData( wos ); } } } return result; } }
agpl-3.0
ULYSSIS-KUL/ipp
shared/src/main/java/org/ulyssis/ipp/control/commands/AddTagCommand.java
2382
/* * Copyright (C) 2014-2015 ULYSSIS VZW * * This file is part of i++. * * i++ is free software: you can redistribute it and/or modify * it under the terms of version 3 of the GNU Affero General Public License * as published by the Free Software Foundation. No other versions apply. * * 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.ulyssis.ipp.control.commands; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeName; import org.ulyssis.ipp.TagId; import java.time.Instant; /** * The "add tag" command, for adding a tag id to a team number. */ @JsonTypeName("AddTag") public final class AddTagCommand extends TagCommand { /** * Create an AddTagCommand for the given tag and team number. * * The time is set to be the current time. * * @param tag * The tag to add. * @param teamNb * The team number to add the tag for. */ public AddTagCommand(TagId tag, int teamNb) { super(tag, teamNb); } /** * Create an AddTagCommand for the given tag and team number at the given time. * * @param time * The time when to add the tag, this can be in the future for * an anticipated adding of a tag, or in the past, to add a tag * afterwards (e.g. as a correction) * @param tag * The tag to add. * @param teamNb * The team number to add the tag for. */ public AddTagCommand(Instant time, TagId tag, int teamNb) { super(time, tag, teamNb); } /* * Only for deserialization. */ @JsonCreator private AddTagCommand(@JsonProperty("commandId") String commandId, @JsonProperty("time") Instant time, @JsonProperty("tag") TagId tag, @JsonProperty("teamNb") int teamNb) { super(commandId, time, tag, teamNb); } }
agpl-3.0
colares/touke-flow
Packages/Framework/TYPO3.Flow/Tests/Unit/Utility/SchemaValidatorTest.php
27397
<?php namespace TYPO3\Flow\Tests\Unit\Utility; /* * * This script belongs to the TYPO3 Flow framework. * * * * It is free software; you can redistribute it and/or modify it under * * the terms of the GNU Lesser General Public License, either version 3 * * of the License, or (at your option) any later version. * * * * The TYPO3 project - inspiring people to share! * * */ /** * Testcase for the configuration validator * */ class SchemaValidatorTest extends \TYPO3\Flow\Tests\UnitTestCase { /** * @var \TYPO3\Flow\Utility\SchemaValidator */ protected $configurationValidator; public function setUp() { $this->configurationValidator = $this->getAccessibleMock('TYPO3\Flow\Utility\SchemaValidator', array('getError')); } /** * Handle the assertion that the given result object has errors * * @param \TYPO3\Flow\Error\Result $result * @param boolean $expectError * @return void */ protected function assertError(\TYPO3\Flow\Error\Result $result, $expectError = TRUE) { if ($expectError === TRUE) { $this->assertTrue($result->hasErrors()); } else { $this->assertFalse($result->hasErrors()); } } /** * Handle the assertation that the given result object has no errors * * @param \TYPO3\Flow\Error\Result $result * @param boolean $expectSuccess * @return void */ protected function assertSuccess(\TYPO3\Flow\Error\Result $result, $expectSuccess = TRUE) { if ($expectSuccess === TRUE) { $this->assertFalse($result->hasErrors()); } else { $this->assertTrue($result->hasErrors()); } } /** * @return array */ public function validateHandlesRequiredPropertyDataProvider() { return array( array(array('foo' => 'a string'), TRUE), array(array('foo' => 'a string', 'bar' => 'a string'), TRUE), array(array('foo' => 'a string', 'bar' => 123), FALSE), array(array('foo' => 'a string', 'bar' => 'a string'), TRUE), array(array('foo' => 123, 'bar' => 'a string'), FALSE), array(array('foo' => NULL, 'bar' => 'a string'), FALSE), array(array('bar'=> 'string'), FALSE) ); } /** * @test * @dataProvider validateHandlesRequiredPropertyDataProvider */ public function validateHandlesRequiredProperty($value, $expectSuccess) { $schema = array( 'type' => 'dictionary', 'properties' => array( 'foo' => array( 'type' => 'string', 'required' => TRUE ), 'bar' => 'string' ) ); $this->assertSuccess($this->configurationValidator->validate($value, $schema), $expectSuccess); } /** * @return array */ public function validateHandlesDisallowPropertyDataProvider() { return array( array('string', TRUE), array(123, FALSE) ); } /** * @test * @dataProvider validateHandlesDisallowPropertyDataProvider */ public function validateHandlesDisallowProperty($value, $expectSuccess) { $schema = array( 'disallow'=>'integer' ); $this->assertSuccess($this->configurationValidator->validate($value, $schema), $expectSuccess); } /** * @return array */ public function validateHandlesEnumPropertyDataProvider() { return array( array(1, TRUE), array(2, TRUE), array(NULL, FALSE), array(4, FALSE) ); } /** * @test * @dataProvider validateHandlesEnumPropertyDataProvider */ public function validateHandlesEnumProperty($value, $expectSuccess) { $schema = array( 'enum'=>array(1,2,3) ); $this->assertSuccess($this->configurationValidator->validate($value, $schema), $expectSuccess); } /** * @test */ public function validateReturnsErrorPath() { $value = array( 'foo' => array( 'bar' => array( 'baz' => 'string' ) ) ); $schema = array( 'type' => 'dictionary', 'properties' => array( 'foo' => array( 'type' => 'dictionary', 'properties' => array( 'bar' => array( 'type' => 'dictionary', 'properties' => array( 'baz' => 'number' ) ) ) ) ) ); $result = $this->configurationValidator->validate($value, $schema); $this->assertError($result); $allErrors = $result->getFlattenedErrors(); $this->assertTrue(array_key_exists('foo.bar.baz', $allErrors)); $pathErrors = $result->forProperty('foo.bar.baz')->getErrors(); $firstPathError = $pathErrors[0]; $this->assertEquals($firstPathError->getCode(), 1328557141); $this->assertEquals($firstPathError->getArguments(), array('type=number', 'type=string')); } /// INTEGER /// /** * @return array */ public function validateHandlesIntegerTypePropertyDataProvider() { return array( array(23, TRUE), array('foo', FALSE), array(23.42, FALSE), array(array(), FALSE), array(NULL, FALSE), ); } /** * @test * @dataProvider validateHandlesIntegerTypePropertyDataProvider */ public function validateHandlesIntegerTypeProperty($value, $expectSuccess) { $schema = array( 'type' => 'integer' ); $this->assertSuccess($this->configurationValidator->validate($value, $schema), $expectSuccess); } /// NUMBER /// /** * @return array */ public function validateHandlesNumberTypePropertyDataProvider() { return array( array(23.42, TRUE), array(42, TRUE), array('foo', FALSE), array(NULL, FALSE) ); } /** * @test * @dataProvider validateHandlesNumberTypePropertyDataProvider */ public function validateHandlesNumberTypeProperty($value, $expectSuccess) { $schema = array( 'type' => 'number' ); $this->assertSuccess($this->configurationValidator->validate($value, $schema), $expectSuccess); } /** * @return array */ public function validateHandlesNumberTypePropertyWithMinimumAndMaximumConstraintDataProvider (){ return array( array(33, TRUE), array(99, FALSE), array(1, FALSE), array(23, TRUE), array(42, TRUE) ); } /** * @test * @dataProvider validateHandlesNumberTypePropertyWithMinimumAndMaximumConstraintDataProvider */ public function validateHandlesNumberTypePropertyWithMinimumAndMaximumConstraint($value, $expectSuccess) { $schema = array( 'type' => 'number', 'minimum' => 23, 'maximum' => 42 ); $this->assertSuccess($this->configurationValidator->validate($value, $schema), $expectSuccess); } /** * @test * @dataProvider validateHandlesNumberTypePropertyWithMinimumAndMaximumConstraintDataProvider */ public function validateHandlesNumberTypePropertyWithNonExclusiveMinimumAndMaximumConstraint($value, $expectSuccess) { $schema = array( 'type' => 'number', 'minimum' => 23, 'exclusiveMinimum' => FALSE, 'maximum' => 42, 'exclusiveMaximum' => FALSE ); $this->assertSuccess($this->configurationValidator->validate($value, $schema), $expectSuccess); } /** * @return array */ public function validateHandlesNumberTypePropertyWithExclusiveMinimumAndMaximumConstraintDataProvider (){ return array( array(10, FALSE), array(22, FALSE), array(23, TRUE), array(42, TRUE), array(43, FALSE), array(99, FALSE) ); } /** * @test * @dataProvider validateHandlesNumberTypePropertyWithExclusiveMinimumAndMaximumConstraintDataProvider */ public function validateHandlesNumberTypePropertyWithExclusiveMinimumAndMaximumConstraint($value, $expectSuccess) { $schema = array( 'type' => 'number', 'minimum' => 22, 'exclusiveMinimum' => TRUE, 'maximum' => 43, 'exclusiveMaximum' => TRUE ); $this->assertSuccess($this->configurationValidator->validate($value, $schema), $expectSuccess); } /** * @return array */ public function validateHandlesNumberTypePropertyWithDivisibleByConstraintDataProvider() { return array( array(4, TRUE), array(3, FALSE), array(-3, FALSE), array(-4, TRUE), array(0, TRUE), ); } /** * @test * @dataProvider validateHandlesNumberTypePropertyWithDivisibleByConstraintDataProvider */ public function validateHandlesNumberTypePropertyWithDivisibleByConstraint($value, $expectSuccess) { $schema = array( 'type' => 'number', 'divisibleBy' => 2 ); $this->assertSuccess($this->configurationValidator->validate($value, $schema), $expectSuccess); } /// STRING /// /** * @return array */ public function validateHandlesStringTypePropertyDataProvider() { return array( array('FooBar', TRUE), array(123, FALSE) ); } /** * @test * @dataProvider validateHandlesStringTypePropertyDataProvider */ public function validateHandlesStringTypeProperty($value, $expectedResult) { $schema = array( 'type' => 'string', ); $this->assertSuccess($this->configurationValidator->validate($value, $schema), $expectedResult); } /** * @return array */ public function validateHandlesStringTypePropertyWithPatternConstraintDataProvider() { return array( array('12a', TRUE), array('1236', FALSE), array('12c', FALSE) ); } /** * @test * @dataProvider validateHandlesStringTypePropertyWithPatternConstraintDataProvider */ public function validateHandlesStringTypePropertyWithPatternConstraint($value, $expectedResult) { $schema = array( 'type' => 'string', 'pattern' => '/^[123ab]{3}$/' ); $this->assertSuccess($this->configurationValidator->validate($value, $schema), $expectedResult); } /** * @return array */ public function validateHandlesStringTypePropertyWithDateTimeConstraintDataProvider() { return array( array('01:25:00', FALSE), array('1976-04-18', FALSE), array('1976-04-18T01:25:00+00:00', TRUE), array('foobar', FALSE), array(123, FALSE) ); } /** * @test * @dataProvider validateHandlesStringTypePropertyWithDateTimeConstraintDataProvider */ public function validateHandlesStringTypePropertyWithDateTimeConstraint($value, $expectedResult) { $schema = array( 'type' => 'string', 'format' => 'date-time' ); $this->assertSuccess($this->configurationValidator->validate($value, $schema), $expectedResult); } /** * @return array */ public function validateHandlesStringTypePropertyWithFormatDateConstraintDataProvider() { return array( array('01:25:00', FALSE), array('1976-04-18', TRUE), array('1976-04-18T01:25:00+00:00', FALSE), array('foobar', FALSE), array(123, FALSE) ); } /** * @test * @dataProvider validateHandlesStringTypePropertyWithFormatDateConstraintDataProvider */ public function validateHandlesStringTypePropertyWithFormatDateConstraint($value, $expectedResult) { $schema = array( 'type' => 'string', 'format' => 'date' ); $this->assertSuccess($this->configurationValidator->validate($value, $schema), $expectedResult); } /** * @return array */ public function validateHandlesStringTypePropertyWithFormatTimeConstraintDataProvider() { return array( array('01:25:00', TRUE), array('1976-04-18', FALSE), array('1976-04-18T01:25:00+00:00', FALSE), array('foobar', FALSE), array(123, FALSE) ); } /** * @test * @dataProvider validateHandlesStringTypePropertyWithFormatTimeConstraintDataProvider */ public function validateHandlesStringTypePropertyWithFormatTimeConstraint($value, $expectedResult) { $schema = array( 'type' => 'string', 'format' => 'time' ); $this->assertSuccess($this->configurationValidator->validate($value, $schema), $expectedResult); } /** * @return array */ public function validateHandlesStringTypePropertyWithFormatUriPConstraintDataProvider() { return array( array('http://foo.bar.de', TRUE), array('ftp://dasdas.de/foo/bar/?asds=123&dasdasd#dasdas', TRUE), array('foo', FALSE), array(123, FALSE), ); } /** * @test * @dataProvider validateHandlesStringTypePropertyWithFormatUriPConstraintDataProvider */ public function validateHandlesStringTypePropertyWithFormatUriPConstraint($value, $expectedResult) { $schema = array( 'type' => 'string', 'format' => 'uri' ); $this->assertSuccess($this->configurationValidator->validate($value, $schema), $expectedResult); } /** * @return array */ public function validateHandlesStringTypePropertyWithFormatHostnameConstraintDataProvider() { return array( array('www.typo3.org', TRUE), array('this.is.an.invalid.hostname', FALSE), array('foobar', FALSE), array(123, FALSE) ); } /** * @test * @dataProvider validateHandlesStringTypePropertyWithFormatHostnameConstraintDataProvider */ public function validateHandlesStringTypePropertyWithFormatHostnameConstraint($value, $expectedResult) { $schema = array( 'type' => 'string', 'format' => 'host-name' ); $this->assertSuccess($this->configurationValidator->validate($value, $schema), $expectedResult); } /** * @return array */ public function validateHandlesStringTypePropertyWithFormatIpv4ConstraintDataProvider() { return array( array('2001:0db8:85a3:08d3:1319:8a2e:0370:7344', FALSE), array('123.132.123.132', TRUE), array('foobar', FALSE), array(123, FALSE) ); } /** * @test * @dataProvider validateHandlesStringTypePropertyWithFormatIpv4ConstraintDataProvider */ public function validateHandlesStringTypePropertyWithFormatIpv4Constraint($value, $expectedResult) { $schema = array( 'type' => 'string', 'format' => 'ipv4' ); $this->assertSuccess($this->configurationValidator->validate($value, $schema), $expectedResult); } /** * @return array */ public function validateHandlesStringTypePropertyWithFormatIpv6ConstraintDataProvider() { return array( array('2001:0db8:85a3:08d3:1319:8a2e:0370:7344', TRUE), array('123.132.123.132', FALSE), array('foobar', FALSE), array(123, FALSE) ); } /** * @test * @dataProvider validateHandlesStringTypePropertyWithFormatIpv6ConstraintDataProvider */ public function validateHandlesStringTypePropertyWithFormatIpv6Constraint($value, $expectedResult) { $schema = array( 'type' => 'string', 'format' => 'ipv6' ); $this->assertSuccess($this->configurationValidator->validate($value, $schema), $expectedResult); } /** * @return array */ public function validateHandlesStringTypePropertyWithFormatIpAddressConstraintDataProvider() { return array( array('2001:0db8:85a3:08d3:1319:8a2e:0370:7344', TRUE), array('123.132.123.132', TRUE), array('foobar', FALSE), array('ab1', FALSE), array(123, FALSE) ); } /** * @test * @dataProvider validateHandlesStringTypePropertyWithFormatIpAddressConstraintDataProvider */ public function validateHandlesStringTypePropertyWithFormatIpAddressConstraint($value, $expectedResult) { $schema = array( 'type' => 'string', 'format' => 'ip-address' ); $this->assertSuccess($this->configurationValidator->validate($value, $schema), $expectedResult); } /** * @return array */ public function validateHandlesStringTypePropertyWithFormatClassNameConstraintDataProvider() { return array( array('\TYPO3\Flow\Package\PackageManager', TRUE), array('\TYPO3\Flow\UnknownClass', FALSE), array('foobar', FALSE), array('foo bar', FALSE), array('foo/bar', FALSE), array('flow/welcome', FALSE), array(123, FALSE) ); } /** * @test * @dataProvider validateHandlesStringTypePropertyWithFormatClassNameConstraintDataProvider */ public function validateHandlesStringTypePropertyWithFormatClassNameConstraint($value, $expectedResult) { $schema = array( 'type' => 'string', 'format' => 'class-name' ); $this->assertSuccess($this->configurationValidator->validate($value, $schema), $expectedResult); } /** * @return array */ public function validateHandlesStringTypePropertyWithFormatInterfaceNameConstraintDataProvider() { return array( array('\TYPO3\Flow\Package\PackageManagerInterface', TRUE), array('\TYPO3\Flow\UnknownClass', FALSE), array('foobar', FALSE), array('foo bar', FALSE), array('foo/bar', FALSE), array('flow/welcome', FALSE), array(123, FALSE) ); } /** * @test * @dataProvider validateHandlesStringTypePropertyWithFormatInterfaceNameConstraintDataProvider */ public function validateHandlesStringTypePropertyWithFormatInterfaceNameConstraint($value, $expectedResult) { $schema = array( 'type' => 'string', 'format' => 'interface-name' ); $this->assertSuccess($this->configurationValidator->validate($value, $schema), $expectedResult); } /** * @return array */ public function validateHandlesStringTypePropertyWithMinLengthConstraintDataProvider() { return array( array('12356', TRUE), array('1235', TRUE), array('123', FALSE), ); } /** * @test * @dataProvider validateHandlesStringTypePropertyWithMinLengthConstraintDataProvider */ public function validateHandlesStringTypePropertyWithMinLengthConstraint($value, $expectedResult) { $schema = array( 'type' => 'string', 'minLength' => 4 ); $this->assertSuccess($this->configurationValidator->validate($value, $schema), $expectedResult); } /** * @return array */ public function validateHandlesStringTypePropertyWithMaxLengthConstraintDataProvider() { return array( array('123', TRUE), array('1234', TRUE), array('12345', FALSE) ); } /** * @test * @dataProvider validateHandlesStringTypePropertyWithMaxLengthConstraintDataProvider */ public function validateHandlesStringTypePropertyWithMaxLengthConstraint($value, $expectedResult) { $schema = array( 'type' => 'string', 'maxLength' => 4 ); $this->assertSuccess($this->configurationValidator->validate($value, $schema), $expectedResult); } /// BOOLEAN /// /** * @return array */ public function validateHandlesBooleanTypeDataProvider() { return array( array(TRUE, TRUE), array(FALSE, TRUE), array('foo', FALSE), array(123, FALSE), array(12.34, FALSE), array(array(1,2,3), FALSE) ); } /** * @test * @dataProvider validateHandlesBooleanTypeDataProvider */ public function validateHandlesBooleanType($value, $expectedResult) { $schema = array( 'type' => 'boolean', ); $this->assertSuccess($this->configurationValidator->validate($value, $schema), $expectedResult); } /// ARRAY /// /** * @return array */ public function validateHandlesArrayTypePropertyDataProvider() { return array( array(array(1, 2, 3), TRUE), array('foo', FALSE), array(array('foo'=>'bar'), FALSE) ); } /** * @test * @dataProvider validateHandlesArrayTypePropertyDataProvider */ public function validateHandlesArrayTypeProperty($value, $expectedResult) { $schema = array( 'type' => 'array' ); $this->assertSuccess($this->configurationValidator->validate($value, $schema), $expectedResult); } /** * @return array */ public function validateHandlesArrayTypePropertyWithItemsConstraintDataProvider() { return array( array(array(1, 2, 3), TRUE), array(array(1, 2, 'test string'), FALSE) ); } /** * @test * @dataProvider validateHandlesArrayTypePropertyWithItemsConstraintDataProvider */ public function validateHandlesArrayTypePropertyWithItemsConstraint($value, $expectedResult) { $schema = array( 'type' => 'array', 'items'=> 'integer' ); $this->assertSuccess($this->configurationValidator->validate($value, $schema), $expectedResult); } /** * @return array */ public function validateHandlesArrayTypePropertyWithItemsSchemaConstraintDataProvider() { return array( array(array(1, 2, 3), TRUE), array(array(1, 2, 'test string'), FALSE) ); } /** * @test * @dataProvider validateHandlesArrayTypePropertyWithItemsSchemaConstraintDataProvider */ public function validateHandlesArrayTypePropertyWithItemsSchemaConstraint($value, $expectedResult) { $schema = array( 'type' => 'array', 'items'=> array ( 'type'=>'integer' ) ); $this->assertSuccess($this->configurationValidator->validate($value, $schema), $expectedResult); } /** * @return array */ public function validateHandlesArrayTypePropertyWithItemsArrayConstraintDataProvider() { return array( array(array(1, 2, 'test string'), TRUE), array(array(1, 2, 'test string', 1.56), FALSE) ); } /** * @test * @dataProvider validateHandlesArrayTypePropertyWithItemsArrayConstraintDataProvider */ public function validateHandlesArrayTypePropertyWithItemsArrayConstraint($value, $expectedResult) { $schema = array( 'type' => 'array', 'items'=> array ( array('type'=>'integer'), 'string' ) ); $this->assertSuccess($this->configurationValidator->validate($value, $schema), $expectedResult); } /** * @return array */ public function validateHandlesArrayUniqueItemsConstraintDataProvider() { return array( array(array(1,2,3), TRUE), array(array(1,2,1), FALSE), array(array(array(1,2), array(1,3)), TRUE), array(array(array(1,2), array(1,3), array(1,2)), FALSE), ); } /** * @test * @dataProvider validateHandlesArrayUniqueItemsConstraintDataProvider */ public function validateHandlesArrayUniqueItemsConstraint($value, $expectedResult) { $schema = array( 'type' => 'array', 'uniqueItems' => TRUE ); $this->assertSuccess($this->configurationValidator->validate($value, $schema), $expectedResult); } /// DICTIONARY /// /** * @return array */ public function validateHandlesDictionaryTypeDataProvider() { return array( array(array('A' => 1, 'B' => 2, 'C' => 3), TRUE), array(array(1, 2, 3), FALSE) ); } /** * @test * @dataProvider validateHandlesDictionaryTypeDataProvider */ public function validateHandlesDictionaryType($value, $expectedResult) { $schema = array( 'type' => 'dictionary' ); $this->assertSuccess($this->configurationValidator->validate($value, $schema), $expectedResult); } /** * @return array */ public function validateHandlesDictionaryTypeWithPropertiesConstraintDataProvider() { return array( array(array('foo'=>123, 'bar'=>'baz'), TRUE), array(array('foo'=>'baz', 'bar'=>'baz'), FALSE), array(array('foo'=>123, 'bar'=>123), FALSE) ); } /** * @test * @dataProvider validateHandlesDictionaryTypeWithPropertiesConstraintDataProvider */ public function validateHandlesDictionaryTypeWithPropertiesConstraint($value, $expectedResult) { $schema = array( 'type' => 'dictionary', 'properties' => array( 'foo' => 'integer', 'bar' => array('type'=>'string') ) ); $this->assertSuccess($this->configurationValidator->validate($value, $schema), $expectedResult); } /** * @return array */ public function validateHandlesDictionaryTypeWithPatternPropertiesConstraintDataProvider() { return array( array(array("ab1" => 'string'), TRUE), array(array('bbb' => 123), FALSE), array(array('ab' => 123), FALSE), array(array('ad12' => 'string'), FALSE), ); } /** * @test * @dataProvider validateHandlesDictionaryTypeWithPatternPropertiesConstraintDataProvider */ public function validateHandlesDictionaryTypeWithPatternPropertiesConstraint($value, $expectedResult) { $schema = array( 'type' => 'dictionary', 'patternProperties' => array( '/^[123ab]{3}$/' => 'string' ), 'additionalProperties' => FALSE ); $this->assertSuccess($this->configurationValidator->validate($value, $schema), $expectedResult); } /** * @return array */ public function validateHandlesDictionaryTypeWithFormatPropertiesConstraintDataProvider() { return array( array(array("127.0.0.1" => 'string'), TRUE), array(array('string' => 123), FALSE), array(array('127.0.0.1' => 123), FALSE), ); } /** * @test * @dataProvider validateHandlesDictionaryTypeWithFormatPropertiesConstraintDataProvider */ public function validateHandlesDictionaryTypeWithFormatPropertiesConstraint($value, $expectedResult) { $schema = array( 'type' => 'dictionary', 'formatProperties' => array( 'ip-address' => 'string' ), 'additionalProperties' => FALSE ); $this->assertSuccess($this->configurationValidator->validate($value, $schema), $expectedResult); } /** * @return array */ public function validateHandlesDictionaryTypeWithAdditionalPropertyFalseConstraintDataProvider() { return array( array(array('empty' => NULL), TRUE), array(array('foo'=>123, 'bar'=>'baz'), TRUE), array(array('foo'=>123, 'bar'=>'baz', 'baz'=>'blah'), FALSE) ); } /** * @test * @dataProvider validateHandlesDictionaryTypeWithAdditionalPropertyFalseConstraintDataProvider */ public function validateHandlesDictionaryTypeWithAdditionalPropertyFalseConstraint($value, $expectedResult) { $schema = array( 'type' => 'dictionary', 'properties' => array( 'empty' => 'null', 'foo' => 'integer', 'bar' => array('type'=>'string') ), 'additionalProperties' => FALSE ); $this->assertSuccess($this->configurationValidator->validate($value, $schema), $expectedResult); } /** * @return array */ public function validateHandlesDictionaryTypeWithAdditionalPropertySchemaConstraintDataProvider() { return array( array(array('foo'=>123, 'bar'=>'baz'), TRUE), array(array('foo'=>123, 'bar'=>'baz', 'baz'=>123), TRUE), array(array('foo'=>123, 'bar'=>123, 'baz'=>'string'), FALSE) ); } /** * @test * @dataProvider validateHandlesDictionaryTypeWithAdditionalPropertySchemaConstraintDataProvider */ public function validateHandlesDictionaryTypeWithAdditionalPropertySchemaConstraint($value, $expectedResult) { $schema = array( 'type' => 'dictionary', 'properties' => array( 'foo' => 'integer', 'bar' => array('type'=>'string') ), 'additionalProperties' => 'integer' ); $this->assertSuccess($this->configurationValidator->validate($value, $schema), $expectedResult); } /// NULL /// /** * @return array */ public function validateHandlesNullTypeDataProvider() { return array( array(NULL, TRUE), array(123, FALSE) ); } /** * @test * @dataProvider validateHandlesNullTypeDataProvider */ public function validateHandlesNullType($value, $expectedResult) { $schema = array( 'type' => 'null' ); $this->assertSuccess($this->configurationValidator->validate($value, $schema), $expectedResult); } /** * @return array */ public function validateHandlesUnknownTypeDataProvider() { return array( array(NULL, FALSE), array(123, FALSE) ); } /** * @test * @dataProvider validateHandlesUnknownTypeDataProvider */ public function validateHandlesUnknownType($value, $expectedResult) { $schema = array( 'type' => 'unknown' ); $this->assertSuccess($this->configurationValidator->validate($value, $schema), $expectedResult); } /// ANY /// /** * @return array */ public function validateAnyTypeResultHasNoErrorsInAnyCaseDataProvider() { return array( array(23, TRUE), array(23.42, TRUE), array('foo', TRUE), array(array(1,2,3), TRUE), array(array('A' => 1, 'B' => 2, 'C' => 3), TRUE), array(NULL, TRUE), ); } /** * @test * @dataProvider validateAnyTypeResultHasNoErrorsInAnyCaseDataProvider */ public function validateAnyTypeResultHasNoErrorsInAnyCase($value, $expectedResult) { $schema = array( 'type' => 'any' ); $this->assertSuccess($this->configurationValidator->validate($value, $schema), $expectedResult); } } ?>
agpl-3.0
cpennington/edx-platform
lms/djangoapps/courseware/tests/test_views.py
151929
# coding=UTF-8 """ Tests courseware views.py """ import itertools import json import unittest from datetime import datetime, timedelta from pytz import utc from uuid import uuid4 import crum import ddt import six from completion.test_utils import CompletionWaffleTestMixin from crum import set_current_request from django.conf import settings from django.contrib.auth.models import AnonymousUser from django.http import Http404, HttpResponseBadRequest from django.test import RequestFactory, TestCase from django.test.client import Client from django.test.utils import override_settings from django.urls import reverse, reverse_lazy from freezegun import freeze_time from markupsafe import escape from milestones.tests.utils import MilestonesTestCaseMixin from mock import MagicMock, PropertyMock, create_autospec, patch from opaque_keys.edx.locator import BlockUsageLocator, CourseLocator from pytz import UTC from six import text_type from six.moves import range from six.moves.html_parser import HTMLParser # pylint: disable=import-error from six.moves.urllib.parse import quote, urlencode # pylint: disable=import-error from web_fragments.fragment import Fragment from xblock.core import XBlock from xblock.fields import Scope, String import lms.djangoapps.courseware.views.views as views import shoppingcart from capa.tests.response_xml_factory import MultipleChoiceResponseXMLFactory from course_modes.models import CourseMode from course_modes.tests.factories import CourseModeFactory from lms.djangoapps.courseware.access_utils import check_course_open_for_learner from lms.djangoapps.courseware.model_data import FieldDataCache, set_score from lms.djangoapps.courseware.module_render import get_module, handle_xblock_callback from lms.djangoapps.courseware.tests.factories import GlobalStaffFactory, RequestFactoryNoCsrf, StudentModuleFactory from lms.djangoapps.courseware.tests.helpers import get_expiration_banner_text from lms.djangoapps.courseware.testutils import RenderXBlockTestMixin from lms.djangoapps.courseware.url_helpers import get_redirect_url from lms.djangoapps.courseware.user_state_client import DjangoXBlockUserStateClient from lms.djangoapps.certificates import api as certs_api from lms.djangoapps.certificates.models import ( CertificateGenerationConfiguration, CertificateStatuses, CertificateWhitelist ) from lms.djangoapps.certificates.tests.factories import CertificateInvalidationFactory, GeneratedCertificateFactory from lms.djangoapps.commerce.models import CommerceConfiguration from lms.djangoapps.commerce.utils import EcommerceService from lms.djangoapps.courseware.views.index import show_courseware_mfe_link from lms.djangoapps.courseware.toggles import ( COURSEWARE_MICROFRONTEND_COURSE_TEAM_PREVIEW, REDIRECT_TO_COURSEWARE_MICROFRONTEND, ) from lms.djangoapps.courseware.url_helpers import get_microfrontend_url from lms.djangoapps.grades.config.waffle import ASSUME_ZERO_GRADE_IF_ABSENT from lms.djangoapps.grades.config.waffle import waffle as grades_waffle from lms.djangoapps.verify_student.models import VerificationDeadline from lms.djangoapps.verify_student.services import IDVerificationService from opaque_keys.edx.keys import CourseKey, UsageKey from openedx.core.djangoapps.catalog.tests.factories import CourseFactory as CatalogCourseFactory from openedx.core.djangoapps.catalog.tests.factories import CourseRunFactory, ProgramFactory from openedx.core.djangoapps.content.course_overviews.models import CourseOverview from openedx.core.djangoapps.crawlers.models import CrawlersConfig from openedx.core.djangoapps.credit.api import set_credit_requirements from openedx.core.djangoapps.credit.models import CreditCourse, CreditProvider from openedx.core.djangoapps.waffle_utils.testutils import WAFFLE_TABLES, override_waffle_flag from openedx.core.djangolib.testing.utils import get_mock_request from openedx.core.lib.gating import api as gating_api from openedx.core.lib.url_utils import quote_slashes from openedx.features.content_type_gating.models import ContentTypeGatingConfig from openedx.features.course_duration_limits.models import CourseDurationLimitConfig from openedx.features.course_experience import ( COURSE_ENABLE_UNENROLLED_ACCESS_FLAG, COURSE_OUTLINE_PAGE_FLAG, RELATIVE_DATES_FLAG, UNIFIED_COURSE_TAB_FLAG ) from openedx.features.course_experience.tests.views.helpers import add_course_mode from openedx.features.enterprise_support.tests.mixins.enterprise import EnterpriseTestConsentRequired from student.models import CourseEnrollment from student.roles import CourseStaffRole from student.tests.factories import TEST_PASSWORD, AdminFactory, CourseEnrollmentFactory, UserFactory from util.tests.test_date_utils import fake_pgettext, fake_ugettext from util.url import reload_django_url_config from util.views import ensure_valid_course_key from xmodule.course_module import COURSE_VISIBILITY_PRIVATE, COURSE_VISIBILITY_PUBLIC, COURSE_VISIBILITY_PUBLIC_OUTLINE from xmodule.graders import ShowCorrectness from xmodule.modulestore import ModuleStoreEnum from xmodule.modulestore.django import modulestore from xmodule.modulestore.tests.django_utils import ( TEST_DATA_MIXED_MODULESTORE, TEST_DATA_SPLIT_MODULESTORE, CourseUserType, ModuleStoreTestCase, SharedModuleStoreTestCase ) from xmodule.modulestore.tests.factories import CourseFactory, ItemFactory, check_mongo_calls QUERY_COUNT_TABLE_BLACKLIST = WAFFLE_TABLES FEATURES_WITH_DISABLE_HONOR_CERTIFICATE = settings.FEATURES.copy() FEATURES_WITH_DISABLE_HONOR_CERTIFICATE['DISABLE_HONOR_CERTIFICATES'] = True @ddt.ddt class TestJumpTo(ModuleStoreTestCase): """ Check the jumpto link for a course. """ MODULESTORE = TEST_DATA_MIXED_MODULESTORE def setUp(self): super(TestJumpTo, self).setUp() # Use toy course from XML self.course_key = CourseKey.from_string('edX/toy/2012_Fall') def test_jumpto_invalid_location(self): location = self.course_key.make_usage_key(None, 'NoSuchPlace') # This is fragile, but unfortunately the problem is that within the LMS we # can't use the reverse calls from the CMS jumpto_url = '{0}/{1}/jump_to/{2}'.format('/courses', six.text_type(self.course_key), six.text_type(location)) response = self.client.get(jumpto_url) self.assertEqual(response.status_code, 404) def test_jumpto_from_section(self): course = CourseFactory.create() chapter = ItemFactory.create(category='chapter', parent_location=course.location) section = ItemFactory.create(category='sequential', parent_location=chapter.location) expected = '/courses/{course_id}/courseware/{chapter_id}/{section_id}/?{activate_block_id}'.format( course_id=six.text_type(course.id), chapter_id=chapter.url_name, section_id=section.url_name, activate_block_id=urlencode({'activate_block_id': six.text_type(section.location)}) ) jumpto_url = '{0}/{1}/jump_to/{2}'.format( '/courses', six.text_type(course.id), six.text_type(section.location), ) response = self.client.get(jumpto_url) self.assertRedirects(response, expected, status_code=302, target_status_code=302) def test_jumpto_from_module(self): course = CourseFactory.create() chapter = ItemFactory.create(category='chapter', parent_location=course.location) section = ItemFactory.create(category='sequential', parent_location=chapter.location) vertical1 = ItemFactory.create(category='vertical', parent_location=section.location) vertical2 = ItemFactory.create(category='vertical', parent_location=section.location) module1 = ItemFactory.create(category='html', parent_location=vertical1.location) module2 = ItemFactory.create(category='html', parent_location=vertical2.location) expected = '/courses/{course_id}/courseware/{chapter_id}/{section_id}/1?{activate_block_id}'.format( course_id=six.text_type(course.id), chapter_id=chapter.url_name, section_id=section.url_name, activate_block_id=urlencode({'activate_block_id': six.text_type(module1.location)}) ) jumpto_url = '{0}/{1}/jump_to/{2}'.format( '/courses', six.text_type(course.id), six.text_type(module1.location), ) response = self.client.get(jumpto_url) self.assertRedirects(response, expected, status_code=302, target_status_code=302) expected = '/courses/{course_id}/courseware/{chapter_id}/{section_id}/2?{activate_block_id}'.format( course_id=six.text_type(course.id), chapter_id=chapter.url_name, section_id=section.url_name, activate_block_id=urlencode({'activate_block_id': six.text_type(module2.location)}) ) jumpto_url = '{0}/{1}/jump_to/{2}'.format( '/courses', six.text_type(course.id), six.text_type(module2.location), ) response = self.client.get(jumpto_url) self.assertRedirects(response, expected, status_code=302, target_status_code=302) def test_jumpto_from_nested_module(self): course = CourseFactory.create() chapter = ItemFactory.create(category='chapter', parent_location=course.location) section = ItemFactory.create(category='sequential', parent_location=chapter.location) vertical = ItemFactory.create(category='vertical', parent_location=section.location) nested_section = ItemFactory.create(category='sequential', parent_location=vertical.location) nested_vertical1 = ItemFactory.create(category='vertical', parent_location=nested_section.location) # put a module into nested_vertical1 for completeness ItemFactory.create(category='html', parent_location=nested_vertical1.location) nested_vertical2 = ItemFactory.create(category='vertical', parent_location=nested_section.location) module2 = ItemFactory.create(category='html', parent_location=nested_vertical2.location) # internal position of module2 will be 1_2 (2nd item withing 1st item) expected = '/courses/{course_id}/courseware/{chapter_id}/{section_id}/1?{activate_block_id}'.format( course_id=six.text_type(course.id), chapter_id=chapter.url_name, section_id=section.url_name, activate_block_id=urlencode({'activate_block_id': six.text_type(module2.location)}) ) jumpto_url = '{0}/{1}/jump_to/{2}'.format( '/courses', six.text_type(course.id), six.text_type(module2.location), ) response = self.client.get(jumpto_url) self.assertRedirects(response, expected, status_code=302, target_status_code=302) def test_jumpto_id_invalid_location(self): location = BlockUsageLocator(CourseLocator('edX', 'toy', 'NoSuchPlace', deprecated=True), None, None, deprecated=True) jumpto_url = '{0}/{1}/jump_to_id/{2}'.format('/courses', six.text_type(self.course_key), six.text_type(location)) response = self.client.get(jumpto_url) self.assertEqual(response.status_code, 404) @ddt.data( (False, '1'), (True, '2') ) @ddt.unpack def test_jump_to_for_learner_with_staff_only_content(self, is_staff_user, position): """ Test for checking correct position in redirect_url for learner when a course has staff-only units. """ course = CourseFactory.create() request = RequestFactory().get('/') request.user = UserFactory(is_staff=is_staff_user, username="staff") request.session = {} course_key = CourseKey.from_string(six.text_type(course.id)) chapter = ItemFactory.create(category='chapter', parent_location=course.location) section = ItemFactory.create(category='sequential', parent_location=chapter.location) __ = ItemFactory.create(category='vertical', parent_location=section.location) staff_only_vertical = ItemFactory.create(category='vertical', parent_location=section.location, metadata=dict(visible_to_staff_only=True)) __ = ItemFactory.create(category='vertical', parent_location=section.location) usage_key = UsageKey.from_string(six.text_type(staff_only_vertical.location)).replace(course_key=course_key) expected_url = reverse( 'courseware_position', kwargs={ 'course_id': six.text_type(course.id), 'chapter': chapter.url_name, 'section': section.url_name, 'position': position, } ) expected_url += "?{}".format(urlencode({'activate_block_id': six.text_type(staff_only_vertical.location)})) self.assertEqual(expected_url, get_redirect_url(course_key, usage_key, request)) @ddt.ddt class IndexQueryTestCase(ModuleStoreTestCase): """ Tests for query count. """ CREATE_USER = False NUM_PROBLEMS = 20 @ddt.data( (ModuleStoreEnum.Type.mongo, 10, 172), (ModuleStoreEnum.Type.split, 4, 170), ) @ddt.unpack def test_index_query_counts(self, store_type, expected_mongo_query_count, expected_mysql_query_count): # TODO: decrease query count as part of REVO-28 ContentTypeGatingConfig.objects.create(enabled=True, enabled_as_of=datetime(2018, 1, 1)) with self.store.default_store(store_type): course = CourseFactory.create() with self.store.bulk_operations(course.id): chapter = ItemFactory.create(category='chapter', parent_location=course.location) section = ItemFactory.create(category='sequential', parent_location=chapter.location) vertical = ItemFactory.create(category='vertical', parent_location=section.location) for _ in range(self.NUM_PROBLEMS): ItemFactory.create(category='problem', parent_location=vertical.location) self.user = UserFactory() self.client.login(username=self.user.username, password=TEST_PASSWORD) CourseEnrollment.enroll(self.user, course.id) with self.assertNumQueries(expected_mysql_query_count, table_blacklist=QUERY_COUNT_TABLE_BLACKLIST): with check_mongo_calls(expected_mongo_query_count): url = reverse( 'courseware_section', kwargs={ 'course_id': six.text_type(course.id), 'chapter': six.text_type(chapter.location.block_id), 'section': six.text_type(section.location.block_id), } ) response = self.client.get(url) self.assertEqual(response.status_code, 200) class BaseViewsTestCase(ModuleStoreTestCase): def setUp(self): super(BaseViewsTestCase, self).setUp() self.course = CourseFactory.create(display_name=u'teꜱᴛ course', run="Testing_course") with self.store.bulk_operations(self.course.id): self.chapter = ItemFactory.create( category='chapter', parent_location=self.course.location, display_name="Chapter 1", ) self.section = ItemFactory.create( category='sequential', parent_location=self.chapter.location, due=datetime(2013, 9, 18, 11, 30, 00), display_name='Sequential 1', format='Homework' ) self.vertical = ItemFactory.create( category='vertical', parent_location=self.section.location, display_name='Vertical 1', ) self.problem = ItemFactory.create( category='problem', parent_location=self.vertical.location, display_name='Problem 1', ) self.section2 = ItemFactory.create( category='sequential', parent_location=self.chapter.location, display_name='Sequential 2', ) self.vertical2 = ItemFactory.create( category='vertical', parent_location=self.section2.location, display_name='Vertical 2', ) self.problem2 = ItemFactory.create( category='problem', parent_location=self.vertical2.location, display_name='Problem 2', ) self.course_key = self.course.id # Set profile country to Åland Islands to check Unicode characters does not raise error self.user = UserFactory(username='dummy', profile__country='AX') self.date = datetime(2013, 1, 22, tzinfo=UTC) self.enrollment = CourseEnrollment.enroll(self.user, self.course_key) self.enrollment.created = self.date self.enrollment.save() chapter = 'Overview' self.chapter_url = '%s/%s/%s' % ('/courses', self.course_key, chapter) self.org = u"ꜱᴛᴀʀᴋ ɪɴᴅᴜꜱᴛʀɪᴇꜱ" self.org_html = "<p>'+Stark/Industries+'</p>" self.assertTrue(self.client.login(username=self.user.username, password=TEST_PASSWORD)) # refresh the course from the modulestore so that it has children self.course = modulestore().get_course(self.course.id) def _create_global_staff_user(self): """ Create global staff user and log them in """ self.global_staff = GlobalStaffFactory.create() # pylint: disable=attribute-defined-outside-init self.assertTrue(self.client.login(username=self.global_staff.username, password=TEST_PASSWORD)) @ddt.ddt class ViewsTestCase(BaseViewsTestCase): """ Tests for views.py methods. """ YESTERDAY = 'yesterday' DATES = { YESTERDAY: datetime.now(UTC) - timedelta(days=1), None: None, } def test_index_success(self): response = self._verify_index_response() self.assertContains(response, self.problem2.location) # re-access to the main course page redirects to last accessed view. url = reverse('courseware', kwargs={'course_id': six.text_type(self.course_key)}) response = self.client.get(url) self.assertEqual(response.status_code, 302) response = self.client.get(response.url) self.assertNotContains(response, self.problem.location) self.assertContains(response, self.problem2.location) def test_index_nonexistent_chapter(self): self._verify_index_response(expected_response_code=404, chapter_name='non-existent') def test_index_nonexistent_chapter_masquerade(self): with patch('lms.djangoapps.courseware.views.index.setup_masquerade') as patch_masquerade: masquerade = MagicMock(role='student') patch_masquerade.return_value = (masquerade, self.user) self._verify_index_response(expected_response_code=302, chapter_name='non-existent') def test_index_nonexistent_section(self): self._verify_index_response(expected_response_code=404, section_name='non-existent') def test_index_nonexistent_section_masquerade(self): with patch('lms.djangoapps.courseware.views.index.setup_masquerade') as patch_masquerade: masquerade = MagicMock(role='student') patch_masquerade.return_value = (masquerade, self.user) self._verify_index_response(expected_response_code=302, section_name='non-existent') def _verify_index_response(self, expected_response_code=200, chapter_name=None, section_name=None): """ Verifies the response when the courseware index page is accessed with the given chapter and section names. """ url = reverse( 'courseware_section', kwargs={ 'course_id': six.text_type(self.course_key), 'chapter': six.text_type(self.chapter.location.block_id) if chapter_name is None else chapter_name, 'section': six.text_type(self.section2.location.block_id) if section_name is None else section_name, } ) response = self.client.get(url) self.assertEqual(response.status_code, expected_response_code) return response def test_index_no_visible_section_in_chapter(self): # reload the chapter from the store so its children information is updated self.chapter = self.store.get_item(self.chapter.location) # disable the visibility of the sections in the chapter for section in self.chapter.get_children(): section.visible_to_staff_only = True self.store.update_item(section, ModuleStoreEnum.UserID.test) url = reverse( 'courseware_chapter', kwargs={'course_id': six.text_type(self.course.id), 'chapter': six.text_type(self.chapter.location.block_id)}, ) response = self.client.get(url) self.assertEqual(response.status_code, 200) self.assertNotContains(response, 'Problem 1') self.assertNotContains(response, 'Problem 2') def _create_url_for_enroll_staff(self): """ creates the courseware url and enroll staff url """ # create the _next parameter courseware_url = reverse( 'courseware_section', kwargs={ 'course_id': six.text_type(self.course_key), 'chapter': six.text_type(self.chapter.location.block_id), 'section': six.text_type(self.section.location.block_id), } ) # create the url for enroll_staff view enroll_url = "{enroll_url}?next={courseware_url}".format( enroll_url=reverse('enroll_staff', kwargs={'course_id': six.text_type(self.course.id)}), courseware_url=courseware_url ) return courseware_url, enroll_url @ddt.data( ({'enroll': "Enroll"}, True), ({'dont_enroll': "Don't enroll"}, False)) @ddt.unpack def test_enroll_staff_redirection(self, data, enrollment): """ Verify unenrolled staff is redirected to correct url. """ self._create_global_staff_user() courseware_url, enroll_url = self._create_url_for_enroll_staff() response = self.client.post(enroll_url, data=data, follow=True) self.assertEqual(response.status_code, 200) # we were redirected to our current location self.assertIn(302, response.redirect_chain[0]) self.assertEqual(len(response.redirect_chain), 1) if enrollment: self.assertRedirects(response, courseware_url) else: self.assertRedirects(response, '/courses/{}/about'.format(six.text_type(self.course_key))) def test_enroll_staff_with_invalid_data(self): """ If we try to post with an invalid data pattern, then we'll redirected to course about page. """ self._create_global_staff_user() __, enroll_url = self._create_url_for_enroll_staff() response = self.client.post(enroll_url, data={'test': "test"}) self.assertEqual(response.status_code, 302) self.assertRedirects(response, '/courses/{}/about'.format(six.text_type(self.course_key))) @unittest.skipUnless(settings.FEATURES.get('ENABLE_SHOPPING_CART'), "Shopping Cart not enabled in settings") @patch.dict(settings.FEATURES, {'ENABLE_PAID_COURSE_REGISTRATION': True}) def test_course_about_in_cart(self): in_cart_span = '<span class="add-to-cart">' # don't mock this course due to shopping cart existence checking course = CourseFactory.create(org="new", number="unenrolled", display_name="course") self.client.logout() response = self.client.get(reverse('about_course', args=[six.text_type(course.id)])) self.assertEqual(response.status_code, 200) self.assertNotContains(response, in_cart_span) # authenticated user with nothing in cart self.assertTrue(self.client.login(username=self.user.username, password=TEST_PASSWORD)) response = self.client.get(reverse('about_course', args=[six.text_type(course.id)])) self.assertEqual(response.status_code, 200) self.assertNotContains(response, in_cart_span) # now add the course to the cart cart = shoppingcart.models.Order.get_cart_for_user(self.user) shoppingcart.models.PaidCourseRegistration.add_to_order(cart, course.id) response = self.client.get(reverse('about_course', args=[six.text_type(course.id)])) self.assertEqual(response.status_code, 200) self.assertContains(response, in_cart_span) def assert_enrollment_link_present(self, is_anonymous): """ Prepare ecommerce checkout data and assert if the ecommerce link is contained in the response. Arguments: is_anonymous(bool): Tell the method to use an anonymous user or the logged in one. _id(bool): Tell the method to either expect an id in the href or not. """ sku = 'TEST123' configuration = CommerceConfiguration.objects.create(checkout_on_ecommerce_service=True) course = CourseFactory.create() CourseModeFactory(mode_slug=CourseMode.PROFESSIONAL, course_id=course.id, sku=sku, min_price=1) if is_anonymous: self.client.logout() else: self.assertTrue(self.client.login(username=self.user.username, password=TEST_PASSWORD)) # Construct the link according the following scenarios and verify its presence in the response: # (1) shopping cart is enabled and the user is not logged in # (2) shopping cart is enabled and the user is logged in href = u'<a href="{uri_stem}?sku={sku}" class="add-to-cart">'.format( uri_stem=configuration.basket_checkout_page, sku=sku, ) # Generate the course about page content response = self.client.get(reverse('about_course', args=[six.text_type(course.id)])) self.assertContains(response, href) @ddt.data(True, False) def test_ecommerce_checkout(self, is_anonymous): if not is_anonymous: self.assert_enrollment_link_present(is_anonymous=is_anonymous) else: self.assertEqual(EcommerceService().is_enabled(AnonymousUser()), False) @ddt.data(True, False) @unittest.skipUnless(settings.FEATURES.get('ENABLE_SHOPPING_CART'), 'Shopping Cart not enabled in settings') @patch.dict(settings.FEATURES, {'ENABLE_PAID_COURSE_REGISTRATION': True}) def test_ecommerce_checkout_shopping_cart_enabled(self, is_anonymous): """ Two scenarios are being validated here -- authenticated/known user and unauthenticated/anonymous user For a known user we expect the checkout link to point to Otto in a scenario where the CommerceConfiguration is active and the course mode is PROFESSIONAL. """ if not is_anonymous: self.assert_enrollment_link_present(is_anonymous=is_anonymous) else: self.assertEqual(EcommerceService().is_enabled(AnonymousUser()), False) def test_user_groups(self): # deprecated function mock_user = MagicMock() type(mock_user).is_authenticated = PropertyMock(return_value=False) self.assertEqual(views.user_groups(mock_user), []) def test_get_redirect_url(self): # test the course location self.assertEqual( u'/courses/{course_key}/courseware?{activate_block_id}'.format( course_key=text_type(self.course_key), activate_block_id=urlencode({'activate_block_id': text_type(self.course.location)}) ), get_redirect_url(self.course_key, self.course.location), ) # test a section location self.assertEqual( u'/courses/{course_key}/courseware/Chapter_1/Sequential_1/?{activate_block_id}'.format( course_key=text_type(self.course_key), activate_block_id=urlencode({'activate_block_id': text_type(self.section.location)}) ), get_redirect_url(self.course_key, self.section.location), ) def test_invalid_course_id(self): response = self.client.get('/courses/MITx/3.091X/') self.assertEqual(response.status_code, 404) def test_incomplete_course_id(self): response = self.client.get('/courses/MITx/') self.assertEqual(response.status_code, 404) def test_index_invalid_position(self): request_url = '/'.join([ '/courses', six.text_type(self.course.id), 'courseware', self.chapter.location.block_id, self.section.location.block_id, 'f' ]) self.assertTrue(self.client.login(username=self.user.username, password=TEST_PASSWORD)) response = self.client.get(request_url) self.assertEqual(response.status_code, 404) def test_unicode_handling_in_url(self): url_parts = [ '/courses', six.text_type(self.course.id), 'courseware', self.chapter.location.block_id, self.section.location.block_id, '1' ] self.assertTrue(self.client.login(username=self.user.username, password=TEST_PASSWORD)) for idx, val in enumerate(url_parts): url_parts_copy = url_parts[:] url_parts_copy[idx] = val + u'χ' request_url = '/'.join(url_parts_copy) response = self.client.get(request_url) self.assertEqual(response.status_code, 404) def test_jump_to_invalid(self): # TODO add a test for invalid location # TODO add a test for no data * response = self.client.get(reverse('jump_to', args=['foo/bar/baz', 'baz'])) self.assertEqual(response.status_code, 404) def verify_end_date(self, course_id, expected_end_text=None): """ Visits the about page for `course_id` and tests that both the text "Classes End", as well as the specified `expected_end_text`, is present on the page. If `expected_end_text` is None, verifies that the about page *does not* contain the text "Classes End". """ result = self.client.get(reverse('about_course', args=[six.text_type(course_id)])) if expected_end_text is not None: self.assertContains(result, "Classes End") self.assertContains(result, expected_end_text) else: self.assertNotContains(result, "Classes End") def test_submission_history_accepts_valid_ids(self): # log into a staff account admin = AdminFactory() self.assertTrue(self.client.login(username=admin.username, password='test')) url = reverse('submission_history', kwargs={ 'course_id': six.text_type(self.course_key), 'student_username': 'dummy', 'location': six.text_type(self.problem.location), }) response = self.client.get(url) # Tests that we do not get an "Invalid x" response when passing correct arguments to view self.assertNotContains(response, 'Invalid') def test_submission_history_xss(self): # log into a staff account admin = AdminFactory() self.assertTrue(self.client.login(username=admin.username, password='test')) # try it with an existing user and a malicious location url = reverse('submission_history', kwargs={ 'course_id': six.text_type(self.course_key), 'student_username': 'dummy', 'location': '<script>alert("hello");</script>' }) response = self.client.get(url) self.assertNotContains(response, '<script>') # try it with a malicious user and a non-existent location url = reverse('submission_history', kwargs={ 'course_id': six.text_type(self.course_key), 'student_username': '<script>alert("hello");</script>', 'location': 'dummy' }) response = self.client.get(url) self.assertNotContains(response, '<script>') def test_submission_history_contents(self): # log into a staff account admin = AdminFactory.create() self.assertTrue(self.client.login(username=admin.username, password='test')) usage_key = self.course_key.make_usage_key('problem', 'test-history') state_client = DjangoXBlockUserStateClient(admin) # store state via the UserStateClient state_client.set( username=admin.username, block_key=usage_key, state={'field_a': 'x', 'field_b': 'y'} ) set_score(admin.id, usage_key, 0, 3) state_client.set( username=admin.username, block_key=usage_key, state={'field_a': 'a', 'field_b': 'b'} ) set_score(admin.id, usage_key, 3, 3) url = reverse('submission_history', kwargs={ 'course_id': six.text_type(self.course_key), 'student_username': admin.username, 'location': six.text_type(usage_key), }) response = self.client.get(url) response_content = HTMLParser().unescape(response.content.decode('utf-8')) # We have update the state 4 times: twice to change content, and twice # to set the scores. We'll check that the identifying content from each is # displayed (but not the order), and also the indexes assigned in the output # #1 - #4 self.assertIn('#1', response_content) self.assertIn(json.dumps({'field_a': 'a', 'field_b': 'b'}, sort_keys=True, indent=2), response_content) self.assertIn("Score: 0.0 / 3.0", response_content) self.assertIn(json.dumps({'field_a': 'x', 'field_b': 'y'}, sort_keys=True, indent=2), response_content) self.assertIn("Score: 3.0 / 3.0", response_content) self.assertIn('#4', response_content) @ddt.data(('America/New_York', -5), # UTC - 5 ('Asia/Pyongyang', 9), # UTC + 9 ('Europe/London', 0), # UTC ('Canada/Yukon', -8), # UTC - 8 ('Europe/Moscow', 4)) # UTC + 3 + 1 for daylight savings @ddt.unpack def test_submission_history_timezone(self, timezone, hour_diff): with freeze_time('2012-01-01'): with (override_settings(TIME_ZONE=timezone)): course = CourseFactory.create() course_key = course.id client = Client() admin = AdminFactory.create() self.assertTrue(client.login(username=admin.username, password='test')) state_client = DjangoXBlockUserStateClient(admin) usage_key = course_key.make_usage_key('problem', 'test-history') state_client.set( username=admin.username, block_key=usage_key, state={'field_a': 'x', 'field_b': 'y'} ) url = reverse('submission_history', kwargs={ 'course_id': six.text_type(course_key), 'student_username': admin.username, 'location': six.text_type(usage_key), }) response = client.get(url) expected_time = datetime.now() + timedelta(hours=hour_diff) expected_tz = expected_time.strftime('%Z') self.assertContains(response, expected_tz) self.assertContains(response, str(expected_time)) def _email_opt_in_checkbox(self, response, org_name_string=None): """Check if the email opt-in checkbox appears in the response content.""" checkbox_html = '<input id="email-opt-in" type="checkbox" name="opt-in" class="email-opt-in" value="true" checked>' if org_name_string: # Verify that the email opt-in checkbox appears, and that the expected # organization name is displayed. self.assertContains(response, checkbox_html, html=True) self.assertContains(response, org_name_string) else: # Verify that the email opt-in checkbox does not appear self.assertNotContains(response, checkbox_html, html=True) def test_financial_assistance_page(self): url = reverse('financial_assistance') response = self.client.get(url) # This is a static page, so just assert that it is returned correctly self.assertEqual(response.status_code, 200) self.assertContains(response, 'Financial Assistance Application') @ddt.data(([CourseMode.AUDIT, CourseMode.VERIFIED], CourseMode.AUDIT, True, YESTERDAY), ([CourseMode.AUDIT, CourseMode.VERIFIED], CourseMode.VERIFIED, True, None), ([CourseMode.AUDIT, CourseMode.VERIFIED], CourseMode.AUDIT, False, None), ([CourseMode.AUDIT], CourseMode.AUDIT, False, None)) @ddt.unpack def test_financial_assistance_form_course_exclusion( self, course_modes, enrollment_mode, eligible_for_aid, expiration): """Verify that learner cannot get the financial aid for the courses having one of the following attributes: 1. User is enrolled in the verified mode. 2. Course is expired. 3. Course does not provide financial assistance. 4. Course does not have verified mode. """ # Create course course = CourseFactory.create() # Create Course Modes for mode in course_modes: CourseModeFactory.create(mode_slug=mode, course_id=course.id, expiration_datetime=self.DATES[expiration]) # Enroll user in the course CourseEnrollmentFactory(course_id=course.id, user=self.user, mode=enrollment_mode) # load course into course overview CourseOverview.get_from_id(course.id) # add whether course is eligible for financial aid or not course_overview = CourseOverview.objects.get(id=course.id) course_overview.eligible_for_financial_aid = eligible_for_aid course_overview.save() url = reverse('financial_assistance_form') response = self.client.get(url) self.assertEqual(response.status_code, 200) self.assertNotContains(response, str(course.id)) @patch.object(CourseOverview, 'load_from_module_store', return_value=None) def test_financial_assistance_form_missing_course_overview(self, _mock_course_overview): """ Verify that learners can not get financial aid for the courses with no course overview. """ # Create course course = CourseFactory.create().id # Create Course Modes CourseModeFactory.create(mode_slug=CourseMode.AUDIT, course_id=course) CourseModeFactory.create(mode_slug=CourseMode.VERIFIED, course_id=course) # Enroll user in the course # Don't use the CourseEnrollmentFactory since it ensures a CourseOverview is available enrollment = CourseEnrollment.objects.create( course_id=course, user=self.user, mode=CourseMode.AUDIT, ) self.assertEqual(enrollment.course_overview, None) url = reverse('financial_assistance_form') response = self.client.get(url) self.assertEqual(response.status_code, 200) self.assertNotContains(response, str(course)) def test_financial_assistance_form(self): """Verify that learner can get the financial aid for the course in which he/she is enrolled in audit mode whereas the course provide verified mode. """ # Create course course = CourseFactory.create().id # Create Course Modes CourseModeFactory.create(mode_slug=CourseMode.AUDIT, course_id=course) CourseModeFactory.create(mode_slug=CourseMode.VERIFIED, course_id=course) # Enroll user in the course CourseEnrollmentFactory(course_id=course, user=self.user, mode=CourseMode.AUDIT) # load course into course overview CourseOverview.get_from_id(course) url = reverse('financial_assistance_form') response = self.client.get(url) self.assertEqual(response.status_code, 200) self.assertContains(response, str(course)) def _submit_financial_assistance_form(self, data): """Submit a financial assistance request.""" url = reverse('submit_financial_assistance_request') return self.client.post(url, json.dumps(data), content_type='application/json') @patch.object(views, 'create_zendesk_ticket', return_value=200) def test_submit_financial_assistance_request(self, mock_create_zendesk_ticket): username = self.user.username course = six.text_type(self.course_key) legal_name = 'Jesse Pinkman' country = 'United States' income = '1234567890' reason_for_applying = "It's just basic chemistry, yo." goals = "I don't know if it even matters, but... work with my hands, I guess." effort = "I'm done, okay? You just give me my money, and you and I, we're done." data = { 'username': username, 'course': course, 'name': legal_name, 'email': self.user.email, 'country': country, 'income': income, 'reason_for_applying': reason_for_applying, 'goals': goals, 'effort': effort, 'mktg-permission': False, } response = self._submit_financial_assistance_form(data) self.assertEqual(response.status_code, 204) __, __, ticket_subject, __ = mock_create_zendesk_ticket.call_args[0] mocked_kwargs = mock_create_zendesk_ticket.call_args[1] group_name = mocked_kwargs['group'] tags = mocked_kwargs['tags'] additional_info = mocked_kwargs['additional_info'] private_comment = '\n'.join(list(additional_info.values())) for info in (country, income, reason_for_applying, goals, effort, username, legal_name, course): self.assertIn(info, private_comment) self.assertEqual(additional_info['Allowed for marketing purposes'], 'No') self.assertEqual( ticket_subject, u'Financial assistance request for learner {username} in course {course}'.format( username=username, course=self.course.display_name ) ) self.assertDictContainsSubset({'course_id': course}, tags) self.assertIn('Client IP', additional_info) self.assertEqual(group_name, 'Financial Assistance') @patch.object(views, 'create_zendesk_ticket', return_value=500) def test_zendesk_submission_failed(self, _mock_create_zendesk_ticket): response = self._submit_financial_assistance_form({ 'username': self.user.username, 'course': six.text_type(self.course.id), 'name': '', 'email': '', 'country': '', 'income': '', 'reason_for_applying': '', 'goals': '', 'effort': '', 'mktg-permission': False, }) self.assertEqual(response.status_code, 500) @ddt.data( ({}, 400), ({'username': 'wwhite'}, 403), ({'username': 'dummy', 'course': 'bad course ID'}, 400) ) @ddt.unpack def test_submit_financial_assistance_errors(self, data, status): response = self._submit_financial_assistance_form(data) self.assertEqual(response.status_code, status) def test_financial_assistance_login_required(self): for url in ( reverse('financial_assistance'), reverse('financial_assistance_form'), reverse('submit_financial_assistance_request') ): self.client.logout() response = self.client.get(url) self.assertRedirects(response, reverse('signin_user') + '?next=' + url) @override_waffle_flag(UNIFIED_COURSE_TAB_FLAG, active=False) def test_bypass_course_info(self): course_id = six.text_type(self.course_key) self.assertFalse(self.course.bypass_home) response = self.client.get(reverse('info', args=[course_id])) self.assertEqual(response.status_code, 200) response = self.client.get(reverse('info', args=[course_id]), HTTP_REFERER=reverse('dashboard')) self.assertEqual(response.status_code, 200) self.course.bypass_home = True self.store.update_item(self.course, self.user.id) self.assertTrue(self.course.bypass_home) response = self.client.get(reverse('info', args=[course_id]), HTTP_REFERER=reverse('dashboard')) self.assertRedirects(response, reverse('courseware', args=[course_id]), fetch_redirect_response=False) response = self.client.get(reverse('info', args=[course_id]), HTTP_REFERER='foo') self.assertEqual(response.status_code, 200) # TODO: TNL-6387: Remove test @override_waffle_flag(COURSE_OUTLINE_PAGE_FLAG, active=False) def test_accordion(self): """ This needs a response_context, which is not included in the render_accordion's main method returning a render_to_string, so we will render via the courseware URL in order to include the needed context """ course_id = quote(six.text_type(self.course.id).encode("utf-8")) response = self.client.get( reverse('courseware', args=[six.text_type(course_id)]), follow=True ) test_responses = [ '<p class="accordion-display-name">Sequential 1 <span class="sr">current section</span></p>', '<p class="accordion-display-name">Sequential 2 </p>' ] for test in test_responses: self.assertContains(response, test) # Patching 'lms.djangoapps.courseware.views.views.get_programs' would be ideal, # but for some unknown reason that patch doesn't seem to be applied. @patch('openedx.core.djangoapps.catalog.utils.cache') class TestProgramMarketingView(SharedModuleStoreTestCase): """Unit tests for the program marketing page.""" program_uuid = str(uuid4()) url = reverse_lazy('program_marketing_view', kwargs={'program_uuid': program_uuid}) @classmethod def setUpClass(cls): super(TestProgramMarketingView, cls).setUpClass() modulestore_course = CourseFactory() course_run = CourseRunFactory(key=six.text_type(modulestore_course.id)) course = CatalogCourseFactory(course_runs=[course_run]) cls.data = ProgramFactory( courses=[course], is_program_eligible_for_one_click_purchase=False, uuid=cls.program_uuid, ) def test_404_if_no_data(self, mock_cache): """ Verify that the page 404s if no program data is found. """ mock_cache.get.return_value = None response = self.client.get(self.url) self.assertEqual(response.status_code, 404) def test_200(self, mock_cache): """ Verify the view returns a 200. """ mock_cache.get.return_value = self.data response = self.client.get(self.url) self.assertEqual(response.status_code, 200) # setting TIME_ZONE_DISPLAYED_FOR_DEADLINES explicitly @override_settings(TIME_ZONE_DISPLAYED_FOR_DEADLINES="UTC") class BaseDueDateTests(ModuleStoreTestCase): """ Base class that verifies that due dates are rendered correctly on a page """ __test__ = False def get_response(self, course): """Return the rendered text for the page to be verified""" raise NotImplementedError def set_up_course(self, **course_kwargs): """ Create a stock course with a specific due date. :param course_kwargs: All kwargs are passed to through to the :class:`CourseFactory` """ course = CourseFactory.create(**course_kwargs) with self.store.bulk_operations(course.id): chapter = ItemFactory.create(category='chapter', parent_location=course.location) section = ItemFactory.create( category='sequential', parent_location=chapter.location, due=datetime(2013, 9, 18, 11, 30, 00), format='homework' ) vertical = ItemFactory.create(category='vertical', parent_location=section.location) ItemFactory.create(category='problem', parent_location=vertical.location) course = modulestore().get_course(course.id) self.assertIsNotNone(course.get_children()[0].get_children()[0].due) CourseEnrollmentFactory(user=self.user, course_id=course.id) CourseOverview.load_from_module_store(course.id) return course def setUp(self): super(BaseDueDateTests, self).setUp() self.user = UserFactory.create() self.assertTrue(self.client.login(username=self.user.username, password='test')) self.time_with_tz = "2013-09-18 11:30:00+00:00" def test_backwards_compatibility(self): # The test course being used has show_timezone = False in the policy file # (and no due_date_display_format set). This is to test our backwards compatibility-- # in course_module's init method, the date_display_format will be set accordingly to # remove the timezone. course = self.set_up_course(due_date_display_format=None, show_timezone=False) response = self.get_response(course) self.assertContains(response, self.time_with_tz) # Test that show_timezone has been cleared (which means you get the default value of True). self.assertTrue(course.show_timezone) def test_defaults(self): course = self.set_up_course() response = self.get_response(course) self.assertContains(response, self.time_with_tz) def test_format_none(self): # Same for setting the due date to None course = self.set_up_course(due_date_display_format=None) response = self.get_response(course) self.assertContains(response, self.time_with_tz) def test_format_date(self): # due date with no time course = self.set_up_course(due_date_display_format=u"%b %d %y") response = self.get_response(course) self.assertContains(response, self.time_with_tz) def test_format_invalid(self): # improperly formatted due_date_display_format falls through to default # (value of show_timezone does not matter-- setting to False to make that clear). course = self.set_up_course(due_date_display_format=u"%%%", show_timezone=False) response = self.get_response(course) self.assertNotContains(response, "%%%") self.assertContains(response, self.time_with_tz) class TestProgressDueDate(BaseDueDateTests): """ Test that the progress page displays due dates correctly """ __test__ = True def get_response(self, course): """ Returns the HTML for the progress page """ return self.client.get(reverse('progress', args=[six.text_type(course.id)])) # TODO: LEARNER-71: Delete entire TestAccordionDueDate class class TestAccordionDueDate(BaseDueDateTests): """ Test that the accordion page displays due dates correctly """ __test__ = True def get_response(self, course): """ Returns the HTML for the accordion """ return self.client.get( reverse('courseware', args=[six.text_type(course.id)]), follow=True ) # TODO: LEARNER-71: Delete entire TestAccordionDueDate class @override_waffle_flag(COURSE_OUTLINE_PAGE_FLAG, active=False) def test_backwards_compatibility(self): super(TestAccordionDueDate, self).test_backwards_compatibility() # TODO: LEARNER-71: Delete entire TestAccordionDueDate class @override_waffle_flag(COURSE_OUTLINE_PAGE_FLAG, active=False) def test_defaults(self): super(TestAccordionDueDate, self).test_defaults() # TODO: LEARNER-71: Delete entire TestAccordionDueDate class @override_waffle_flag(COURSE_OUTLINE_PAGE_FLAG, active=False) def test_format_date(self): super(TestAccordionDueDate, self).test_format_date() # TODO: LEARNER-71: Delete entire TestAccordionDueDate class @override_waffle_flag(COURSE_OUTLINE_PAGE_FLAG, active=False) def test_format_invalid(self): super(TestAccordionDueDate, self).test_format_invalid() # TODO: LEARNER-71: Delete entire TestAccordionDueDate class @override_waffle_flag(COURSE_OUTLINE_PAGE_FLAG, active=False) def test_format_none(self): super(TestAccordionDueDate, self).test_format_none() class StartDateTests(ModuleStoreTestCase): """ Test that start dates are properly localized and displayed on the student dashboard. """ def setUp(self): super(StartDateTests, self).setUp() self.user = UserFactory.create() def set_up_course(self): """ Create a stock course with a specific due date. :param course_kwargs: All kwargs are passed to through to the :class:`CourseFactory` """ course = CourseFactory.create(start=datetime(2013, 9, 16, 7, 17, 28)) course = modulestore().get_course(course.id) return course def get_about_response(self, course_key): """ Get the text of the /about page for the course. """ return self.client.get(reverse('about_course', args=[six.text_type(course_key)])) @patch('util.date_utils.pgettext', fake_pgettext(translations={ ("abbreviated month name", "Sep"): "SEPTEMBER", })) @patch('util.date_utils.ugettext', fake_ugettext(translations={ "SHORT_DATE_FORMAT": "%Y-%b-%d", })) def test_format_localized_in_studio_course(self): course = self.set_up_course() response = self.get_about_response(course.id) # The start date is set in the set_up_course function above. # This should return in the format '%Y-%m-%dT%H:%M:%S%z' self.assertContains(response, "2013-09-16T07:17:28+0000") class ProgressPageBaseTests(ModuleStoreTestCase): """ Base class for progress page tests. """ ENABLED_CACHES = ['default', 'mongo_modulestore_inheritance', 'loc_cache'] ENABLED_SIGNALS = ['course_published'] def setUp(self): super(ProgressPageBaseTests, self).setUp() self.user = UserFactory.create() self.assertTrue(self.client.login(username=self.user.username, password='test')) self.setup_course() def create_course(self, **options): """Create the test course.""" self.course = CourseFactory.create( start=datetime(2013, 9, 16, 7, 17, 28), grade_cutoffs={u'çü†øƒƒ': 0.75, 'Pass': 0.5}, end=datetime.now(), certificate_available_date=datetime.now(UTC), **options ) def setup_course(self, **course_options): """Create the test course and content, and enroll the user.""" self.create_course(**course_options) with self.store.bulk_operations(self.course.id): self.chapter = ItemFactory.create(category='chapter', parent_location=self.course.location) self.section = ItemFactory.create(category='sequential', parent_location=self.chapter.location) self.vertical = ItemFactory.create(category='vertical', parent_location=self.section.location) CourseEnrollmentFactory(user=self.user, course_id=self.course.id, mode=CourseMode.HONOR) def _get_progress_page(self, expected_status_code=200): """ Gets the progress page for the currently logged-in user. """ resp = self.client.get( reverse('progress', args=[six.text_type(self.course.id)]) ) self.assertEqual(resp.status_code, expected_status_code) return resp def _get_student_progress_page(self, expected_status_code=200): """ Gets the progress page for the user in the course. """ resp = self.client.get( reverse('student_progress', args=[six.text_type(self.course.id), self.user.id]) ) self.assertEqual(resp.status_code, expected_status_code) return resp # pylint: disable=protected-access @patch('lms.djangoapps.certificates.api.get_active_web_certificate', PropertyMock(return_value=True)) @ddt.ddt class ProgressPageTests(ProgressPageBaseTests): """ Tests that verify that the progress page works correctly. """ @ddt.data('"><script>alert(1)</script>', '<script>alert(1)</script>', '</script><script>alert(1)</script>') def test_progress_page_xss_prevent(self, malicious_code): """ Test that XSS attack is prevented """ resp = self._get_student_progress_page() # Test that malicious code does not appear in html self.assertNotContains(resp, malicious_code) def test_pure_ungraded_xblock(self): ItemFactory.create(category='acid', parent_location=self.vertical.location) self._get_progress_page() @ddt.data(ModuleStoreEnum.Type.mongo, ModuleStoreEnum.Type.split) def test_student_progress_with_valid_and_invalid_id(self, default_store): """ Check that invalid 'student_id' raises Http404 for both old mongo and split mongo courses. """ # Create new course with respect to 'default_store' # Enroll student into course self.course = CourseFactory.create(default_store=default_store) CourseEnrollmentFactory(user=self.user, course_id=self.course.id, mode=CourseMode.HONOR) # Invalid Student Ids (Integer and Non-int) invalid_student_ids = [ 991021, 'azU3N_8$', ] for invalid_id in invalid_student_ids: resp = self.client.get( reverse('student_progress', args=[six.text_type(self.course.id), invalid_id]) ) self.assertEqual(resp.status_code, 404) # Assert that valid 'student_id' returns 200 status self._get_student_progress_page() @ddt.data(ModuleStoreEnum.Type.mongo, ModuleStoreEnum.Type.split) def test_unenrolled_student_progress_for_credit_course(self, default_store): """ Test that student progress page does not break while checking for an unenrolled student. Scenario: When instructor checks the progress of a student who is not enrolled in credit course. It should return 200 response. """ # Create a new course, a user which will not be enrolled in course, admin user for staff access course = CourseFactory.create(default_store=default_store) admin = AdminFactory.create() self.assertTrue(self.client.login(username=admin.username, password='test')) # Create and enable Credit course CreditCourse.objects.create(course_key=course.id, enabled=True) # Configure a credit provider for the course CreditProvider.objects.create( provider_id="ASU", enable_integration=True, provider_url="https://credit.example.com/request" ) requirements = [{ "namespace": "grade", "name": "grade", "display_name": "Grade", "criteria": {"min_grade": 0.52}, }] # Add a single credit requirement (final grade) set_credit_requirements(course.id, requirements) self._get_student_progress_page() def test_non_ascii_grade_cutoffs(self): self._get_progress_page() def test_generate_cert_config(self): resp = self._get_progress_page() self.assertNotContains(resp, 'Request Certificate') # Enable the feature, but do not enable it for this course CertificateGenerationConfiguration(enabled=True).save() resp = self._get_progress_page() self.assertNotContains(resp, 'Request Certificate') # Enable certificate generation for this course certs_api.set_cert_generation_enabled(self.course.id, True) resp = self._get_progress_page() self.assertNotContains(resp, 'Request Certificate') @patch.dict('django.conf.settings.FEATURES', {'CERTIFICATES_HTML_VIEW': True}) def test_view_certificate_for_unverified_student(self): """ If user has already generated a certificate, it should be visible in case of user being unverified too. """ GeneratedCertificateFactory.create( user=self.user, course_id=self.course.id, status=CertificateStatuses.downloadable, mode='verified' ) # Enable the feature, but do not enable it for this course CertificateGenerationConfiguration(enabled=True).save() # Enable certificate generation for this course certs_api.set_cert_generation_enabled(self.course.id, True) CourseEnrollment.enroll(self.user, self.course.id, mode="verified") # Check that the user is unverified self.assertFalse(IDVerificationService.user_is_verified(self.user)) with patch('lms.djangoapps.grades.course_grade_factory.CourseGradeFactory.read') as mock_create: course_grade = mock_create.return_value course_grade.passed = True course_grade.summary = {'grade': 'Pass', 'percent': 0.75, 'section_breakdown': [], 'grade_breakdown': {}} resp = self._get_progress_page() self.assertNotContains(resp, u"Certificate unavailable") self.assertContains(resp, u"Your certificate is available") @patch.dict('django.conf.settings.FEATURES', {'CERTIFICATES_HTML_VIEW': True}) def test_view_certificate_link(self): """ If certificate web view is enabled then certificate web view button should appear for user who certificate is available/generated """ certificate = GeneratedCertificateFactory.create( user=self.user, course_id=self.course.id, status=CertificateStatuses.downloadable, download_url="http://www.example.com/certificate.pdf", mode='honor' ) # Enable the feature, but do not enable it for this course CertificateGenerationConfiguration(enabled=True).save() # Enable certificate generation for this course certs_api.set_cert_generation_enabled(self.course.id, True) # Course certificate configurations certificates = [ { 'id': 1, 'name': 'Name 1', 'description': 'Description 1', 'course_title': 'course_title_1', 'signatories': [], 'version': 1, 'is_active': True } ] self.course.certificates = {'certificates': certificates} self.course.cert_html_view_enabled = True self.course.save() self.store.update_item(self.course, self.user.id) with patch('lms.djangoapps.grades.course_grade_factory.CourseGradeFactory.read') as mock_create: course_grade = mock_create.return_value course_grade.passed = True course_grade.summary = {'grade': 'Pass', 'percent': 0.75, 'section_breakdown': [], 'grade_breakdown': {}} resp = self._get_progress_page() self.assertContains(resp, u"View Certificate") self.assertContains(resp, u"earned a certificate for this course") cert_url = certs_api.get_certificate_url(course_id=self.course.id, uuid=certificate.verify_uuid) self.assertContains(resp, cert_url) # when course certificate is not active certificates[0]['is_active'] = False self.store.update_item(self.course, self.user.id) resp = self._get_progress_page() self.assertNotContains(resp, u"View Your Certificate") self.assertNotContains(resp, u"You can now view your certificate") self.assertContains(resp, "Your certificate is available") self.assertContains(resp, "earned a certificate for this course.") @patch.dict('django.conf.settings.FEATURES', {'CERTIFICATES_HTML_VIEW': False}) def test_view_certificate_link_hidden(self): """ If certificate web view is disabled then certificate web view button should not appear for user who certificate is available/generated """ GeneratedCertificateFactory.create( user=self.user, course_id=self.course.id, status=CertificateStatuses.downloadable, download_url="http://www.example.com/certificate.pdf", mode='honor' ) # Enable the feature, but do not enable it for this course CertificateGenerationConfiguration(enabled=True).save() # Enable certificate generation for this course certs_api.set_cert_generation_enabled(self.course.id, True) with patch('lms.djangoapps.grades.course_grade_factory.CourseGradeFactory.read') as mock_create: course_grade = mock_create.return_value course_grade.passed = True course_grade.summary = {'grade': 'Pass', 'percent': 0.75, 'section_breakdown': [], 'grade_breakdown': {}} resp = self._get_progress_page() self.assertContains(resp, u"Download Your Certificate") @ddt.data( (True, 54), (False, 53), ) @ddt.unpack def test_progress_queries_paced_courses(self, self_paced, query_count): """Test that query counts remain the same for self-paced and instructor-paced courses.""" # TODO: decrease query count as part of REVO-28 ContentTypeGatingConfig.objects.create(enabled=True, enabled_as_of=datetime(2018, 1, 1)) self.setup_course(self_paced=self_paced) with self.assertNumQueries(query_count, table_blacklist=QUERY_COUNT_TABLE_BLACKLIST), check_mongo_calls(1): self._get_progress_page() @patch.dict(settings.FEATURES, {'ASSUME_ZERO_GRADE_IF_ABSENT_FOR_ALL_TESTS': False}) @ddt.data( (False, 62, 41), (True, 53, 36) ) @ddt.unpack def test_progress_queries(self, enable_waffle, initial, subsequent): ContentTypeGatingConfig.objects.create(enabled=True, enabled_as_of=datetime(2018, 1, 1)) self.setup_course() with grades_waffle().override(ASSUME_ZERO_GRADE_IF_ABSENT, active=enable_waffle): with self.assertNumQueries( initial, table_blacklist=QUERY_COUNT_TABLE_BLACKLIST ), check_mongo_calls(1): self._get_progress_page() # subsequent accesses to the progress page require fewer queries. for _ in range(2): with self.assertNumQueries( subsequent, table_blacklist=QUERY_COUNT_TABLE_BLACKLIST ), check_mongo_calls(1): self._get_progress_page() @ddt.data( *itertools.product( ( CourseMode.AUDIT, CourseMode.HONOR, CourseMode.VERIFIED, CourseMode.PROFESSIONAL, CourseMode.NO_ID_PROFESSIONAL_MODE, CourseMode.CREDIT_MODE ), (True, False) ) ) @ddt.unpack def test_show_certificate_request_button(self, course_mode, user_verified): """Verify that the Request Certificate is not displayed in audit mode.""" CertificateGenerationConfiguration(enabled=True).save() certs_api.set_cert_generation_enabled(self.course.id, True) CourseEnrollment.enroll(self.user, self.course.id, mode=course_mode) with patch( 'lms.djangoapps.verify_student.services.IDVerificationService.user_is_verified' ) as user_verify: user_verify.return_value = user_verified with patch('lms.djangoapps.grades.course_grade_factory.CourseGradeFactory.read') as mock_create: course_grade = mock_create.return_value course_grade.passed = True course_grade.summary = { 'grade': 'Pass', 'percent': 0.75, 'section_breakdown': [], 'grade_breakdown': {} } resp = self._get_progress_page() cert_button_hidden = course_mode is CourseMode.AUDIT or \ course_mode in CourseMode.VERIFIED_MODES and not user_verified self.assertEqual( cert_button_hidden, 'Request Certificate' not in resp.content.decode('utf-8') ) @patch.dict('django.conf.settings.FEATURES', {'CERTIFICATES_HTML_VIEW': True}) def test_page_with_invalidated_certificate_with_html_view(self): """ Verify that for html certs if certificate is marked as invalidated than re-generate button should not appear on progress page. """ generated_certificate = self.generate_certificate( "http://www.example.com/certificate.pdf", "honor" ) # Course certificate configurations certificates = [ { 'id': 1, 'name': 'dummy', 'description': 'dummy description', 'course_title': 'dummy title', 'signatories': [], 'version': 1, 'is_active': True } ] self.course.certificates = {'certificates': certificates} self.course.cert_html_view_enabled = True self.course.save() self.store.update_item(self.course, self.user.id) with patch('lms.djangoapps.grades.course_grade_factory.CourseGradeFactory.read') as mock_create: course_grade = mock_create.return_value course_grade.passed = True course_grade.summary = { 'grade': 'Pass', 'percent': 0.75, 'section_breakdown': [], 'grade_breakdown': {} } resp = self._get_progress_page() self.assertContains(resp, u"View Certificate") self.assert_invalidate_certificate(generated_certificate) @patch.dict('django.conf.settings.FEATURES', {'CERTIFICATES_HTML_VIEW': True}) def test_page_with_whitelisted_certificate_with_html_view(self): """ Verify that for white listed user the view certificate is appearing on dashboard """ generated_certificate = self.generate_certificate( "http://www.example.com/certificate.pdf", "honor" ) # Course certificate configurations certificates = [ { 'id': 1, 'name': 'dummy', 'description': 'dummy description', 'course_title': 'dummy title', 'signatories': [], 'version': 1, 'is_active': True } ] self.course.certificates = {'certificates': certificates} self.course.cert_html_view_enabled = True self.course.save() self.store.update_item(self.course, self.user.id) CertificateWhitelist.objects.create( user=self.user, course_id=self.course.id, whitelist=True ) with patch('lms.djangoapps.grades.course_grade_factory.CourseGradeFactory.read') as mock_create: course_grade = mock_create.return_value course_grade.passed = False course_grade.summary = { 'grade': 'Fail', 'percent': 0.75, 'section_breakdown': [], 'grade_breakdown': {} } resp = self._get_progress_page() self.assertContains(resp, u"View Certificate") self.assert_invalidate_certificate(generated_certificate) def test_page_with_invalidated_certificate_with_pdf(self): """ Verify that for pdf certs if certificate is marked as invalidated than re-generate button should not appear on progress page. """ generated_certificate = self.generate_certificate( "http://www.example.com/certificate.pdf", "honor" ) with patch('lms.djangoapps.grades.course_grade_factory.CourseGradeFactory.read') as mock_create: course_grade = mock_create.return_value course_grade.passed = True course_grade.summary = {'grade': 'Pass', 'percent': 0.75, 'section_breakdown': [], 'grade_breakdown': {}} resp = self._get_progress_page() self.assertContains(resp, u'Download Your Certificate') self.assert_invalidate_certificate(generated_certificate) @ddt.data( *itertools.product( ( CourseMode.AUDIT, CourseMode.HONOR, CourseMode.VERIFIED, CourseMode.PROFESSIONAL, CourseMode.NO_ID_PROFESSIONAL_MODE, CourseMode.CREDIT_MODE ) ) ) @ddt.unpack def test_progress_with_course_duration_limits(self, course_mode): """ Verify that expired banner message appears on progress page, if learner is enrolled in audit mode. """ CourseDurationLimitConfig.objects.create(enabled=True, enabled_as_of=datetime(2018, 1, 1)) user = UserFactory.create() self.assertTrue(self.client.login(username=user.username, password='test')) add_course_mode(self.course, upgrade_deadline_expired=False) CourseEnrollmentFactory(user=user, course_id=self.course.id, mode=course_mode) response = self._get_progress_page() bannerText = get_expiration_banner_text(user, self.course) if course_mode == CourseMode.AUDIT: self.assertContains(response, bannerText, html=True) else: self.assertNotContains(response, bannerText, html=True) @ddt.data( *itertools.product( ( CourseMode.AUDIT, CourseMode.HONOR, CourseMode.VERIFIED, CourseMode.PROFESSIONAL, CourseMode.NO_ID_PROFESSIONAL_MODE, CourseMode.CREDIT_MODE ) ) ) @ddt.unpack def test_progress_without_course_duration_limits(self, course_mode): """ Verify that expired banner message never appears on progress page, regardless of course_mode """ CourseDurationLimitConfig.objects.create(enabled=False) user = UserFactory.create() self.assertTrue(self.client.login(username=user.username, password='test')) CourseModeFactory.create( course_id=self.course.id, mode_slug=course_mode ) CourseEnrollmentFactory(user=user, course_id=self.course.id, mode=course_mode) response = self._get_progress_page() bannerText = get_expiration_banner_text(user, self.course) self.assertNotContains(response, bannerText, html=True) @patch('lms.djangoapps.courseware.views.views.is_course_passed', PropertyMock(return_value=True)) @override_settings(FEATURES=FEATURES_WITH_DISABLE_HONOR_CERTIFICATE) @ddt.data(CourseMode.AUDIT, CourseMode.HONOR) def test_message_for_ineligible_mode(self, course_mode): """ Verify that message appears on progress page, if learner is enrolled in an ineligible mode. """ user = UserFactory.create() self.assertTrue(self.client.login(username=user.username, password='test')) CourseEnrollmentFactory(user=user, course_id=self.course.id, mode=course_mode) with patch('lms.djangoapps.grades.course_grade_factory.CourseGradeFactory.read') as mock_create: course_grade = mock_create.return_value course_grade.passed = True course_grade.summary = {'grade': 'Pass', 'percent': 0.75, 'section_breakdown': [], 'grade_breakdown': {}} response = self._get_progress_page() expected_message = (u'You are enrolled in the {mode} track for this course. ' u'The {mode} track does not include a certificate.').format(mode=course_mode) self.assertContains(response, expected_message) def test_invalidated_cert_data(self): """ Verify that invalidated cert data is returned if cert is invalidated. """ generated_certificate = self.generate_certificate( "http://www.example.com/certificate.pdf", "honor" ) CertificateInvalidationFactory.create( generated_certificate=generated_certificate, invalidated_by=self.user ) # Invalidate user certificate generated_certificate.invalidate() response = views._get_cert_data(self.user, self.course, CourseMode.HONOR, MagicMock(passed=True)) self.assertEqual(response.cert_status, 'invalidated') self.assertEqual(response.title, 'Your certificate has been invalidated') @override_settings(FEATURES=FEATURES_WITH_DISABLE_HONOR_CERTIFICATE) def test_downloadable_get_cert_data(self): """ Verify that downloadable cert data is returned if cert is downloadable even when DISABLE_HONOR_CERTIFICATES feature flag is turned ON. """ self.generate_certificate( "http://www.example.com/certificate.pdf", "honor" ) response = views._get_cert_data( self.user, self.course, CourseMode.HONOR, MagicMock(passed=True) ) self.assertEqual(response.cert_status, 'downloadable') self.assertEqual(response.title, 'Your certificate is available') def test_generating_get_cert_data(self): """ Verify that generating cert data is returned if cert is generating. """ self.generate_certificate( "http://www.example.com/certificate.pdf", "honor" ) with patch('lms.djangoapps.certificates.api.certificate_downloadable_status', return_value=self.mock_certificate_downloadable_status(is_generating=True)): response = views._get_cert_data(self.user, self.course, CourseMode.HONOR, MagicMock(passed=True)) self.assertEqual(response.cert_status, 'generating') self.assertEqual(response.title, "We're working on it...") def test_unverified_get_cert_data(self): """ Verify that unverified cert data is returned if cert is unverified. """ self.generate_certificate( "http://www.example.com/certificate.pdf", "honor" ) with patch('lms.djangoapps.certificates.api.certificate_downloadable_status', return_value=self.mock_certificate_downloadable_status(is_unverified=True)): response = views._get_cert_data(self.user, self.course, CourseMode.HONOR, MagicMock(passed=True)) self.assertEqual(response.cert_status, 'unverified') self.assertEqual(response.title, "Certificate unavailable") def test_request_get_cert_data(self): """ Verify that requested cert data is returned if cert is to be requested. """ self.generate_certificate( "http://www.example.com/certificate.pdf", "honor" ) with patch('lms.djangoapps.certificates.api.certificate_downloadable_status', return_value=self.mock_certificate_downloadable_status()): response = views._get_cert_data(self.user, self.course, CourseMode.HONOR, MagicMock(passed=True)) self.assertEqual(response.cert_status, 'requesting') self.assertEqual(response.title, "Congratulations, you qualified for a certificate!") def assert_invalidate_certificate(self, certificate): """ Dry method to mark certificate as invalid. And assert the response. """ CertificateInvalidationFactory.create( generated_certificate=certificate, invalidated_by=self.user ) # Invalidate user certificate certificate.invalidate() resp = self._get_progress_page() self.assertNotContains(resp, u'Request Certificate') self.assertContains(resp, u'Your certificate has been invalidated') self.assertContains(resp, u'Please contact your course team if you have any questions.') self.assertNotContains(resp, u'View Your Certificate') self.assertNotContains(resp, u'Download Your Certificate') def generate_certificate(self, url, mode): """ Dry method to generate certificate. """ generated_certificate = GeneratedCertificateFactory.create( user=self.user, course_id=self.course.id, status=CertificateStatuses.downloadable, download_url=url, mode=mode ) CertificateGenerationConfiguration(enabled=True).save() certs_api.set_cert_generation_enabled(self.course.id, True) return generated_certificate def mock_certificate_downloadable_status( self, is_downloadable=False, is_generating=False, is_unverified=False, uuid=None, download_url=None ): """Dry method to mock certificate downloadable status response.""" return { 'is_downloadable': is_downloadable, 'is_generating': is_generating, 'is_unverified': is_unverified, 'download_url': uuid, 'uuid': download_url, } @ddt.ddt class ProgressPageShowCorrectnessTests(ProgressPageBaseTests): """ Tests that verify that the progress page works correctly when displaying subsections where correctness is hidden. """ # Constants used in the test data NOW = datetime.now(UTC) DAY_DELTA = timedelta(days=1) YESTERDAY = 'yesterday' TODAY = 'today' TOMORROW = 'tomorrow' GRADER_TYPE = 'Homework' DATES = { YESTERDAY: NOW - DAY_DELTA, TODAY: NOW, TOMORROW: NOW + DAY_DELTA, None: None, } def setUp(self): super(ProgressPageShowCorrectnessTests, self).setUp() self.staff_user = UserFactory.create(is_staff=True) def setup_course(self, show_correctness='', due_date=None, graded=False, **course_options): """ Set up course with a subsection with the given show_correctness, due_date, and graded settings. """ # Use a simple grading policy course_options['grading_policy'] = { "GRADER": [{ "type": self.GRADER_TYPE, "min_count": 2, "drop_count": 0, "short_label": "HW", "weight": 1.0 }], "GRADE_CUTOFFS": { 'A': .9, 'B': .33 } } self.create_course(**course_options) metadata = dict( show_correctness=show_correctness, ) if due_date is not None: metadata['due'] = due_date if graded: metadata['graded'] = True metadata['format'] = self.GRADER_TYPE with self.store.bulk_operations(self.course.id): self.chapter = ItemFactory.create(category='chapter', parent_location=self.course.location, display_name="Section 1") self.section = ItemFactory.create(category='sequential', parent_location=self.chapter.location, display_name="Subsection 1", metadata=metadata) self.vertical = ItemFactory.create(category='vertical', parent_location=self.section.location) CourseEnrollmentFactory(user=self.user, course_id=self.course.id, mode=CourseMode.HONOR) def add_problem(self): """ Add a problem to the subsection """ problem_xml = MultipleChoiceResponseXMLFactory().build_xml( question_text='The correct answer is Choice 1', choices=[True, False], choice_names=['choice_0', 'choice_1'] ) self.problem = ItemFactory.create(category='problem', parent_location=self.vertical.location, data=problem_xml, display_name='Problem 1') # Re-fetch the course from the database self.course = self.store.get_course(self.course.id) def answer_problem(self, value=1, max_value=1): """ Submit the given score to the problem on behalf of the user """ # Get the module for the problem, as viewed by the user field_data_cache = FieldDataCache.cache_for_descriptor_descendents( self.course.id, self.user, self.course, depth=2 ) self.addCleanup(set_current_request, None) module = get_module( self.user, get_mock_request(self.user), self.problem.scope_ids.usage_id, field_data_cache, ) # Submit the given score/max_score to the problem xmodule grade_dict = {'value': value, 'max_value': max_value, 'user_id': self.user.id} module.system.publish(self.problem, 'grade', grade_dict) def assert_progress_page_show_grades(self, response, show_correctness, due_date, graded, show_grades, score, max_score, avg): """ Ensures that grades and scores are shown or not shown on the progress page as required. """ expected_score = u"<dd>{score}/{max_score}</dd>".format(score=score, max_score=max_score) percent = score / float(max_score) # Test individual problem scores if show_grades: # If grades are shown, we should be able to see the current problem scores. self.assertContains(response, expected_score) if graded: expected_summary_text = u"Problem Scores:" else: expected_summary_text = u"Practice Scores:" else: # If grades are hidden, we should not be able to see the current problem scores. self.assertNotContains(response, expected_score) if graded: expected_summary_text = u"Problem scores are hidden" else: expected_summary_text = u"Practice scores are hidden" if show_correctness == ShowCorrectness.PAST_DUE and due_date: expected_summary_text += u' until the due date.' else: expected_summary_text += u'.' # Ensure that expected text is present self.assertContains(response, expected_summary_text) # Test overall sequential score if graded and max_score > 0: percentageString = "{0:.0%}".format(percent) if max_score > 0 else "" template = u'<span> ({0:.3n}/{1:.3n}) {2}</span>' expected_grade_summary = template.format(float(score), float(max_score), percentageString) if show_grades: self.assertContains(response, expected_grade_summary) else: self.assertNotContains(response, expected_grade_summary) @ddt.data( ('', None, False), ('', None, True), (ShowCorrectness.ALWAYS, None, False), (ShowCorrectness.ALWAYS, None, True), (ShowCorrectness.ALWAYS, YESTERDAY, False), (ShowCorrectness.ALWAYS, YESTERDAY, True), (ShowCorrectness.ALWAYS, TODAY, False), (ShowCorrectness.ALWAYS, TODAY, True), (ShowCorrectness.ALWAYS, TOMORROW, False), (ShowCorrectness.ALWAYS, TOMORROW, True), (ShowCorrectness.NEVER, None, False), (ShowCorrectness.NEVER, None, True), (ShowCorrectness.NEVER, YESTERDAY, False), (ShowCorrectness.NEVER, YESTERDAY, True), (ShowCorrectness.NEVER, TODAY, False), (ShowCorrectness.NEVER, TODAY, True), (ShowCorrectness.NEVER, TOMORROW, False), (ShowCorrectness.NEVER, TOMORROW, True), (ShowCorrectness.PAST_DUE, None, False), (ShowCorrectness.PAST_DUE, None, True), (ShowCorrectness.PAST_DUE, YESTERDAY, False), (ShowCorrectness.PAST_DUE, YESTERDAY, True), (ShowCorrectness.PAST_DUE, TODAY, False), (ShowCorrectness.PAST_DUE, TODAY, True), (ShowCorrectness.PAST_DUE, TOMORROW, False), (ShowCorrectness.PAST_DUE, TOMORROW, True), ) @ddt.unpack def test_progress_page_no_problem_scores(self, show_correctness, due_date_name, graded): """ Test that "no problem scores are present" for a course with no problems, regardless of the various show correctness settings. """ self.setup_course(show_correctness=show_correctness, due_date=self.DATES[due_date_name], graded=graded) resp = self._get_progress_page() # Test that no problem scores are present self.assertContains(resp, 'No problem scores in this section') @ddt.data( ('', None, False, True), ('', None, True, True), (ShowCorrectness.ALWAYS, None, False, True), (ShowCorrectness.ALWAYS, None, True, True), (ShowCorrectness.ALWAYS, YESTERDAY, False, True), (ShowCorrectness.ALWAYS, YESTERDAY, True, True), (ShowCorrectness.ALWAYS, TODAY, False, True), (ShowCorrectness.ALWAYS, TODAY, True, True), (ShowCorrectness.ALWAYS, TOMORROW, False, True), (ShowCorrectness.ALWAYS, TOMORROW, True, True), (ShowCorrectness.NEVER, None, False, False), (ShowCorrectness.NEVER, None, True, False), (ShowCorrectness.NEVER, YESTERDAY, False, False), (ShowCorrectness.NEVER, YESTERDAY, True, False), (ShowCorrectness.NEVER, TODAY, False, False), (ShowCorrectness.NEVER, TODAY, True, False), (ShowCorrectness.NEVER, TOMORROW, False, False), (ShowCorrectness.NEVER, TOMORROW, True, False), (ShowCorrectness.PAST_DUE, None, False, True), (ShowCorrectness.PAST_DUE, None, True, True), (ShowCorrectness.PAST_DUE, YESTERDAY, False, True), (ShowCorrectness.PAST_DUE, YESTERDAY, True, True), (ShowCorrectness.PAST_DUE, TODAY, False, True), (ShowCorrectness.PAST_DUE, TODAY, True, True), (ShowCorrectness.PAST_DUE, TOMORROW, False, False), (ShowCorrectness.PAST_DUE, TOMORROW, True, False), ) @ddt.unpack def test_progress_page_hide_scores_from_learner(self, show_correctness, due_date_name, graded, show_grades): """ Test that problem scores are hidden on progress page when correctness is not available to the learner, and that they are visible when it is. """ due_date = self.DATES[due_date_name] self.setup_course(show_correctness=show_correctness, due_date=due_date, graded=graded) self.add_problem() self.client.login(username=self.user.username, password='test') resp = self._get_progress_page() # Ensure that expected text is present self.assert_progress_page_show_grades(resp, show_correctness, due_date, graded, show_grades, 0, 1, 0) # Submit answers to the problem, and re-fetch the progress page self.answer_problem() resp = self._get_progress_page() # Test that the expected text is still present. self.assert_progress_page_show_grades(resp, show_correctness, due_date, graded, show_grades, 1, 1, .5) @ddt.data( ('', None, False, True), ('', None, True, True), (ShowCorrectness.ALWAYS, None, False, True), (ShowCorrectness.ALWAYS, None, True, True), (ShowCorrectness.ALWAYS, YESTERDAY, False, True), (ShowCorrectness.ALWAYS, YESTERDAY, True, True), (ShowCorrectness.ALWAYS, TODAY, False, True), (ShowCorrectness.ALWAYS, TODAY, True, True), (ShowCorrectness.ALWAYS, TOMORROW, False, True), (ShowCorrectness.ALWAYS, TOMORROW, True, True), (ShowCorrectness.NEVER, None, False, False), (ShowCorrectness.NEVER, None, True, False), (ShowCorrectness.NEVER, YESTERDAY, False, False), (ShowCorrectness.NEVER, YESTERDAY, True, False), (ShowCorrectness.NEVER, TODAY, False, False), (ShowCorrectness.NEVER, TODAY, True, False), (ShowCorrectness.NEVER, TOMORROW, False, False), (ShowCorrectness.NEVER, TOMORROW, True, False), (ShowCorrectness.PAST_DUE, None, False, True), (ShowCorrectness.PAST_DUE, None, True, True), (ShowCorrectness.PAST_DUE, YESTERDAY, False, True), (ShowCorrectness.PAST_DUE, YESTERDAY, True, True), (ShowCorrectness.PAST_DUE, TODAY, False, True), (ShowCorrectness.PAST_DUE, TODAY, True, True), (ShowCorrectness.PAST_DUE, TOMORROW, False, True), (ShowCorrectness.PAST_DUE, TOMORROW, True, True), ) @ddt.unpack def test_progress_page_hide_scores_from_staff(self, show_correctness, due_date_name, graded, show_grades): """ Test that problem scores are hidden from staff viewing a learner's progress page only if show_correctness=never. """ due_date = self.DATES[due_date_name] self.setup_course(show_correctness=show_correctness, due_date=due_date, graded=graded) self.add_problem() # Login as a course staff user to view the student progress page. self.client.login(username=self.staff_user.username, password='test') resp = self._get_student_progress_page() # Ensure that expected text is present self.assert_progress_page_show_grades(resp, show_correctness, due_date, graded, show_grades, 0, 1, 0) # Submit answers to the problem, and re-fetch the progress page self.answer_problem() resp = self._get_student_progress_page() # Test that the expected text is still present. self.assert_progress_page_show_grades(resp, show_correctness, due_date, graded, show_grades, 1, 1, .5) class VerifyCourseKeyDecoratorTests(TestCase): """ Tests for the ensure_valid_course_key decorator. """ def setUp(self): super(VerifyCourseKeyDecoratorTests, self).setUp() self.request = RequestFactoryNoCsrf().get("foo") self.valid_course_id = "edX/test/1" self.invalid_course_id = "edX/" def test_decorator_with_valid_course_id(self): mocked_view = create_autospec(views.course_about) view_function = ensure_valid_course_key(mocked_view) view_function(self.request, course_id=self.valid_course_id) self.assertTrue(mocked_view.called) def test_decorator_with_invalid_course_id(self): mocked_view = create_autospec(views.course_about) view_function = ensure_valid_course_key(mocked_view) self.assertRaises(Http404, view_function, self.request, course_id=self.invalid_course_id) self.assertFalse(mocked_view.called) class GenerateUserCertTests(ModuleStoreTestCase): """ Tests for the view function Generated User Certs """ def setUp(self): super(GenerateUserCertTests, self).setUp() self.student = UserFactory() self.course = CourseFactory.create( org='edx', number='verified', end=datetime.now(), display_name='Verified Course', grade_cutoffs={'cutoff': 0.75, 'Pass': 0.5}, self_paced=True ) self.enrollment = CourseEnrollment.enroll(self.student, self.course.id, mode='honor') self.assertTrue(self.client.login(username=self.student, password=TEST_PASSWORD)) self.url = reverse('generate_user_cert', kwargs={'course_id': six.text_type(self.course.id)}) def test_user_with_out_passing_grades(self): # If user has no grading then json will return failed message and badrequest code resp = self.client.post(self.url) self.assertContains( resp, "Your certificate will be available when you pass the course.", status_code=HttpResponseBadRequest.status_code, ) @patch('lms.djangoapps.courseware.views.views.is_course_passed', return_value=True) @override_settings(CERT_QUEUE='certificates', LMS_SEGMENT_KEY="foobar") def test_user_with_passing_grade(self, mock_is_course_passed): # If user has above passing grading then json will return cert generating message and # status valid code # mocking xqueue and Segment analytics analytics_patcher = patch('lms.djangoapps.courseware.views.views.segment') mock_tracker = analytics_patcher.start() self.addCleanup(analytics_patcher.stop) with patch('capa.xqueue_interface.XQueueInterface.send_to_queue') as mock_send_to_queue: mock_send_to_queue.return_value = (0, "Successfully queued") resp = self.client.post(self.url) self.assertEqual(resp.status_code, 200) # Verify Google Analytics event fired after generating certificate mock_tracker.track.assert_called_once_with( self.student.id, 'edx.bi.user.certificate.generate', { 'category': 'certificates', 'label': six.text_type(self.course.id) }, ) mock_tracker.reset_mock() def test_user_with_passing_existing_generating_cert(self): # If user has passing grade but also has existing generating cert # then json will return cert generating message with bad request code GeneratedCertificateFactory.create( user=self.student, course_id=self.course.id, status=CertificateStatuses.generating, mode='verified' ) with patch('lms.djangoapps.grades.course_grade_factory.CourseGradeFactory.read') as mock_create: course_grade = mock_create.return_value course_grade.passed = True course_grade.summary = {'grade': 'Pass', 'percent': 0.75} resp = self.client.post(self.url) self.assertContains(resp, "Certificate is being created.", status_code=HttpResponseBadRequest.status_code) @override_settings(CERT_QUEUE='certificates', LMS_SEGMENT_KEY="foobar") def test_user_with_passing_existing_downloadable_cert(self): # If user has already downloadable certificate # then json will return cert generating message with bad request code GeneratedCertificateFactory.create( user=self.student, course_id=self.course.id, status=CertificateStatuses.downloadable, mode='verified' ) with patch('lms.djangoapps.grades.course_grade_factory.CourseGradeFactory.read') as mock_create: course_grade = mock_create.return_value course_grade.passed = True course_grade.summay = {'grade': 'Pass', 'percent': 0.75} resp = self.client.post(self.url) self.assertContains( resp, "Certificate has already been created.", status_code=HttpResponseBadRequest.status_code, ) def test_user_with_non_existing_course(self): # If try to access a course with valid key pattern then it will return # bad request code with course is not valid message resp = self.client.post('/courses/def/abc/in_valid/generate_user_cert') self.assertContains(resp, "Course is not valid", status_code=HttpResponseBadRequest.status_code) def test_user_with_invalid_course_id(self): # If try to access a course with invalid key pattern then 404 will return resp = self.client.post('/courses/def/generate_user_cert') self.assertEqual(resp.status_code, 404) def test_user_without_login_return_error(self): # If user try to access without login should see a bad request status code with message self.client.logout() resp = self.client.post(self.url) self.assertContains( resp, u"You must be signed in to {platform_name} to create a certificate.".format( platform_name=settings.PLATFORM_NAME ), status_code=HttpResponseBadRequest.status_code, ) class ActivateIDCheckerBlock(XBlock): """ XBlock for checking for an activate_block_id entry in the render context. """ # We don't need actual children to test this. has_children = False def student_view(self, context): """ A student view that displays the activate_block_id context variable. """ result = Fragment() if 'activate_block_id' in context: result.add_content(u"Activate Block ID: {block_id}</p>".format(block_id=context['activate_block_id'])) return result class ViewCheckerBlock(XBlock): """ XBlock for testing user state in views. """ has_children = True state = String(scope=Scope.user_state) position = 0 def student_view(self, context): # pylint: disable=unused-argument """ A student_view that asserts that the ``state`` field for this block matches the block's usage_id. """ msg = u"{} != {}".format(self.state, self.scope_ids.usage_id) assert self.state == six.text_type(self.scope_ids.usage_id), msg fragments = self.runtime.render_children(self) result = Fragment( content=u"<p>ViewCheckerPassed: {}</p>\n{}".format( six.text_type(self.scope_ids.usage_id), "\n".join(fragment.content for fragment in fragments), ) ) return result @ddt.ddt class TestIndexView(ModuleStoreTestCase): """ Tests of the courseware.views.index view. """ @XBlock.register_temp_plugin(ViewCheckerBlock, 'view_checker') @ddt.data(ModuleStoreEnum.Type.mongo, ModuleStoreEnum.Type.split) def test_student_state(self, default_store): """ Verify that saved student state is loaded for xblocks rendered in the index view. """ user = UserFactory() with modulestore().default_store(default_store): course = CourseFactory.create() chapter = ItemFactory.create(parent=course, category='chapter') section = ItemFactory.create(parent=chapter, category='view_checker', display_name="Sequence Checker") vertical = ItemFactory.create(parent=section, category='view_checker', display_name="Vertical Checker") block = ItemFactory.create(parent=vertical, category='view_checker', display_name="Block Checker") for item in (section, vertical, block): StudentModuleFactory.create( student=user, course_id=course.id, module_state_key=item.scope_ids.usage_id, state=json.dumps({'state': six.text_type(item.scope_ids.usage_id)}) ) CourseOverview.load_from_module_store(course.id) CourseEnrollmentFactory(user=user, course_id=course.id) self.assertTrue(self.client.login(username=user.username, password='test')) response = self.client.get( reverse( 'courseware_section', kwargs={ 'course_id': six.text_type(course.id), 'chapter': chapter.url_name, 'section': section.url_name, } ) ) # Trigger the assertions embedded in the ViewCheckerBlocks self.assertContains(response, "ViewCheckerPassed", count=3) @XBlock.register_temp_plugin(ActivateIDCheckerBlock, 'id_checker') def test_activate_block_id(self): user = UserFactory() course = CourseFactory.create() with self.store.bulk_operations(course.id): chapter = ItemFactory.create(parent=course, category='chapter') section = ItemFactory.create(parent=chapter, category='sequential', display_name="Sequence") vertical = ItemFactory.create(parent=section, category='vertical', display_name="Vertical") ItemFactory.create(parent=vertical, category='id_checker', display_name="ID Checker") CourseOverview.load_from_module_store(course.id) CourseEnrollmentFactory(user=user, course_id=course.id) self.assertTrue(self.client.login(username=user.username, password='test')) response = self.client.get( reverse( 'courseware_section', kwargs={ 'course_id': six.text_type(course.id), 'chapter': chapter.url_name, 'section': section.url_name, } ) + '?activate_block_id=test_block_id' ) self.assertContains(response, "Activate Block ID: test_block_id") @ddt.data( [False, COURSE_VISIBILITY_PRIVATE, CourseUserType.ANONYMOUS, False], [False, COURSE_VISIBILITY_PUBLIC_OUTLINE, CourseUserType.ANONYMOUS, False], [False, COURSE_VISIBILITY_PUBLIC, CourseUserType.ANONYMOUS, False], [True, COURSE_VISIBILITY_PRIVATE, CourseUserType.ANONYMOUS, False], [True, COURSE_VISIBILITY_PUBLIC_OUTLINE, CourseUserType.ANONYMOUS, False], [True, COURSE_VISIBILITY_PUBLIC, CourseUserType.ANONYMOUS, True], [False, COURSE_VISIBILITY_PRIVATE, CourseUserType.UNENROLLED, False], [False, COURSE_VISIBILITY_PUBLIC_OUTLINE, CourseUserType.UNENROLLED, False], [False, COURSE_VISIBILITY_PUBLIC, CourseUserType.UNENROLLED, False], [True, COURSE_VISIBILITY_PRIVATE, CourseUserType.UNENROLLED, False], [True, COURSE_VISIBILITY_PUBLIC_OUTLINE, CourseUserType.UNENROLLED, False], [True, COURSE_VISIBILITY_PUBLIC, CourseUserType.UNENROLLED, True], [False, COURSE_VISIBILITY_PRIVATE, CourseUserType.ENROLLED, True], [True, COURSE_VISIBILITY_PRIVATE, CourseUserType.ENROLLED, True], [True, COURSE_VISIBILITY_PUBLIC_OUTLINE, CourseUserType.ENROLLED, True], [True, COURSE_VISIBILITY_PUBLIC, CourseUserType.ENROLLED, True], [False, COURSE_VISIBILITY_PRIVATE, CourseUserType.UNENROLLED_STAFF, True], [True, COURSE_VISIBILITY_PRIVATE, CourseUserType.UNENROLLED_STAFF, True], [True, COURSE_VISIBILITY_PUBLIC_OUTLINE, CourseUserType.UNENROLLED_STAFF, True], [True, COURSE_VISIBILITY_PUBLIC, CourseUserType.UNENROLLED_STAFF, True], [False, COURSE_VISIBILITY_PRIVATE, CourseUserType.GLOBAL_STAFF, True], [True, COURSE_VISIBILITY_PRIVATE, CourseUserType.GLOBAL_STAFF, True], [True, COURSE_VISIBILITY_PUBLIC_OUTLINE, CourseUserType.GLOBAL_STAFF, True], [True, COURSE_VISIBILITY_PUBLIC, CourseUserType.GLOBAL_STAFF, True], ) @ddt.unpack def test_courseware_access(self, waffle_override, course_visibility, user_type, expected_course_content): course = CourseFactory(course_visibility=course_visibility) with self.store.bulk_operations(course.id): chapter = ItemFactory(parent=course, category='chapter') section = ItemFactory(parent=chapter, category='sequential') vertical = ItemFactory.create(parent=section, category='vertical', display_name="Vertical") ItemFactory.create(parent=vertical, category='html', display_name='HTML block') ItemFactory.create(parent=vertical, category='video', display_name='Video') self.create_user_for_course(course, user_type) url = reverse( 'courseware_section', kwargs={ 'course_id': str(course.id), 'chapter': chapter.url_name, 'section': section.url_name, } ) with override_waffle_flag(COURSE_ENABLE_UNENROLLED_ACCESS_FLAG, active=waffle_override): response = self.client.get(url, follow=False) assert response.status_code == (200 if expected_course_content else 302) unicode_content = response.content.decode('utf-8') if expected_course_content: if user_type in (CourseUserType.ANONYMOUS, CourseUserType.UNENROLLED): self.assertIn('data-save-position="false"', unicode_content) self.assertIn('data-show-completion="false"', unicode_content) self.assertIn('xblock-public_view-sequential', unicode_content) self.assertIn('xblock-public_view-vertical', unicode_content) self.assertIn('xblock-public_view-html', unicode_content) self.assertIn('xblock-public_view-video', unicode_content) if user_type == CourseUserType.ANONYMOUS and course_visibility == COURSE_VISIBILITY_PRIVATE: self.assertIn('To see course content', unicode_content) if user_type == CourseUserType.UNENROLLED and course_visibility == COURSE_VISIBILITY_PRIVATE: self.assertIn('You must be enrolled', unicode_content) else: self.assertIn('data-save-position="true"', unicode_content) self.assertIn('data-show-completion="true"', unicode_content) self.assertIn('xblock-student_view-sequential', unicode_content) self.assertIn('xblock-student_view-vertical', unicode_content) self.assertIn('xblock-student_view-html', unicode_content) self.assertIn('xblock-student_view-video', unicode_content) @patch('lms.djangoapps.courseware.views.views.CourseTabView.course_open_for_learner_enrollment') @patch('openedx.core.djangoapps.util.user_messages.PageLevelMessages.register_warning_message') def test_courseware_messages_differentiate_for_anonymous_users( self, patch_register_warning_message, patch_course_open_for_learner_enrollment ): """ Tests that the anonymous user case for the register_user_access_warning_messages returns different messaging based on the possibility of enrollment """ course = CourseFactory() user = self.create_user_for_course(course, CourseUserType.ANONYMOUS) request = RequestFactory().get('/') request.user = user patch_course_open_for_learner_enrollment.return_value = False views.CourseTabView.register_user_access_warning_messages(request, course) open_for_enrollment_message = patch_register_warning_message.mock_calls[0][1][1] patch_register_warning_message.reset_mock() patch_course_open_for_learner_enrollment.return_value = True views.CourseTabView.register_user_access_warning_messages(request, course) closed_to_enrollment_message = patch_register_warning_message.mock_calls[0][1][1] assert open_for_enrollment_message != closed_to_enrollment_message @patch('openedx.core.djangoapps.util.user_messages.PageLevelMessages.register_warning_message') def test_courseware_messages_masters_only(self, patch_register_warning_message): with patch( 'lms.djangoapps.courseware.views.views.CourseTabView.course_open_for_learner_enrollment' ) as patch_course_open_for_learner_enrollment: course = CourseFactory() user = self.create_user_for_course(course, CourseUserType.UNENROLLED) request = RequestFactory().get('/') request.user = user button_html = '<button class="enroll-btn btn-link">Enroll now</button>' patch_course_open_for_learner_enrollment.return_value = False views.CourseTabView.register_user_access_warning_messages(request, course) # pull message out of the calls to the mock so that # we can make finer grained assertions than mock provides message = patch_register_warning_message.mock_calls[0][1][1] assert button_html not in message patch_register_warning_message.reset_mock() patch_course_open_for_learner_enrollment.return_value = True views.CourseTabView.register_user_access_warning_messages(request, course) # pull message out of the calls to the mock so that # we can make finer grained assertions than mock provides message = patch_register_warning_message.mock_calls[0][1][1] assert button_html in message @ddt.data( [True, True, True, False, ], [False, True, True, False, ], [True, False, True, False, ], [True, True, False, False, ], [False, False, True, False, ], [True, False, False, True, ], [False, True, False, False, ], [False, False, False, False, ], ) @ddt.unpack def test_should_show_enroll_button(self, course_open_for_self_enrollment, invitation_only, is_masters_only, expected_should_show_enroll_button): with patch('lms.djangoapps.courseware.views.views.course_open_for_self_enrollment') \ as patch_course_open_for_self_enrollment, \ patch('course_modes.models.CourseMode.is_masters_only') as patch_is_masters_only: course = CourseFactory() patch_course_open_for_self_enrollment.return_value = course_open_for_self_enrollment patch_is_masters_only.return_value = is_masters_only course.invitation_only = invitation_only self.assertEqual( views.CourseTabView.course_open_for_learner_enrollment(course), expected_should_show_enroll_button ) @ddt.ddt class TestIndexViewCompleteOnView(ModuleStoreTestCase, CompletionWaffleTestMixin): """ Tests CompleteOnView is set up correctly in CoursewareIndex. """ def setup_course(self, default_store): """ Set up course content for modulestore. """ # pylint:disable=attribute-defined-outside-init self.request_factory = RequestFactoryNoCsrf() self.user = UserFactory() with modulestore().default_store(default_store): self.course = CourseFactory.create() with self.store.bulk_operations(self.course.id): self.chapter = ItemFactory.create( parent_location=self.course.location, category='chapter', display_name='Week 1' ) self.section_1 = ItemFactory.create( parent_location=self.chapter.location, category='sequential', display_name='Lesson 1' ) self.vertical_1 = ItemFactory.create( parent_location=self.section_1.location, category='vertical', display_name='Subsection 1' ) self.html_1_1 = ItemFactory.create( parent_location=self.vertical_1.location, category='html', display_name="HTML 1_1" ) self.problem_1 = ItemFactory.create( parent_location=self.vertical_1.location, category='problem', display_name="Problem 1" ) self.html_1_2 = ItemFactory.create( parent_location=self.vertical_1.location, category='html', display_name="HTML 1_2" ) self.section_2 = ItemFactory.create( parent_location=self.chapter.location, category='sequential', display_name='Lesson 2' ) self.vertical_2 = ItemFactory.create( parent_location=self.section_2.location, category='vertical', display_name='Subsection 2' ) self.video_2 = ItemFactory.create( parent_location=self.vertical_2.location, category='video', display_name="Video 2" ) self.problem_2 = ItemFactory.create( parent_location=self.vertical_2.location, category='problem', display_name="Problem 2" ) self.section_1_url = reverse( 'courseware_section', kwargs={ 'course_id': six.text_type(self.course.id), 'chapter': self.chapter.url_name, 'section': self.section_1.url_name, } ) self.section_2_url = reverse( 'courseware_section', kwargs={ 'course_id': six.text_type(self.course.id), 'chapter': self.chapter.url_name, 'section': self.section_2.url_name, } ) CourseOverview.load_from_module_store(self.course.id) CourseEnrollmentFactory(user=self.user, course_id=self.course.id) @ddt.data(ModuleStoreEnum.Type.mongo, ModuleStoreEnum.Type.split) def test_completion_service_disabled(self, default_store): self.setup_course(default_store) self.assertTrue(self.client.login(username=self.user.username, password='test')) response = self.client.get(self.section_1_url) self.assertNotContains(response, 'data-mark-completed-on-view-after-delay') response = self.client.get(self.section_2_url) self.assertNotContains(response, 'data-mark-completed-on-view-after-delay') @ddt.data(ModuleStoreEnum.Type.mongo, ModuleStoreEnum.Type.split) def test_completion_service_enabled(self, default_store): self.override_waffle_switch(True) self.setup_course(default_store) self.assertTrue(self.client.login(username=self.user.username, password='test')) response = self.client.get(self.section_1_url) self.assertContains(response, 'data-mark-completed-on-view-after-delay') self.assertContains(response, 'data-mark-completed-on-view-after-delay', count=2) request = self.request_factory.post( '/', data=json.dumps({"completion": 1}), content_type='application/json', ) request.user = self.user response = handle_xblock_callback( request, six.text_type(self.course.id), quote_slashes(six.text_type(self.html_1_1.scope_ids.usage_id)), 'publish_completion', ) self.assertEqual(json.loads(response.content.decode('utf-8')), {'result': "ok"}) response = self.client.get(self.section_1_url) self.assertContains(response, 'data-mark-completed-on-view-after-delay') self.assertContains(response, 'data-mark-completed-on-view-after-delay', count=1) request = self.request_factory.post( '/', data=json.dumps({"completion": 1}), content_type='application/json', ) request.user = self.user response = handle_xblock_callback( request, six.text_type(self.course.id), quote_slashes(six.text_type(self.html_1_2.scope_ids.usage_id)), 'publish_completion', ) self.assertEqual(json.loads(response.content.decode('utf-8')), {'result': "ok"}) response = self.client.get(self.section_1_url) self.assertNotContains(response, 'data-mark-completed-on-view-after-delay') response = self.client.get(self.section_2_url) self.assertNotContains(response, 'data-mark-completed-on-view-after-delay') @ddt.ddt class TestIndexViewWithVerticalPositions(ModuleStoreTestCase): """ Test the index view to handle vertical positions. Confirms that first position is loaded if input position is non-positive or greater than number of positions available. """ def setUp(self): """ Set up initial test data """ super(TestIndexViewWithVerticalPositions, self).setUp() self.user = UserFactory() # create course with 3 positions self.course = CourseFactory.create() with self.store.bulk_operations(self.course.id): self.chapter = ItemFactory.create(parent=self.course, category='chapter') self.section = ItemFactory.create(parent=self.chapter, category='sequential', display_name="Sequence") ItemFactory.create(parent=self.section, category='vertical', display_name="Vertical1") ItemFactory.create(parent=self.section, category='vertical', display_name="Vertical2") ItemFactory.create(parent=self.section, category='vertical', display_name="Vertical3") CourseOverview.load_from_module_store(self.course.id) self.client.login(username=self.user, password='test') CourseEnrollmentFactory(user=self.user, course_id=self.course.id) def _get_course_vertical_by_position(self, input_position): """ Returns client response to input position. """ return self.client.get( reverse( 'courseware_position', kwargs={ 'course_id': six.text_type(self.course.id), 'chapter': self.chapter.url_name, 'section': self.section.url_name, 'position': input_position, } ) ) def _assert_correct_position(self, response, expected_position): """ Asserts that the expected position and the position in the response are the same """ self.assertContains(response, 'data-position="{}"'.format(expected_position)) @ddt.data(("-1", 1), ("0", 1), ("-0", 1), ("2", 2), ("5", 1)) @ddt.unpack def test_vertical_positions(self, input_position, expected_position): """ Tests the following cases: * Load first position when negative position inputted. * Load first position when 0/-0 position inputted. * Load given position when 0 < input_position <= num_positions_available. * Load first position when positive position > num_positions_available. """ resp = self._get_course_vertical_by_position(input_position) self._assert_correct_position(resp, expected_position) class TestIndexViewWithGating(ModuleStoreTestCase, MilestonesTestCaseMixin): """ Test the index view for a course with gated content """ def setUp(self): """ Set up the initial test data """ super(TestIndexViewWithGating, self).setUp() self.user = UserFactory() self.course = CourseFactory.create() with self.store.bulk_operations(self.course.id): self.course.enable_subsection_gating = True self.course.save() self.store.update_item(self.course, 0) self.chapter = ItemFactory.create(parent=self.course, category="chapter", display_name="Chapter") self.open_seq = ItemFactory.create( parent=self.chapter, category='sequential', display_name="Open Sequential" ) ItemFactory.create(parent=self.open_seq, category='problem', display_name="Problem 1") self.gated_seq = ItemFactory.create( parent=self.chapter, category='sequential', display_name="Gated Sequential" ) ItemFactory.create(parent=self.gated_seq, category='problem', display_name="Problem 2") gating_api.add_prerequisite(self.course.id, self.open_seq.location) gating_api.set_required_content(self.course.id, self.gated_seq.location, self.open_seq.location, 100) CourseEnrollmentFactory(user=self.user, course_id=self.course.id) def test_index_with_gated_sequential(self): """ Test index view with a gated sequential raises Http404 """ self.assertTrue(self.client.login(username=self.user.username, password='test')) response = self.client.get( reverse( 'courseware_section', kwargs={ 'course_id': six.text_type(self.course.id), 'chapter': self.chapter.url_name, 'section': self.gated_seq.url_name, } ) ) self.assertEqual(response.status_code, 200) self.assertContains(response, "Content Locked") class TestIndexViewWithCourseDurationLimits(ModuleStoreTestCase): """ Test the index view for a course with course duration limits enabled. """ def setUp(self): """ Set up the initial test data. """ super(TestIndexViewWithCourseDurationLimits, self).setUp() self.user = UserFactory() self.course = CourseFactory.create(start=datetime.now() - timedelta(weeks=1)) with self.store.bulk_operations(self.course.id): self.chapter = ItemFactory.create(parent=self.course, category="chapter") self.sequential = ItemFactory.create(parent=self.chapter, category='sequential') self.vertical = ItemFactory.create(parent=self.sequential, category="vertical") CourseEnrollmentFactory(user=self.user, course_id=self.course.id) def test_index_with_course_duration_limits(self): """ Test that the courseware contains the course expiration banner when course_duration_limits are enabled. """ CourseDurationLimitConfig.objects.create(enabled=True, enabled_as_of=datetime(2018, 1, 1)) self.assertTrue(self.client.login(username=self.user.username, password='test')) add_course_mode(self.course, upgrade_deadline_expired=False) response = self.client.get( reverse( 'courseware_section', kwargs={ 'course_id': six.text_type(self.course.id), 'chapter': self.chapter.url_name, 'section': self.sequential.url_name, } ) ) bannerText = get_expiration_banner_text(self.user, self.course) # Banner is XBlock wrapper, so it is escaped in raw response. Since # it's escaped, ignoring the whitespace with assertContains doesn't # work. Instead we remove all whitespace to verify content is correct. bannerText_no_spaces = escape(bannerText).replace(' ', '') response_no_spaces = response.content.decode('utf-8').replace(' ', '') self.assertIn(bannerText_no_spaces, response_no_spaces) def test_index_without_course_duration_limits(self): """ Test that the courseware does not contain the course expiration banner when course_duration_limits are disabled. """ CourseDurationLimitConfig.objects.create(enabled=False) self.assertTrue(self.client.login(username=self.user.username, password='test')) add_course_mode(self.course, upgrade_deadline_expired=False) response = self.client.get( reverse( 'courseware_section', kwargs={ 'course_id': six.text_type(self.course.id), 'chapter': self.chapter.url_name, 'section': self.sequential.url_name, } ) ) bannerText = get_expiration_banner_text(self.user, self.course) self.assertNotContains(response, bannerText, html=True) class TestRenderXBlock(RenderXBlockTestMixin, ModuleStoreTestCase, CompletionWaffleTestMixin): """ Tests for the courseware.render_xblock endpoint. This class overrides the get_response method, which is used by the tests defined in RenderXBlockTestMixin. """ def setUp(self): reload_django_url_config() super(TestRenderXBlock, self).setUp() def test_render_xblock_with_invalid_usage_key(self): """ Test XBlockRendering with invalid usage key """ response = self.get_response(usage_key='some_invalid_usage_key') self.assertContains(response, 'Page not found', status_code=404) def get_response(self, usage_key, url_encoded_params=None): """ Overridable method to get the response from the endpoint that is being tested. """ url = reverse('render_xblock', kwargs={'usage_key_string': six.text_type(usage_key)}) if url_encoded_params: url += '?' + url_encoded_params return self.client.get(url) def test_render_xblock_with_completion_service_disabled(self): """ Test that render_xblock does not set up the CompletionOnViewService. """ self.setup_course(ModuleStoreEnum.Type.split) self.setup_user(admin=True, enroll=True, login=True) response = self.get_response(usage_key=self.html_block.location) self.assertEqual(response.status_code, 200) self.assertContains(response, 'data-enable-completion-on-view-service="false"') self.assertNotContains(response, 'data-mark-completed-on-view-after-delay') def test_render_xblock_with_completion_service_enabled(self): """ Test that render_xblock sets up the CompletionOnViewService for relevant xblocks. """ self.override_waffle_switch(True) self.setup_course(ModuleStoreEnum.Type.split) self.setup_user(admin=False, enroll=True, login=True) response = self.get_response(usage_key=self.html_block.location) self.assertEqual(response.status_code, 200) self.assertContains(response, 'data-enable-completion-on-view-service="true"') self.assertContains(response, 'data-mark-completed-on-view-after-delay') request = RequestFactoryNoCsrf().post( '/', data=json.dumps({"completion": 1}), content_type='application/json', ) request.user = self.user response = handle_xblock_callback( request, six.text_type(self.course.id), quote_slashes(six.text_type(self.html_block.location)), 'publish_completion', ) self.assertEqual(response.status_code, 200) self.assertEqual(json.loads(response.content.decode('utf-8')), {'result': "ok"}) response = self.get_response(usage_key=self.html_block.location) self.assertEqual(response.status_code, 200) self.assertContains(response, 'data-enable-completion-on-view-service="false"') self.assertNotContains(response, 'data-mark-completed-on-view-after-delay') response = self.get_response(usage_key=self.problem_block.location) self.assertEqual(response.status_code, 200) self.assertContains(response, 'data-enable-completion-on-view-service="false"') self.assertNotContains(response, 'data-mark-completed-on-view-after-delay') class TestRenderXBlockSelfPaced(TestRenderXBlock): """ Test rendering XBlocks for a self-paced course. Relies on the query count assertions in the tests defined by RenderXBlockMixin. """ def setUp(self): super(TestRenderXBlockSelfPaced, self).setUp() def course_options(self): options = super(TestRenderXBlockSelfPaced, self).course_options() options['self_paced'] = True return options class TestIndexViewCrawlerStudentStateWrites(SharedModuleStoreTestCase): """ Ensure that courseware index requests do not trigger student state writes. This is to prevent locking issues that have caused latency spikes in the courseware_studentmodule table when concurrent requests each try to update the same rows for sequence, section, and course positions. """ @classmethod def setUpClass(cls): """Set up the simplest course possible.""" # setUpClassAndTestData() already calls setUpClass on SharedModuleStoreTestCase # pylint: disable=super-method-not-called with super(TestIndexViewCrawlerStudentStateWrites, cls).setUpClassAndTestData(): cls.course = CourseFactory.create() with cls.store.bulk_operations(cls.course.id): cls.chapter = ItemFactory.create(category='chapter', parent_location=cls.course.location) cls.section = ItemFactory.create(category='sequential', parent_location=cls.chapter.location) cls.vertical = ItemFactory.create(category='vertical', parent_location=cls.section.location) @classmethod def setUpTestData(cls): """Set up and enroll our fake user in the course.""" cls.user = UserFactory() CourseEnrollment.enroll(cls.user, cls.course.id) def setUp(self): """Do the client login.""" super(TestIndexViewCrawlerStudentStateWrites, self).setUp() self.client.login(username=self.user.username, password=TEST_PASSWORD) def test_write_by_default(self): """By default, always write student state, regardless of user agent.""" with patch('lms.djangoapps.courseware.model_data.UserStateCache.set_many') as patched_state_client_set_many: # Simulate someone using Chrome self._load_courseware('Mozilla/5.0 AppleWebKit/537.36') self.assertTrue(patched_state_client_set_many.called) patched_state_client_set_many.reset_mock() # Common crawler user agent self._load_courseware('edX-downloader/0.1') self.assertTrue(patched_state_client_set_many.called) def test_writes_with_config(self): """Test state writes (or lack thereof) based on config values.""" CrawlersConfig.objects.create(known_user_agents='edX-downloader,crawler_foo', enabled=True) with patch('lms.djangoapps.courseware.model_data.UserStateCache.set_many') as patched_state_client_set_many: # Exact matching of crawler user agent self._load_courseware('crawler_foo') self.assertFalse(patched_state_client_set_many.called) # Partial matching of crawler user agent self._load_courseware('edX-downloader/0.1') self.assertFalse(patched_state_client_set_many.called) # Simulate an actual browser hitting it (we should write) self._load_courseware('Mozilla/5.0 AppleWebKit/537.36') self.assertTrue(patched_state_client_set_many.called) # Disabling the crawlers config should revert us to default behavior CrawlersConfig.objects.create(enabled=False) self.test_write_by_default() def _load_courseware(self, user_agent): """Helper to load the actual courseware page.""" url = reverse( 'courseware_section', kwargs={ 'course_id': six.text_type(self.course.id), 'chapter': six.text_type(self.chapter.location.block_id), 'section': six.text_type(self.section.location.block_id), } ) response = self.client.get(url, HTTP_USER_AGENT=user_agent) # Make sure we get back an actual 200, and aren't redirected because we # messed up the setup somehow (e.g. didn't enroll properly) self.assertEqual(response.status_code, 200) class EnterpriseConsentTestCase(EnterpriseTestConsentRequired, ModuleStoreTestCase): """ Ensure that the Enterprise Data Consent redirects are in place only when consent is required. """ def setUp(self): super(EnterpriseConsentTestCase, self).setUp() self.user = UserFactory.create() self.assertTrue(self.client.login(username=self.user.username, password='test')) self.course = CourseFactory.create() CourseOverview.load_from_module_store(self.course.id) CourseEnrollmentFactory(user=self.user, course_id=self.course.id) @patch('openedx.features.enterprise_support.api.enterprise_customer_for_request') def test_consent_required(self, mock_enterprise_customer_for_request): """ Test that enterprise data sharing consent is required when enabled for the various courseware views. """ # ENT-924: Temporary solution to replace sensitive SSO usernames. mock_enterprise_customer_for_request.return_value = None course_id = six.text_type(self.course.id) for url in ( reverse("courseware", kwargs=dict(course_id=course_id)), reverse("progress", kwargs=dict(course_id=course_id)), reverse("student_progress", kwargs=dict(course_id=course_id, student_id=str(self.user.id))), ): self.verify_consent_required(self.client, url) @ddt.ddt class AccessUtilsTestCase(ModuleStoreTestCase): """ Test access utilities """ @ddt.data( (1, False), (-1, True) ) @ddt.unpack @patch.dict('django.conf.settings.FEATURES', {'DISABLE_START_DATES': False}) def test_is_course_open_for_learner(self, start_date_modifier, expected_value): staff_user = AdminFactory() start_date = datetime.now(UTC) + timedelta(days=start_date_modifier) course = CourseFactory.create(start=start_date) self.assertEqual(bool(check_course_open_for_learner(staff_user, course)), expected_value) @ddt.ddt class DatesTabTestCase(ModuleStoreTestCase): """ Ensure that the dates page renders with the correct data for both a verified and audit learner """ def setUp(self): super(DatesTabTestCase, self).setUp() self.user = UserFactory.create() now = datetime.now(utc) self.course = CourseFactory.create(start=now + timedelta(days=-1)) self.course.end = now + timedelta(days=3) CourseModeFactory(course_id=self.course.id, mode_slug=CourseMode.AUDIT) CourseModeFactory( course_id=self.course.id, mode_slug=CourseMode.VERIFIED, expiration_datetime=now + timedelta(days=1) ) VerificationDeadline.objects.create( course_key=self.course.id, deadline=now + timedelta(days=2) ) def _get_response(self, course): """ Returns the HTML for the progress page """ return self.client.get(reverse('dates', args=[six.text_type(course.id)])) @RELATIVE_DATES_FLAG.override(active=True) def test_defaults(self): request = RequestFactory().request() request.user = self.user self.addCleanup(crum.set_current_request, None) crum.set_current_request(request) enrollment = CourseEnrollmentFactory(course_id=self.course.id, user=self.user, mode=CourseMode.VERIFIED) now = datetime.now(utc) with self.store.bulk_operations(self.course.id): section = ItemFactory.create(category='chapter', parent_location=self.course.location) subsection = ItemFactory.create( category='sequential', display_name='Released', parent_location=section.location, start=now - timedelta(days=1), due=now, # Setting this today so it'll show the 'Due Today' pill graded=True, ) with patch('lms.djangoapps.courseware.courses.get_dates_for_course') as mock_get_dates: with patch('lms.djangoapps.courseware.views.views.get_enrollment') as mock_get_enrollment: mock_get_dates.return_value = { (subsection.location, 'due'): subsection.due, (subsection.location, 'start'): subsection.start, } mock_get_enrollment.return_value = { 'mode': enrollment.mode } response = self._get_response(self.course) self.assertContains(response, subsection.display_name) # Show the Verification Deadline for everyone self.assertContains(response, 'Verification Deadline') # Make sure pill exists for assignment due today self.assertContains(response, '<div class="pill due">') # No pills for verified enrollments self.assertNotContains(response, '<div class="pill verified">') enrollment.delete() subsection.due = now + timedelta(days=1) enrollment = CourseEnrollmentFactory(course_id=self.course.id, user=self.user, mode=CourseMode.AUDIT) mock_get_dates.return_value = { (subsection.location, 'due'): subsection.due, (subsection.location, 'start'): subsection.start, } mock_get_enrollment.return_value = { 'mode': enrollment.mode } response = self._get_response(self.course) self.assertContains(response, subsection.display_name) # Show the Verification Deadline for everyone self.assertContains(response, 'Verification Deadline') # Pill doesn't exist for assignment due tomorrow self.assertNotContains(response, '<div class="pill due">') # Should have verified pills for audit enrollments self.assertContains(response, '<div class="pill verified">') class TestShowCoursewareMFE(TestCase): """ Make sure we're showing the Courseware MFE link when appropriate. There are an unfortunate number of state permutations here since we have the product of the following binary states: * the ENABLE_COURSEWARE_MICROFRONTEND Django setting * user is global staff member * user is member of the course team * whether the course_key is an old Mongo style of key * the COURSEWARE_MICROFRONTEND_COURSE_TEAM_PREVIEW CourseWaffleFlag * the REDIRECT_TO_COURSEWARE_MICROFRONTEND CourseWaffleFlag Giving us theoretically 2^6 = 64 states. >_< """ @patch.dict(settings.FEATURES, {'ENABLE_COURSEWARE_MICROFRONTEND': False}) def test_disabled_at_platform_level(self): """Test every permutation where the platform feature is disabled.""" old_course_key = CourseKey.from_string("OpenEdX/Old/2020") new_course_key = CourseKey.from_string("course-v1:OpenEdX+New+2020") global_staff_user = UserFactory(username="global_staff", is_staff=True) regular_user = UserFactory(username="normal", is_staff=False) # We never show when the feature is entirely disabled, no matter what # the waffle flags are set to, who the user is, or what the course_key # type is. combos = itertools.product( [regular_user, global_staff_user], # User (is global staff) [old_course_key, new_course_key], # Course Key (old vs. new) [True, False], # is_course_staff [True, False], # preview_active (COURSEWARE_MICROFRONTEND_COURSE_TEAM_PREVIEW) [True, False], # redirect_active (REDIRECT_TO_COURSEWARE_MICROFRONTEND) ) for user, course_key, is_course_staff, preview_active, redirect_active in combos: with override_waffle_flag(COURSEWARE_MICROFRONTEND_COURSE_TEAM_PREVIEW, preview_active): with override_waffle_flag(REDIRECT_TO_COURSEWARE_MICROFRONTEND, redirect_active): assert show_courseware_mfe_link(user, is_course_staff, course_key) is False @patch.dict(settings.FEATURES, {'ENABLE_COURSEWARE_MICROFRONTEND': True}) def test_enabled_at_platform_level(self): """Test every permutation where the platform feature is enabled.""" old_course_key = CourseKey.from_string("OpenEdX/Old/2020") new_course_key = CourseKey.from_string("course-v1:OpenEdX+New+2020") global_staff_user = UserFactory(username="global_staff", is_staff=True) regular_user = UserFactory(username="normal", is_staff=False) # Old style course keys are never supported and should always return false... old_mongo_combos = itertools.product( [regular_user, global_staff_user], # User (is global staff) [True, False], # is_course_staff [True, False], # preview_active (COURSEWARE_MICROFRONTEND_COURSE_TEAM_PREVIEW) [True, False], # redirect_active (REDIRECT_TO_COURSEWARE_MICROFRONTEND) ) for user, is_course_staff, preview_active, redirect_active in old_mongo_combos: with override_waffle_flag(COURSEWARE_MICROFRONTEND_COURSE_TEAM_PREVIEW, preview_active): with override_waffle_flag(REDIRECT_TO_COURSEWARE_MICROFRONTEND, redirect_active): assert show_courseware_mfe_link(user, is_course_staff, old_course_key) is False # We've checked all old-style course keys now, so we can test only the # new ones going forward. Now we check combinations of waffle flags and # user permissions... with override_waffle_flag(COURSEWARE_MICROFRONTEND_COURSE_TEAM_PREVIEW, True): with override_waffle_flag(REDIRECT_TO_COURSEWARE_MICROFRONTEND, True): # (preview=on, redirect=on) # Global and Course Staff can see the link. self.assertTrue(show_courseware_mfe_link(global_staff_user, True, new_course_key)) self.assertTrue(show_courseware_mfe_link(global_staff_user, False, new_course_key)) self.assertTrue(show_courseware_mfe_link(regular_user, True, new_course_key)) # Regular users don't see the link. self.assertFalse(show_courseware_mfe_link(regular_user, False, new_course_key)) with override_waffle_flag(REDIRECT_TO_COURSEWARE_MICROFRONTEND, False): # (preview=on, redirect=off) # Global and Course Staff can see the link. self.assertTrue(show_courseware_mfe_link(global_staff_user, True, new_course_key)) self.assertTrue(show_courseware_mfe_link(global_staff_user, False, new_course_key)) self.assertTrue(show_courseware_mfe_link(regular_user, True, new_course_key)) # Regular users don't see the link. self.assertFalse(show_courseware_mfe_link(regular_user, False, new_course_key)) with override_waffle_flag(COURSEWARE_MICROFRONTEND_COURSE_TEAM_PREVIEW, False): with override_waffle_flag(REDIRECT_TO_COURSEWARE_MICROFRONTEND, True): # (preview=off, redirect=on) # Global staff see the link anyway self.assertTrue(show_courseware_mfe_link(global_staff_user, True, new_course_key)) self.assertTrue(show_courseware_mfe_link(global_staff_user, False, new_course_key)) # If redirect is active for their students, course staff see the link even # if preview=off. self.assertTrue(show_courseware_mfe_link(regular_user, True, new_course_key)) # Regular users don't see the link. self.assertFalse(show_courseware_mfe_link(regular_user, False, new_course_key)) with override_waffle_flag(REDIRECT_TO_COURSEWARE_MICROFRONTEND, False): # (preview=off, redirect=off) # Global staff see the link anyway self.assertTrue(show_courseware_mfe_link(global_staff_user, True, new_course_key)) self.assertTrue(show_courseware_mfe_link(global_staff_user, False, new_course_key)) # Course teams can NOT see the link because both rollout waffle flags are false. self.assertFalse(show_courseware_mfe_link(regular_user, True, new_course_key)) # Regular users don't see the link. self.assertFalse(show_courseware_mfe_link(regular_user, False, new_course_key)) @override_settings(LEARNING_MICROFRONTEND_URL='https://learningmfe.openedx.org') def test_url_generation(self): course_key = CourseKey.from_string("course-v1:OpenEdX+MFE+2020") section_key = UsageKey.from_string("block-v1:OpenEdX+MFE+2020+type@sequential+block@Introduction") unit_id = "block-v1:OpenEdX+MFE+2020+type@vertical+block@Getting_To_Know_You" assert get_microfrontend_url(course_key) == ( 'https://learningmfe.openedx.org' '/course/course-v1:OpenEdX+MFE+2020' ) assert get_microfrontend_url(course_key, section_key, '') == ( 'https://learningmfe.openedx.org' '/course/course-v1:OpenEdX+MFE+2020' '/block-v1:OpenEdX+MFE+2020+type@sequential+block@Introduction' ) assert get_microfrontend_url(course_key, section_key, unit_id) == ( 'https://learningmfe.openedx.org' '/course/course-v1:OpenEdX+MFE+2020' '/block-v1:OpenEdX+MFE+2020+type@sequential+block@Introduction' '/block-v1:OpenEdX+MFE+2020+type@vertical+block@Getting_To_Know_You' ) @patch.dict('django.conf.settings.FEATURES', {'ENABLE_COURSEWARE_MICROFRONTEND': True}) @ddt.ddt class MFERedirectTests(BaseViewsTestCase): MODULESTORE = TEST_DATA_SPLIT_MODULESTORE def _get_urls(self): lms_url = reverse( 'courseware_section', kwargs={ 'course_id': str(self.course_key), 'chapter': str(self.chapter.location.block_id), 'section': str(self.section2.location.block_id), } ) mfe_url = '{}/course/{}/{}'.format( settings.LEARNING_MICROFRONTEND_URL, self.course_key, self.section2.location ) return lms_url, mfe_url def test_learner_redirect(self): # learners will be redirected when the waffle flag is set lms_url, mfe_url = self._get_urls() with override_waffle_flag(REDIRECT_TO_COURSEWARE_MICROFRONTEND, True): assert self.client.get(lms_url).url == mfe_url def test_staff_no_redirect(self): lms_url, mfe_url = self._get_urls() # course staff will not redirect course_staff = UserFactory.create(is_staff=False) CourseStaffRole(self.course_key).add_users(course_staff) self.client.login(username=course_staff.username, password='test') assert self.client.get(lms_url).status_code == 200 with override_waffle_flag(REDIRECT_TO_COURSEWARE_MICROFRONTEND, True): assert self.client.get(lms_url).status_code == 200 # global staff will never be redirected self._create_global_staff_user() assert self.client.get(lms_url).status_code == 200 with override_waffle_flag(REDIRECT_TO_COURSEWARE_MICROFRONTEND, True): assert self.client.get(lms_url).status_code == 200 def test_exam_no_redirect(self): # exams will not redirect to the mfe, for the time being self.section2.is_time_limited = True self.store.update_item(self.section2, self.user.id) lms_url, mfe_url = self._get_urls() with override_waffle_flag(REDIRECT_TO_COURSEWARE_MICROFRONTEND, True): assert self.client.get(lms_url).status_code == 200
agpl-3.0
aceat64/Taskr
src/Model/Table/GiftsTable.php
2098
<?php namespace App\Model\Table; use Cake\ORM\Query; use Cake\ORM\RulesChecker; use Cake\ORM\Table; use Cake\Validation\Validator; /** * Gifts Model */ class GiftsTable extends Table { /** * Initialize method * * @param array $config The configuration for the Table. * @return void */ public function initialize(array $config) { $this->table('gifts'); $this->displayField('id'); $this->primaryKey('id'); $this->addBehavior('Timestamp'); $this->belongsTo('Tasks', [ 'foreignKey' => 'task_id' ]); $this->belongsTo('Users', [ 'foreignKey' => 'user_id' ]); } /** * Default validation rules. * * @param \Cake\Validation\Validator $validator instance * @return \Cake\Validation\Validator */ public function validationDefault(Validator $validator) { $validator ->add('id', 'valid', ['rule' => 'numeric']) ->allowEmpty('id', 'create') ->add('task_id', 'valid', ['rule' => 'numeric']) ->requirePresence('task_id', 'create') ->notEmpty('task_id') ->add('user_id', 'valid', ['rule' => 'numeric']) ->requirePresence('user_id', 'create') ->notEmpty('user_id') ->add('credits', 'valid', ['rule' => 'decimal']) ->requirePresence('credits', 'create') ->notEmpty('credits') ->add('points', 'valid', ['rule' => 'numeric']) ->requirePresence('points', 'create') ->notEmpty('points'); return $validator; } /** * Returns a rules checker object that will be used for validating * application integrity. * * @param \Cake\ORM\RulesChecker $rules The rules object to be modified. * @return \Cake\ORM\RulesChecker */ public function buildRules(RulesChecker $rules) { $rules->add($rules->existsIn(['task_id'], 'Tasks')); $rules->add($rules->existsIn(['user_id'], 'Users')); return $rules; } }
agpl-3.0
klette/comics
comics/comics/perrybiblefellowship.py
393
from comics.aggregator.crawler import CrawlerBase from comics.meta.base import MetaBase class Meta(MetaBase): name = 'The Perry Bible Fellowship' language = 'en' url = 'http://www.pbfcomics.com/' active = False start_date = '2001-01-01' rights = 'Nicholas Gurewitch' class Crawler(CrawlerBase): def crawl(self, pub_date): pass # Comic no longer published
agpl-3.0